text
stringlengths
3
1.05M
import glob import optparse import os.path import subprocess import sys def main(): """ Repeatedly run GUI functional tests. """ parser = optparse.OptionParser() parser.add_option('-t', '--trials', type='int', default=100, help='# trials to attempt') parser.add_option('-n', '--nonose', action='store_true', help='if present, run outside of nose') options, files = parser.parse_args() args = ['-v'] if options.nonose: args.append('--nonose') stop = 'STOP' if os.path.exists(stop): os.remove(stop) logfile = open('stressit.log', 'w') for trial in range(options.trials): if os.path.exists(stop): break if sys.platform == 'win32': msg = 'Trial %s:' % (trial+1) else: avgs = os.getloadavg() msg = 'Trial %s: %.2f, %.2f, %.2f' \ % (trial+1, avgs[0], avgs[1], avgs[2]) print msg logfile.write('\n'+msg+'\n') if not files: files = sorted(glob.glob('test_*.py')) for test_script in files: msg = ' Running %s' % test_script print msg logfile.write(msg+'\n') logfile.flush() cmd = ['python', test_script] cmd.extend(args) status = subprocess.call(cmd, stdout=logfile, stderr=subprocess.STDOUT) if status: msg = ' exit status %s' % status print msg logfile.write(msg+'\n') sys.exit(status) logfile.close() if __name__ == '__main__': main()
import { swapItems } from '../../toolFunction'; const changePayListCols = (state, action) => { let {items, status} = action; if (items) { return Object.assign({}, state, { changePayListCols: items }); } else if (status) { console.log('changePayListCols:', status); return state; } return state; }; const changePayList = (state, action) => { let {items, status} = action; if (items) { return Object.assign({}, state, { changePayList: items }); } else if (status) { console.log('changePayList:', status); return state; } return state; }; const checkList = (state, action) => { let {isCheckAll, checked, index} = action; let [...items] = state.changePayList; if (isCheckAll) { for (let item of items) { item.checked = checked; } } else { items[index].checked = checked; } return Object.assign({}, state, {changePayList: items}); }; const swapCol = (state, action) => { let {key1, key2} = action; let [...cols] = state.changePayListCols; return Object.assign({}, state, { changePayListCols: swapItems(cols, key1, key2)} ); }; const modal = (state, action) => { return Object.assign({}, state, {showModal: action.isShow}); }; const modalCheckChange = (state, action) => { let [...cols2] = state.changePayListCols; for (let col of cols2) { if (col.title == action.name){ col.hide = !col.hide; break; } } return Object.assign({}, state, {changePayListCols: cols2}); }; const initState = { changePayListCols: [], changePayList: [], showModal: false, }; const changePayListReducer = (state = initState, action) => { switch (action.type) { case 'payChangePayListCols': return changePayListCols(state, action); case 'payChangePayList': return changePayList(state, action); case "payChangePayCheckList": return checkList(state, action); case "receiveChangeReceiveSwapCol": return swapCol(state, action); case "payChangePaySortCol": return state; case "payChangePayModal": return modal(state, action); case "payChangePayModalCheckChange": return modalCheckChange(state, action); default: return state; } }; export default changePayListReducer;
from scipy.stats import norm from statsmodels.tsa.holtwinters import ExponentialSmoothing from .base import BaseNewsvendor, ClassicMixin from ..utils.validation import check_cu_co, formate_hyperparameter from sklearn.utils.validation import check_array from sklearn.metrics import mean_absolute_error import numpy as np class HoltWintersNewsvendor(BaseNewsvendor, ClassicMixin): """ A newsvendor model based on Holt-Winters' exponential smoothing forecaster The next order quantity q is calculatad by: q = f + MAE*1.25*z(alpha), where - f is the forecast for the demand in the next period, calculated by Holt-Winters' exponential smoothing, - MAE is the Mean Squared Error between the true demand of y_train and the values fitted by the Exponential Smoothing model, - z(.) is the inverse of standard normal distribution, - alpha is the service level calculated by cu/(cu+co) Parameters ---------- cu : {array-like of shape (n_outputs,), Number or None}, default=None The underage costs per unit. If None, then underage costs are one for each target variable co : {array-like of shape (n_outputs,), Number or None}, default=None The overage costs per unit. If None, then overage costs are one for each target variable trend : {"add", "mul", "additive", "multiplicative", None}, default=None Type of trend component. damped : bool, optional (default=None) Should the trend component be damped. seasonal : {"add", "mul", "additive", "multiplicative", None}, default=None Type of seasonal component. seasonal_periods : int, default=None The number of periods in a complete seasonal cycle, e.g., 4 for quarterly data or 7 for daily data with a weekly cycle. smoothing_level : float, optional The alpha value of the simple exponential smoothing, if the value is set then this value will be used as the value. smoothing_slope : float, optional The beta value of the Holt's trend method, if the value is set then this value will be used as the value. smoothing_seasonal : float, optional The gamma value of the holt winters seasonal method, if the value is set then this value will be used as the value. damping_slope : float, optional The phi value of the damped method, if the value is set then this value will be used as the value. optimized : bool, optional Estimate model parameters by maximizing the log-likelihood use_boxcox : {True, False, 'log', float}, optional Should the Box-Cox transform be applied to the data first? If 'log' then apply the log. If float then use lambda equal to float. remove_bias : bool, optional Remove bias from forecast values and fitted values by enforcing that the average residual is equal to zero. use_basinhopping : bool, optional Using Basin Hopping optimizer to find optimal values Attributes ---------- n_outputs_ : int The number of outputs when ``fit`` is performed. cu_ : ndarray, shape (n_outputs,) Validated underage costs. co_ : ndarray, shape (n_outputs,) Validated overage costs. Notes ----- References ---------- .. [1] Hyndman, Rob J., and George Athanasopoulos. Forecasting: principles and practice. OTexts, 2014. Examples -------- >>> from ddop.datasets.load_datasets import load_data >>> from ddop.newsvendor import HoltWintersNewsvendor >>> from sklearn.model_selection import train_test_split >>> data = load_data("yaz_steak.csv") >>> Y = data.iloc[:,24] >>> cu,co = 15,10 >>> Y_train, Y_test = train_test_split(Y, test_size=0.25, shuffle=False, random_state=1) >>> mdl = HoltWintersNewsvendor(cu, co, 'add', False, 'add',7) >>> mdl.fit(Y_train) >>> mdl.score(Y_test) TODO: Add result """ def __init__( self, cu=None, co=None, trend=None, damped=False, seasonal=None, seasonal_periods=None, smoothing_level=None, smoothing_slope=None, smoothing_seasonal=None, damping_slope=None, optimized=True, use_boxcox=False, remove_bias=False, use_basinhopping=False ): self.cu = cu self.co = co self.trend = trend self.damped = damped self.seasonal = seasonal self.seasonal_periods = seasonal_periods self.smoothing_level = smoothing_level self.optimized = optimized self.smoothing_slope = smoothing_slope self.smoothing_seasonal = smoothing_seasonal self.damping_slope = damping_slope self.use_boxcox = use_boxcox self.remove_bias = remove_bias self.use_basinhopping = use_basinhopping super().__init__( cu=cu, co=co) def fit(self, y, X=None): """Fit the model to the training data y. Parameters ---------- y : array-like of shape (n_samples, n_outputs) The target values. X : array-like of shape (n_samples, n_features), optional (default=None) Exogenous variables are ignored Returns ---------- self : HoltWintersNewsvendor Fitted estimator """ y = check_array(y, ensure_2d=False) if y.ndim == 1: y = np.reshape(y, (-1, 1)) self.n_outputs_ = y.shape[1] # Check and format under- and overage costs self.cu_, self.co_ = check_cu_co(self.cu, self.co, self.n_outputs_) # Formate hyperparameter self.trend = formate_hyperparameter(self.trend, "trend", self.n_outputs_) self.damped = formate_hyperparameter(self.damped, "damped", self.n_outputs_) self.seasonal = formate_hyperparameter(self.seasonal, "seasonal", self.n_outputs_) self.seasonal_periods = formate_hyperparameter(self.seasonal_periods, "seasonal_periods", self.n_outputs_) self.smoothing_level = formate_hyperparameter(self.smoothing_level, "smoothing_level", self.n_outputs_) self.optimized = formate_hyperparameter(self.optimized, "optimized", self.n_outputs_) self.smoothing_slope = formate_hyperparameter(self.smoothing_slope, "smoothing_slope", self.n_outputs_) self.smoothing_seasonal = formate_hyperparameter(self.smoothing_seasonal, "smoothing_seasonal", self.n_outputs_) self.damping_slope = formate_hyperparameter(self.damping_slope, "damping_slope", self.n_outputs_) self.use_boxcox = formate_hyperparameter(self.use_boxcox, "use_boxcox", self.n_outputs_) self.remove_bias = formate_hyperparameter(self.remove_bias, "remove_bias", self.n_outputs_) self.use_basinhopping = formate_hyperparameter(self.use_basinhopping, "use_basinhopping", self.n_outputs_) forecasters = [ExponentialSmoothing( endog=y[:, i], trend=self.trend[i], damped=self.damped[i], seasonal=self.seasonal[i], seasonal_periods=self.seasonal_periods[i]) for i in range(self.n_outputs_)] fitted_forecasters = [forecasters[i].fit( smoothing_level=self.smoothing_level[i], optimized=self.optimized[i], smoothing_slope=self.smoothing_slope[i], smoothing_seasonal=self.smoothing_seasonal[i], damping_slope=self.damping_slope[i], use_boxcox=self.use_boxcox[i], remove_bias=self.remove_bias[i], use_basinhopping=self.use_basinhopping[i]) for i in range(self.n_outputs_)] mae = np.array([mean_absolute_error(y[:, i], fitted_forecasters[i].fittedvalues) for i in range(self.n_outputs_)]) z_alpha = np.array([norm.ppf(self.cu_[i]/(self.co_[i]+self.cu_[i])) for i in range(self.n_outputs_)]) self.safety_buffer_ = mae*1.25*z_alpha self.forecasters_ = fitted_forecasters return self def predict(self, n=1): """Predict n time-steps Parameters ---------- n : int, default=1 The number of steps to predict ahead Returns ---------- y : array-like of shape (n, n_outputs) The predicted values """ forecasts = np.array([forecaster.forecast(n) for forecaster in self.forecasters_]).T pred = forecasts+self.safety_buffer_ return pred
'use strict' module.exports = { verbose: true, preset: 'ts-jest', testEnvironment: 'node', collectCoverage: true, collectCoverageFrom: ['./src/**/*.ts'], coverageReporters: ['json', 'lcov', 'text'], clearMocks: false, coverageThreshold: { global: { statements: 90, functions: 90, branches: 90, lines: 90 } }, reporters: ['jest-junit', 'default'] }
(function(){function b(){return b}function c(b,d){var e=c.resolve(b),f=c.modules[e];if(!f)throw new Error('failed to require "'+b+'" from '+d);return f.exports||(f.exports={},f.call(f.exports,f,f.exports,c.relative(e),a)),f.exports}var a=this;c.modules={},c.resolve=function(a){var b=a,d=a+".js",e=a+"/index.js";return c.modules[d]&&d||c.modules[e]&&e||b},c.register=function(a,b){c.modules[a]=b},c.relative=function(a){return function(d){if("debug"==d)return b;if("."!=d.charAt(0))return c(d);var e=a.split("/"),f=d.split("/");e.pop();for(var g=0;g<f.length;g++){var h=f[g];".."==h?e.pop():"."!=h&&e.push(h)}return c(e.join("/"),a)}},c.register("index.js",function(a,b,c,d){function l(a){for(var b=0;b<a.length;b++)a[b]=Math.round(a[b])}var e=c("./conversions"),f=function(){return new k};for(var g in e){f[g+"Raw"]=function(a){return function(b){return typeof b=="number"&&(b=Array.prototype.slice.call(arguments)),e[a](b)}}(g);var h=/(\w+)2(\w+)/.exec(g),i=h[1],j=h[2];f[i]=f[i]||{},f[i][j]=f[g]=function(a){return function(b){typeof b=="number"&&(b=Array.prototype.slice.call(arguments));var c=e[a](b);return typeof c=="string"||c===undefined?c:(l(c),c)}}(g)}var k=function(){this.space="rgb",this.convs={rgb:[0,0,0]}};k.prototype.routeSpace=function(a,b){var c=b[0];return c===undefined?this.getValues(a):(typeof c=="number"&&(c=Array.prototype.slice.call(b)),this.setValues(a,c))},k.prototype.setValues=function(a,b){return this.space=a,this.convs={},this.convs[a]=b,this},k.prototype.getValues=function(a){var b=this.convs[a];if(!b){var c=this.space,d=this.convs[c];b=f[c][a](d),this.convs[a]=b}else l(b);return b},["rgb","hsl","hsv","cmyk","keyword"].forEach(function(a){k.prototype[a]=function(b){return this.routeSpace(a,arguments)}}),a.exports=f}),c.register("conversions.js",function(a,b,c,d){function e(a){var b=a[0]/255,c=a[1]/255,d=a[2]/255,e=Math.min(b,c,d),f=Math.max(b,c,d),g=f-e,h,i,j;return f==e?h=0:b==f?h=(c-d)/g:c==f?h=2+(d-b)/g:d==f&&(h=4+(b-c)/g),h=Math.min(h*60,360),h<0&&(h+=360),j=(e+f)/2,f==e?i=0:j<=.5?i=g/(f+e):i=g/(2-f-e),[h,i*100,j*100]}function f(a){var b=a[0],c=a[1],d=a[2],e=Math.min(b,c,d),f=Math.max(b,c,d),g=f-e,h,i,j;return f==0?i=0:i=g/f*1e3/10,f==e?h=0:b==f?h=(c-d)/g:c==f?h=2+(d-b)/g:d==f&&(h=4+(b-c)/g),h=Math.min(h*60,360),h<0&&(h+=360),j=f/255*1e3/10,[h,i,j]}function g(a){var b=a[0]/255,c=a[1]/255,d=a[2]/255,e,f,g,h;return h=Math.min(1-b,1-c,1-d),e=(1-b-h)/(1-h),f=(1-c-h)/(1-h),g=(1-d-h)/(1-h),[e*100,f*100,g*100,h*100]}function h(a){return G[JSON.stringify(a)]}function i(a){var b=a[0]/255,c=a[1]/255,d=a[2]/255;b=b>.04045?Math.pow((b+.055)/1.055,2.4):b/12.92,c=c>.04045?Math.pow((c+.055)/1.055,2.4):c/12.92,d=d>.04045?Math.pow((d+.055)/1.055,2.4):d/12.92;var e=b*.4124+c*.3576+d*.1805,f=b*.2126+c*.7152+d*.0722,g=b*.0193+c*.1192+d*.9505;return[e*100,f*100,g*100]}function j(a){var b=i(a),c=b[0],d=b[1],e=b[2],f,g,h;return c/=95.047,d/=100,e/=108.883,c=c>.008856?Math.pow(c,1/3):7.787*c+16/116,d=d>.008856?Math.pow(d,1/3):7.787*d+16/116,e=e>.008856?Math.pow(e,1/3):7.787*e+16/116,f=116*d-16,g=500*(c-d),h=200*(d-e),[f,g,h]}function k(a){var b=a[0]/360,c=a[1]/100,d=a[2]/100,e,f,g,h,i;if(c==0)return i=d*255,[i,i,i];d<.5?f=d*(1+c):f=d+c-d*c,e=2*d-f,h=[0,0,0];for(var j=0;j<3;j++)g=b+1/3*-(j-1),g<0&&g++,g>1&&g--,6*g<1?i=e+(f-e)*6*g:2*g<1?i=f:3*g<2?i=e+(f-e)*(2/3-g)*6:i=e,h[j]=i*255;return h}function l(a){var b=a[0],c=a[1]/100,d=a[2]/100,e,f;return d*=2,c*=d<=1?d:2-d,f=(d+c)/2,e=2*c/(d+c),[b,e*100,f*100]}function m(a){return g(k(a))}function n(a){return h(k(a))}function o(a){var b=a[0]/60,c=a[1]/100,d=a[2]/100,e=Math.floor(b)%6,f=b-Math.floor(b),g=255*d*(1-c),h=255*d*(1-c*f),i=255*d*(1-c*(1-f)),d=255*d;switch(e){case 0:return[d,i,g];case 1:return[h,d,g];case 2:return[g,d,i];case 3:return[g,h,d];case 4:return[i,g,d];case 5:return[d,g,h]}}function p(a){var b=a[0],c=a[1]/100,d=a[2]/100,e,f;return f=(2-c)*d,e=c*d,e/=f<=1?f:2-f,f/=2,[b,e*100,f*100]}function q(a){return g(o(a))}function r(a){return h(o(a))}function s(a){var b=a[0]/100,c=a[1]/100,d=a[2]/100,e=a[3]/100,f,g,h;return f=1-Math.min(1,b*(1-e)+e),g=1-Math.min(1,c*(1-e)+e),h=1-Math.min(1,d*(1-e)+e),[f*255,g*255,h*255]}function t(a){return e(s(a))}function u(a){return f(s(a))}function v(a){return h(s(a))}function w(a){var b=a[0]/100,c=a[1]/100,d=a[2]/100,e,f,g;return e=b*3.2406+c*-1.5372+d*-0.4986,f=b*-0.9689+c*1.8758+d*.0415,g=b*.0557+c*-0.204+d*1.057,e=e>.0031308?1.055*Math.pow(e,1/2.4)-.055:e*=12.92,f=f>.0031308?1.055*Math.pow(f,1/2.4)-.055:f*=12.92,g=g>.0031308?1.055*Math.pow(g,1/2.4)-.055:g*=12.92,e=e<0?0:e,f=f<0?0:f,g=g<0?0:g,[e*255,f*255,g*255]}function x(a){var b=a[0],c=a[1],d=a[2],e,f,g;return b/=95.047,c/=100,d/=108.883,b=b>.008856?Math.pow(b,1/3):7.787*b+16/116,c=c>.008856?Math.pow(c,1/3):7.787*c+16/116,d=d>.008856?Math.pow(d,1/3):7.787*d+16/116,e=116*c-16,f=500*(b-c),g=200*(c-d),[e,f,g]}function y(a){var b=a[0],c=a[1],d=a[2],e,f,g,h;return b<=8?(f=b*100/903.3,h=7.787*(f/100)+16/116):(f=100*Math.pow((b+16)/116,3),h=Math.pow(f/100,1/3)),e=e/95.047<=.008856?e=95.047*(c/500+h-16/116)/7.787:95.047*Math.pow(c/500+h,3),g=g/108.883<=.008859?g=108.883*(h-d/200-16/116)/7.787:108.883*Math.pow(h-d/200,3),[e,f,g]}function z(a){return F[a]}function A(a){return e(z(a))}function B(a){return f(z(a))}function C(a){return g(z(a))}function D(a){return j(z(a))}function E(a){return i(z(a))}a.exports={rgb2hsl:e,rgb2hsv:f,rgb2cmyk:g,rgb2keyword:h,rgb2xyz:i,rgb2lab:j,hsl2rgb:k,hsl2hsv:l,hsl2cmyk:m,hsl2keyword:n,hsv2rgb:o,hsv2hsl:p,hsv2cmyk:q,hsv2keyword:r,cmyk2rgb:s,cmyk2hsl:t,cmyk2hsv:u,cmyk2keyword:v,keyword2rgb:z,keyword2hsl:A,keyword2hsv:B,keyword2cmyk:C,keyword2lab:D,keyword2xyz:E,xyz2rgb:w,xyz2lab:x,lab2xyz:y};var F={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]},G={};for(var H in F)G[JSON.stringify(F[H])]=H}),colorConvert=c("index.js")})();
/*--------------------------------------------------------------------------------------------- * Copyright (c) Microsoft Corporation. All rights reserved. * Licensed under the MIT License. See License.txt in the project root for license information. *--------------------------------------------------------------------------------------------*/ var _a; import { TimeoutTimer } from '../../../base/common/async'; import * as strings from '../../../base/common/strings'; import { LineTokens } from '../../common/core/lineTokens'; import { TokenizationRegistry } from '../../common/modes'; import { RenderLineInput, renderViewLine2 as renderViewLine } from '../../common/viewLayout/viewLineRenderer'; import { ViewLineRenderingData } from '../../common/viewModel/viewModel'; import { MonarchTokenizer } from '../common/monarch/monarchLexer'; const ttPolicy = (_a = window.trustedTypes) === null || _a === void 0 ? void 0 : _a.createPolicy('standaloneColorizer', { createHTML: value => value }); export class Colorizer { static colorizeElement(themeService, modeService, domNode, options) { options = options || {}; let theme = options.theme || 'vs'; let mimeType = options.mimeType || domNode.getAttribute('lang') || domNode.getAttribute('data-lang'); if (!mimeType) { console.error('Mode not detected'); return Promise.resolve(); } themeService.setTheme(theme); let text = domNode.firstChild ? domNode.firstChild.nodeValue : ''; domNode.className += ' ' + theme; let render = (str) => { var _a; const trustedhtml = (_a = ttPolicy === null || ttPolicy === void 0 ? void 0 : ttPolicy.createHTML(str)) !== null && _a !== void 0 ? _a : str; domNode.innerHTML = trustedhtml; }; return this.colorize(modeService, text || '', mimeType, options).then(render, (err) => console.error(err)); } static colorize(modeService, text, mimeType, options) { let tabSize = 4; if (options && typeof options.tabSize === 'number') { tabSize = options.tabSize; } if (strings.startsWithUTF8BOM(text)) { text = text.substr(1); } let lines = strings.splitLines(text); let language = modeService.getModeId(mimeType); if (!language) { return Promise.resolve(_fakeColorize(lines, tabSize)); } // Send out the event to create the mode modeService.triggerMode(language); const tokenizationSupport = TokenizationRegistry.get(language); if (tokenizationSupport) { return _colorize(lines, tabSize, tokenizationSupport); } const tokenizationSupportPromise = TokenizationRegistry.getPromise(language); if (tokenizationSupportPromise) { // A tokenizer will be registered soon return new Promise((resolve, reject) => { tokenizationSupportPromise.then(tokenizationSupport => { _colorize(lines, tabSize, tokenizationSupport).then(resolve, reject); }, reject); }); } return new Promise((resolve, reject) => { let listener = null; let timeout = null; const execute = () => { if (listener) { listener.dispose(); listener = null; } if (timeout) { timeout.dispose(); timeout = null; } const tokenizationSupport = TokenizationRegistry.get(language); if (tokenizationSupport) { _colorize(lines, tabSize, tokenizationSupport).then(resolve, reject); return; } resolve(_fakeColorize(lines, tabSize)); }; // wait 500ms for mode to load, then give up timeout = new TimeoutTimer(); timeout.cancelAndSet(execute, 500); listener = TokenizationRegistry.onDidChange((e) => { if (e.changedLanguages.indexOf(language) >= 0) { execute(); } }); }); } static colorizeLine(line, mightContainNonBasicASCII, mightContainRTL, tokens, tabSize = 4) { const isBasicASCII = ViewLineRenderingData.isBasicASCII(line, mightContainNonBasicASCII); const containsRTL = ViewLineRenderingData.containsRTL(line, isBasicASCII, mightContainRTL); let renderResult = renderViewLine(new RenderLineInput(false, true, line, false, isBasicASCII, containsRTL, 0, tokens, [], tabSize, 0, 0, 0, 0, -1, 'none', false, false, null)); return renderResult.html; } static colorizeModelLine(model, lineNumber, tabSize = 4) { let content = model.getLineContent(lineNumber); model.forceTokenization(lineNumber); let tokens = model.getLineTokens(lineNumber); let inflatedTokens = tokens.inflate(); return this.colorizeLine(content, model.mightContainNonBasicASCII(), model.mightContainRTL(), inflatedTokens, tabSize); } } function _colorize(lines, tabSize, tokenizationSupport) { return new Promise((c, e) => { const execute = () => { const result = _actualColorize(lines, tabSize, tokenizationSupport); if (tokenizationSupport instanceof MonarchTokenizer) { const status = tokenizationSupport.getLoadStatus(); if (status.loaded === false) { status.promise.then(execute, e); return; } } c(result); }; execute(); }); } function _fakeColorize(lines, tabSize) { let html = []; const defaultMetadata = ((0 /* None */ << 11 /* FONT_STYLE_OFFSET */) | (1 /* DefaultForeground */ << 14 /* FOREGROUND_OFFSET */) | (2 /* DefaultBackground */ << 23 /* BACKGROUND_OFFSET */)) >>> 0; const tokens = new Uint32Array(2); tokens[0] = 0; tokens[1] = defaultMetadata; for (let i = 0, length = lines.length; i < length; i++) { let line = lines[i]; tokens[0] = line.length; const lineTokens = new LineTokens(tokens, line); const isBasicASCII = ViewLineRenderingData.isBasicASCII(line, /* check for basic ASCII */ true); const containsRTL = ViewLineRenderingData.containsRTL(line, isBasicASCII, /* check for RTL */ true); let renderResult = renderViewLine(new RenderLineInput(false, true, line, false, isBasicASCII, containsRTL, 0, lineTokens, [], tabSize, 0, 0, 0, 0, -1, 'none', false, false, null)); html = html.concat(renderResult.html); html.push('<br/>'); } return html.join(''); } function _actualColorize(lines, tabSize, tokenizationSupport) { let html = []; let state = tokenizationSupport.getInitialState(); for (let i = 0, length = lines.length; i < length; i++) { let line = lines[i]; let tokenizeResult = tokenizationSupport.tokenize2(line, true, state, 0); LineTokens.convertToEndOffset(tokenizeResult.tokens, line.length); let lineTokens = new LineTokens(tokenizeResult.tokens, line); const isBasicASCII = ViewLineRenderingData.isBasicASCII(line, /* check for basic ASCII */ true); const containsRTL = ViewLineRenderingData.containsRTL(line, isBasicASCII, /* check for RTL */ true); let renderResult = renderViewLine(new RenderLineInput(false, true, line, false, isBasicASCII, containsRTL, 0, lineTokens.inflate(), [], tabSize, 0, 0, 0, 0, -1, 'none', false, false, null)); html = html.concat(renderResult.html); html.push('<br/>'); state = tokenizeResult.endState; } return html.join(''); }
# import pytest # # from factories.factory_pipelines import OperationRunFactory # from lifecycles.task_runs import TaskRunLifeCycle # from lifecycles.pipelines import PipelineLifeCycle # from pipelines.celery_task import ClassBasedTask, OperationTask # from polyaxon.celery_api import celery_app # from tests.base.case import BaseTest # # TODO # # @pytest.mark.pipelines_mark # class TestOperationTask(BaseTest): # def setUp(self): # # self.operation_run = OperationRunFactory() # self.pipeline_run = self.operation_run.pipeline_run # # Manually set status to scheduled # self.operation_run.on_scheduled() # return super().setUp() # # def test_task_without_operation_run_raises(self): # @celery_app.task(base=OperationTask, shared=False) # def dummy_task(): # return # # with self.assertRaises(TypeError): # dummy_task.apply_async() # # def test_task_with_operation_run_succeeds(self): # @celery_app.task(base=OperationTask, shared=False) # def dummy_task(operation_run_id): # return # # kwargs = {'operation_run_id': self.operation_run.id} # dummy_task.apply_async(kwargs=kwargs) # self.operation_run.refresh_from_db() # assert self.operation_run.succeeded is True # assert set(self.operation_run.statuses.values_list('status', flat=True)) == { # TaskRunLifeCycle.CREATED, # TaskRunLifeCycle.SCHEDULED, # TaskRunLifeCycle.RUNNING, # TaskRunLifeCycle.SUCCEEDED, # } # self.pipeline_run.refresh_from_db() # assert self.operation_run.pipeline_run.last_status == PipelineLifeCycle.DONE # assert set(self.operation_run.pipeline_run.statuses.values_list('status', flat=True)) == { # PipelineLifeCycle.CREATED, # PipelineLifeCycle.SCHEDULED, # PipelineLifeCycle.RUNNING, # PipelineLifeCycle.DONE, # } # # def test_task_with_error_fails(self): # @celery_app.task(base=OperationTask, shared=False) # def raising_task(operation_run_id): # raise KeyError # # kwargs = {'operation_run_id': self.operation_run.id} # raising_task.apply_async(kwargs=kwargs) # self.operation_run.refresh_from_db() # assert self.operation_run.failed is True # assert set(self.operation_run.statuses.values_list('status', flat=True)) == { # TaskRunLifeCycle.CREATED, # TaskRunLifeCycle.SCHEDULED, # TaskRunLifeCycle.RUNNING, # TaskRunLifeCycle.FAILED, # } # self.pipeline_run.refresh_from_db() # assert self.operation_run.pipeline_run.last_status == PipelineLifeCycle.DONE # assert set(self.operation_run.pipeline_run.statuses.values_list('status', flat=True)) == { # PipelineLifeCycle.CREATED, # PipelineLifeCycle.SCHEDULED, # PipelineLifeCycle.RUNNING, # PipelineLifeCycle.DONE, # } # # def test_task_retries_for_specified_exception(self): # class RetryTask(ClassBasedTask): # retry_for = (KeyError, ) # # @staticmethod # def _run(task_bind, *args, **kwargs): # raise KeyError # # @celery_app.task(base=OperationTask, bind=True, shared=False) # def retry_task(task_bind, operation_run_id): # assert task_bind.max_retries == 2 # assert task_bind.countdown == 0 # RetryTask.run(task_bind=task_bind, operation_run_id=operation_run_id) # # # Add retries and count to the operation # self.operation_run.operation.max_retries = 2 # self.operation_run.operation.retry_delay = 0 # self.operation_run.operation.save() # # kwargs = {'operation_run_id': self.operation_run.id} # retry_task.apply_async(kwargs=kwargs) # self.operation_run.refresh_from_db() # assert self.operation_run.last_status == TaskRunLifeCycle.RETRYING # assert set(self.operation_run.statuses.values_list('status', flat=True)) == { # TaskRunLifeCycle.CREATED, # TaskRunLifeCycle.SCHEDULED, # TaskRunLifeCycle.RUNNING, # TaskRunLifeCycle.RETRYING, # } # self.pipeline_run.refresh_from_db() # assert self.operation_run.pipeline_run.last_status == PipelineLifeCycle.RUNNING # assert set(self.operation_run.pipeline_run.statuses.values_list('status', flat=True)) == { # PipelineLifeCycle.CREATED, # PipelineLifeCycle.SCHEDULED, # PipelineLifeCycle.RUNNING, # }
import mimetypes import os from ast import literal_eval import requests class Api(object): def __init__(self, url, private_token, proxy=None): self.url = url mimetypes.add_type('text/plain', '.log') mimetypes.add_type('application/octet-stream', '') self.request = requests.Session() self.request.headers = {'Authorization': 'PrivateToken ' + private_token} self.request.proxies = literal_eval(proxy) if proxy else {} # AutoTests def create_autotest(self, json): response = self.request.post( self.url + '/api/v2/autoTests', json=json ) print(f"Autotest: {json['name']}") if response.status_code != 201: raise Exception(f"Create autotest error: {response.json()['error']['key']}") print('\nCreate autotest passed!') return response.json()['id'] def link_autotest(self, autotest_id, workitem_id): response = self.request.post( f'{self.url}/api/v2/autoTests/{autotest_id}/workItems', json={'id': workitem_id} ) if response.status_code == 204: print('Link autoTest with workItems passed!') else: print(f"Link autoTest with workItems error: {response.json()['error']['key']}") def get_autotest(self, external_id, project_id): response = self.request.get( f'{self.url}/api/v2/autoTests?projectId={project_id}&externalId={external_id}' ) if response.status_code != 200: raise Exception(f"Get autoTest error: {response.json()['error']['key']}") print('\nGet autoTest passed!') return response def update_autotest(self, json): response = self.request.put( self.url + '/api/v2/autoTests', json=json ) print(f"AutoTest: {json['name']}") if response.status_code == 204: print('Update passed!') else: raise Exception(f"Update error: {response.json()['error']['key']}") # TestRuns def create_testrun(self, json): response = self.request.post( self.url + '/api/v2/testRuns', json=json ) if response.status_code != 201: raise Exception(f"Create testRun error: {response.json()['error']['key']}") print('Create testRun passed!') return response.json()['id'] def get_testrun(self, testrun_id): response = self.request.get( f'{self.url}/api/v2/testRuns/{testrun_id}' ) if response.status_code != 200: raise Exception(f"Get testRun error: {response.json()['error']['key']}") print('Get testRun passed!') return response.json()['projectId'], response.json()['testResults'] def set_results_for_testrun(self, testrun_id, json): response = self.request.post( f'{self.url}/api/v2/testRuns/{testrun_id}/testResults', json=json ) if response.status_code == 200: print('Set results passed!') else: raise Exception(f"Set results error: {response.json()['error']['key']}") def testrun_activity(self, testrun_id, action): response = self.request.post( f'{self.url}/api/v2/testRuns/{testrun_id}/{action}' ) if response.status_code == 204: print(f'TestRun {action} passed!') else: raise Exception(f"TestRun {action} error: {response.json()['error']['key']}") def load_attachment(self, file): response = self.request.post( f'{self.url}/api/Attachments', files={ 'file': (os.path.basename(file.name), file, mimetypes.guess_type(file.name)[0]) } ) if response.status_code == 201: print(f'Attachment {file.name} loaded!') return response.json()['id'] else: print(f"Attachment {file.name} error: {response.json()['error']['key']}") return None
#!/usr/bin/env python """ Freight ======= A deploy service. :copyright: (c) 2015 Functional Software Inc. :license: Apache 2.0, see LICENSE for more details. """ from __future__ import absolute_import import os.path from setuptools import setup, find_packages # Hack to prevent stupid "TypeError: 'NoneType' object is not callable" error # in multiprocessing/util.py _exit_function when running `python # setup.py test` (see # http://www.eby-sarna.com/pipermail/peak/2010-May/003357.html) for m in ('multiprocessing', 'billiard'): try: __import__(m) except ImportError: pass ROOT = os.path.realpath(os.path.join(os.path.dirname(__file__))) with open('requirements-test.txt') as file: tests_require = file.read().splitlines() with open('requirements.txt') as file: install_requires = file.read().splitlines() setup( name='freight', version='0.0.0', author='David Cramer', author_email='dcramer@gmail.com', url='https://github.com/getsentry/freight', description='A deployment service', long_description=open('README.rst').read(), packages=find_packages(exclude=['tests']), zip_safe=False, install_requires=install_requires, extras_require={ 'test': tests_require, }, license='Apache 2.0', include_package_data=True, classifiers=[ 'Intended Audience :: Developers', 'Intended Audience :: System Administrators', 'Operating System :: OS Independent', 'Topic :: Software Development' ], )
// DO NOT EDIT! This test has been generated by tools/gentest.py. // OffscreenCanvas test in a worker:2d.pattern.paint.norepeat.coord2 // Description: // Note: importScripts("/resources/testharness.js"); importScripts("/2dcontext/resources/canvas-tests.js"); var t = async_test(""); var t_pass = t.done.bind(t); var t_fail = t.step_func(function(reason) { throw reason; }); t.step(function() { var offscreenCanvas = new OffscreenCanvas(100, 50); var ctx = offscreenCanvas.getContext('2d'); var promise = new Promise(function(resolve, reject) { var xhr = new XMLHttpRequest(); xhr.open("GET", '/images/green.png'); xhr.responseType = 'blob'; xhr.send(); xhr.onload = function() { resolve(xhr.response); }; }); promise.then(function(response) { createImageBitmap(response).then(bitmap => { var pattern = ctx.createPattern(bitmap, 'no-repeat'); ctx.fillStyle = pattern; ctx.fillRect(0, 0, 50, 50); ctx.fillStyle = '#f00'; ctx.fillRect(50, 0, 50, 50); ctx.fillStyle = pattern; ctx.translate(50, 0); ctx.fillRect(-50, 0, 100, 50); _assertPixel(offscreenCanvas, 1,1, 0,255,0,255, "1,1", "0,255,0,255"); _assertPixel(offscreenCanvas, 98,1, 0,255,0,255, "98,1", "0,255,0,255"); _assertPixel(offscreenCanvas, 1,48, 0,255,0,255, "1,48", "0,255,0,255"); _assertPixel(offscreenCanvas, 98,48, 0,255,0,255, "98,48", "0,255,0,255"); }, t_fail); }).then(t_pass, t_fail); }); done();
import React from 'react'; import Pane from '../elements/Pane'; /** * Pane for creating gallery from external source. Not implemented in current version. */ export default function ExternalSourcePane(){ return ( <Pane> <h5>Create dynamic galleries.</h5> <p>We are plaining to create dynamic instagram galleries in the next version of myGallery. Follow us on twitter to do not miss this important update.</p> <div className="d-flex"> <a href="https://www.facebook.com/evgeny.zalevski"><span className='fo fo-facebook'></span></a> <a href="https://twitter.com/EvgeniyZ6"><span className='fo fo-twitter ml-3 mr-3'></span></a> <a href="https://github.com/zalevsk1y/MyGallery"><span className='fo fo-github'></span></a> </div> </Pane> ) }
import Box2D as b2 import numpy as np from staticobject import StaticObject from mind import programed #------------------------------------------------------------------------------- # Wheel #------------------------------------------------------------------------------- WDC_LEFT = 0x1 WDC_RIGHT = 0x2 WDC_UP = 0x4 WDC_DOWN = 0x8 DEGTORAD = 0.0174532925199432957 RADTODEG = 57.295779513082320876 #------------------------------------------------------------------------------- # Wheel #------------------------------------------------------------------------------- class Wheel(object): def __init__(self): self.body = None self.maxForwardSpeed = 0 self.maxBackwardSpeed = 0 self.maxDriveForce = 0 self.maxLateralImpulse = 0 def create(self, world, carBody, carPos, cfg): self.maxForwardSpeed = cfg.maxForwardSpeed self.maxBackwardSpeed = cfg.maxBackwardSpeed self.maxDriveForce = cfg.maxDriveForce self.maxLateralImpulse = cfg.maxLateralImpulse bodyDef = b2.b2BodyDef() bodyDef.type = b2.b2_dynamicBody bodyDef.position = b2.b2Vec2(carPos) + b2.b2Vec2(cfg.position) self.body = world.CreateBody(bodyDef) fx = self.body.CreatePolygonFixture(box=(cfg.size.width, cfg.size.height), density=cfg.density) def getLateralVelocity(self): currentRightNormal = self.body.GetWorldVector((1,0)) return b2.b2Dot(currentRightNormal, self.body.linearVelocity) * currentRightNormal def getForwardVelocity(self): currentForwardNormal = self.body.GetWorldVector((0,1)) return b2.b2Dot(currentForwardNormal, self.body.linearVelocity) * currentForwardNormal def updateFriction(self): # Lateral linear velocity maxLateralImpulse = 2.5 impulse = self.body.mass * -self.getLateralVelocity() if impulse.length > maxLateralImpulse: impulse *= maxLateralImpulse / impulse.length self.body.ApplyLinearImpulse(impulse, self.body.worldCenter, True) # Angular velocity self.body.ApplyAngularImpulse(0.1*self.body.inertia*-self.body.angularVelocity, True) # Forward linear velocity currentForwardNormal = self.getForwardVelocity() currentForwardSpeed = currentForwardNormal.Normalize() dragForceMagnitude = -2 * currentForwardSpeed self.body.ApplyForce(dragForceMagnitude * currentForwardNormal, self.body.worldCenter, True) def updateDrive(self, controlState): desiredSpeed = 0 if controlState & WDC_UP: desiredSpeed = self.maxForwardSpeed if controlState & WDC_DOWN: desiredSpeed = self.maxBackwardSpeed # Current speed in forward direction currentForwardNormal = self.body.GetWorldVector((0,1)) currentSpeed = b2.b2Dot(self.getForwardVelocity(), currentForwardNormal) # Apply necessary force force = 0 if desiredSpeed > currentSpeed: force = self.maxDriveForce elif desiredSpeed < currentSpeed: force = -self.maxDriveForce else: return self.body.ApplyForce(force*currentForwardNormal, self.body.worldCenter, True) #------------------------------------------------------------------------------- # Agent #------------------------------------------------------------------------------- class Agent(object): def __init__(self, name): self.name = name # Control variables # Bodies self.body = None self.frontLeftWheel = Wheel() self.frontRightWheel = Wheel() self.rearLeftWheel = Wheel() self.rearRightWheel = Wheel() self.wheels = (self.frontLeftWheel, self.frontRightWheel, self.rearLeftWheel, self.rearRightWheel) self.flJoint = None self.frJoint = None # Sensors self.sensor = None self.fov = None self.sensorField = {} self.frameNum = 0 # Mind self.mind = None self.controlState = 0x0 def addWheel(self, wheel, world, carBody, carPos, cfg): wheel.create(world, carBody, carPos, cfg) jointDef = b2.b2RevoluteJointDef() jointDef.bodyA = self.body jointDef.enableLimit = True jointDef.lowerAngle = 0 jointDef.upperAngle = 0 # Center of wheel jointDef.localAnchorB.SetZero() jointDef.bodyB = wheel.body jointDef.localAnchorA.Set(*cfg.anchor) return world.CreateJoint(jointDef) def addSensor(self, world, cfg): sensorFov = b2.b2PolygonShape() # Define sensor shape w, h = cfg.fov.width, cfg.fov.height self.fov = (w,h) fov = np.array([(-0.5*w,-0.5*h),(0.5*w,-0.5*h), (0.5*w,0.5*h),(-0.5*w, 0.5*h)]) # Move sensor relative to the body relpos = np.array([cfg.relpos.x, cfg.relpos.y]) sensorFov.vertices = (fov+relpos).tolist() sensorFixtureDef = b2.b2FixtureDef() sensorFixtureDef.isSensor = True sensorFixtureDef.shape = sensorFov self.sensor = self.body.CreateFixture(sensorFixtureDef) def construct(self, world, cfg): # Agent body bodyDef = b2.b2BodyDef() bodyDef.type = b2.b2_dynamicBody bodyDef.linearDamping = cfg.linearDamping bodyDef.angularDamping = cfg.angularDamping bodyDef.position = cfg.position self.body = world.CreateBody(bodyDef) self.body.userData = self verts = ((1.5,0.0), (3.0,2.5), (2.8,5.5), (1.0,10.0), (-1.0,10.0), (-2.8,5.5), (-3.0,2.5), (-1.5,0.0) ) self.body.CreatePolygonFixture(vertices=verts, friction=cfg.friction, density=cfg.density, restitution=cfg.restitution ) self.flJoint = self.addWheel(self.frontLeftWheel, world, self.body, cfg.position, cfg.wheels.frontLeft ) self.frJoint = self.addWheel(self.frontRightWheel, world, self.body, cfg.position, cfg.wheels.frontRight ) self.addWheel(self.rearLeftWheel, world, self.body, cfg.position, cfg.wheels.rearLeft ) self.addWheel(self.rearRightWheel, world, self.body, cfg.position, cfg.wheels.rearRight ) # Create Sensor self.addSensor(world, cfg.sensor) # Create the mind or remain mindless if not cfg.mind: return self.mind = programed.MindProgram() self.mind.configure(cfg.mind, self) def accelerate(self): self.controlState |= WDC_UP def releaseAccelerator(self): self.controlState &= ~WDC_UP def reverse(self): self.controlState |= WDC_DOWN def releaseReverse(self): self.controlState &= ~WDC_DOWN def steerLeft(self): self.controlState |= WDC_LEFT def releaseLeft(self): self.controlState &= ~WDC_LEFT def steerRight(self): self.controlState |= WDC_RIGHT def releaseRight(self): self.controlState &= ~WDC_RIGHT def brake(self): pass def releaseBrake(self): pass def update(self): # Decision-making time if self.mind: self.mind.think() # Put our actions into physics for wheel in self.wheels: wheel.updateFriction() wheel.updateDrive(self.controlState) lockAngle = 35*DEGTORAD turnSpeedPerSec = 160 * DEGTORAD turnPerTimeStep = turnSpeedPerSec / 60.0 desiredAngle = 0 if self.controlState & WDC_LEFT: desiredAngle = -lockAngle elif self.controlState & WDC_RIGHT: desiredAngle = lockAngle angleToTurn = desiredAngle - self.flJoint.angle # Some problem with the API, therefore workaround: angleToTurn = b2.b2Clamp((angleToTurn,0), (-turnPerTimeStep,0), (turnPerTimeStep,0)).x newAngle = self.flJoint.angle + angleToTurn self.flJoint.limits = (newAngle, newAngle) self.frJoint.limits = (newAngle, newAngle) def handleCollisionBegin(self, contact, fixtureMe, fixtureOther): """ Collision events that do not come from the sensor, meaning that the agent has collided with something. Can be used to simulate damage, pain, etc. """ # Will check if this is a sensor first if fixtureMe.sensor: # print '%d, b: %d' % (self.frameNum, id(fixtureOther)) self.sensorField[fixtureOther] = {} return if fixtureOther.sensor: return obj = fixtureOther.body.userData # The other object is an agent if isinstance(obj, Agent): pass # print '%s - %s' % (self.name, obj.name) elif isinstance(obj, StaticObject): pass # print '%s - sObj(%d)' % (self.name, obj.id) # Either an error or an unknown body type without user data else: pass def handleCollisionEnd(self, contact, fixtureMe, fixtureOther): """ Collision events that do not come from the sensor, meaning that the agent has collided with something. Can be used to simulate damage, pain, etc. It is the *touch* sensor. """ # Will check if this is a sensor first if fixtureMe.sensor: # print '%d, e: %d' % (self.frameNum, id(fixtureOther)) self.sensorField.pop(fixtureOther) return if fixtureOther.sensor: return obj = fixtureOther.body.userData # The other object is an agent if isinstance(obj, Agent): pass # print '%s - %s' % (self.name, obj.name) elif isinstance(obj, StaticObject): pass # print '%s - sObj(%d)' % (self.name, obj.id) # Either an error or an unknown body type without user data else: pass
"""pyhaversion package.""" import asyncio from dataclasses import dataclass import async_timeout from .base import HaVersionBase from .consts import ( DATA_AUDIO, DATA_BOARD, DATA_CLI, DATA_DNS, DATA_HASSOS, DATA_HOMEASSISTANT, DATA_IMAGE, DATA_MULTICAST, DATA_OBSERVER, DATA_OS, DATA_SUPERVISOR, DEFAULT_BOARD, DEFAULT_HEADERS, DEFAULT_IMAGE, LOGGER, HaVersionSource, ) from .exceptions import HaVersionInputException URL = "https://version.home-assistant.io/{channel}.json" @dataclass class HaVersionSupervisor(HaVersionBase): """Handle versions for the Supervisor source.""" source = HaVersionSource.SUPERVISOR def validate_input(self) -> None: """Raise HaVersionInputException if expected input are missing.""" if self.session is None: raise HaVersionInputException("Missing aiohttp.ClientSession") if self.image is None: self.image = "default" async def fetch(self, **kwargs): """Logic to fetch new version data.""" async with async_timeout.timeout(self.timeout, loop=asyncio.get_event_loop()): request = await self.session.get( url=URL.format(channel=self.channel), headers=DEFAULT_HEADERS ) self._data = await request.json() def parse(self): """Logic to parse new version data.""" if self.image != DEFAULT_IMAGE and self.image not in self.data.get( DATA_HOMEASSISTANT, {} ): LOGGER.warning( "Image '%s' not found, using default '%s'", self.image, DEFAULT_IMAGE ) self.image = DEFAULT_IMAGE self._version = self.data.get(DATA_HOMEASSISTANT, {}).get(self.image) if self.board != DEFAULT_BOARD and self.board not in self.data.get( DATA_HASSOS, {} ): LOGGER.warning( "Board '%s' not found, using default '%s'", self.board, DEFAULT_BOARD ) self.board = DEFAULT_BOARD self._version_data = { DATA_AUDIO: self.data.get(DATA_AUDIO), DATA_BOARD: self.board, DATA_CLI: self.data.get(DATA_CLI), DATA_DNS: self.data.get(DATA_DNS), DATA_OS: self.data.get(DATA_HASSOS, {}).get(self.board), DATA_IMAGE: self.image, DATA_MULTICAST: self.data.get(DATA_MULTICAST), DATA_OBSERVER: self.data.get(DATA_OBSERVER), DATA_SUPERVISOR: self.data.get(DATA_SUPERVISOR), }
'use strict'; const FixtureLoader = require('./fixture-loader/FixtureLoader'); const AsyncAdapter = require('./fixture-loader/adapters/AsyncAdapter'); const { serviceRequest } = require('@envage/water-abstraction-helpers'); const config = require('../../../config'); const urlJoin = require('url-join'); const createReturnsUrl = (...parts) => urlJoin(config.services.returns, ...parts); // Resolve path to fixtures directory const path = require('path'); const dir = path.resolve(__dirname, '../fixtures'); const createConnector = tail => async body => { const { data } = await serviceRequest.post(createReturnsUrl(tail), { body }); return data; }; const create = () => { // Create Returns service fixture loader const asyncAdapter = new AsyncAdapter(); asyncAdapter .add('Return', createConnector('returns')) .add('Version', createConnector('versions')) .add('Line', createConnector('lines')); return new FixtureLoader(asyncAdapter, dir); }; module.exports = create;
from torch.utils.data import DataLoader from torch.utils.data.dataloader import default_collate class BaseDataLoader(DataLoader): """ Base class for all data loaders """ def __init__(self, dataset, batch_size, shuffle, num_workers, collate_fn=default_collate): self.n_samples = len(dataset) self.init_kwargs = { 'dataset': dataset, 'batch_size': batch_size, 'shuffle': shuffle, 'collate_fn': collate_fn, 'num_workers': num_workers } super(BaseDataLoader, self).__init__(**self.init_kwargs)
import * as mars3d from "mars3d" export let map // mars3d.Map三维地图对象 // 需要覆盖config.json中地图属性参数(当前示例框架中自动处理合并) export const mapOptions = { scene: { center: { lat: 31.221078, lng: 117.305076, alt: 136530, heading: 10, pitch: -68 } } } /** * 初始化地图业务,生命周期钩子函数(必须) * 框架在地图初始化完成后自动调用该函数 * @param {mars3d.Map} mapInstance 地图对象 * @returns {void} 无 */ export function onMounted(mapInstance) { map = mapInstance // 记录首次创建的map showWeiVectorTileLayer() } /** * 释放当前地图业务的生命周期函数 * @returns {void} 无 */ export function onUnmounted() { map = null } /** * API文档,参考lib\mars3d\thirdParty\weiVectorTile\Document.rar(解压Document.rar) * 显示国界线 * * @returns {void} */ function showWeiVectorTileLayer() { // shp 国界线 Promise.all([ Cesium.Resource.fetchBlob({ url: "//data.mars3d.cn/file/shp/hefei_xz.shp" }), Cesium.Resource.fetchBlob({ url: "//data.mars3d.cn/file/shp/hefei_xz.dbf" }), Cesium.Resource.fetchBlob({ url: "//data.mars3d.cn/file/shp/hefei_xz.prj" }) ]).then(function (files) { files[0].name = "hefei.shp" files[1].name = "hefei.dbf" files[2].name = "hefei.prj" const tileLayer = new mars3d.layer.WeiVectorTileLayer({ source: files, removeDuplicate: false, zIndex: 2, encoding: "gbk", defaultStyle: { // 参考api文档的Cesium.VectorStyle类 tileCacheSize: 200, fill: true, // 是否填充,仅面数据有效。 fillColor: "rgba(255,255,255,0.01)", outline: true, // 是否显示边,仅面数据有效。 outlineColor: "rgba(209,204,226,1)", // lineDash: [3, 10], lineWidth: 2, showMaker: false, showCenterLabel: false // showCenterLabel: true, //是否显示文本,仅对线和面数据有效 // centerLabelPropertyName: 'NAME', // fontColor: 'rgba(255,255,255,1)', // fontSize: 23, // fontFamily: '楷体', // labelOffsetX: -10, // labelOffsetY: -5, }, maximumLevel: 20, minimumLevel: 1, simplify: false, allowPick: true, // 允许单击 // 以下为mars3d参数,API参考http://mars3d.cn/api/BaseTileLayer.html#.ConstructorOptions maxLength: -1, popup: "名称:{name} <br /> 日期:{address}" }) map.addLayer(tileLayer) tileLayer.on(mars3d.EventType.click, function (event) { console.log("单击了图层", event) }) }) }
import express from 'express'; import { getIndexPage, postMedicineInCart, postOrder, getOrderPopup, getPharmacistId, getSaveVideo } from '../controllers/generalMedicine'; const router = express.Router(); router.get('/pharmacist', getIndexPage); router.get('/pharmacist-get-medicines/:medicineIds', postMedicineInCart); router.get('/pharmacist-clear-cart', postOrder); router.get('/pharmacist-get-pharmacist-id/:pharmacistDBNumber', getPharmacistId); router.put('/pharmacist-order-medicine', getOrderPopup); router.get('/pharmacist-save-video-file', getSaveVideo); export default router;
const varListTemplate = { consentMain: true } let varList const mockSession = { setYarValue: (request, key, value) => null, getYarValue: (request, key) => { if (Object.keys(varList).includes(key)) return varList[key] else return 'Error' } } jest.mock('../../../../app/helpers/session', () => mockSession) describe('Reference number page', () => { beforeEach(() => { varList = { ...varListTemplate } }) afterAll(() => { jest.resetAllMocks() }) // it('load page successfully with the Reference ID', async () => { // const getOtions = { // method: 'GET', // url: `${global.__URLPREFIX__}/confirmation` // } // const getResponse = await global.__SERVER__.inject(getOtions) // expect(getResponse.statusCode).toBe(200) // expect(getResponse.payload).toContain('Details submitted') // }) it('it redirects to start page if no conscent is given', async () => { varList.consentMain = null const getOtions = { method: 'GET', url: `${global.__URLPREFIX__}/confirmation` } const getResponse = await global.__SERVER__.inject(getOtions) expect(getResponse.statusCode).toBe(302) expect(getResponse.headers.location).toBe('/productivity/start') }) })
from selenium import webdriver FILEURLSLIST = [] def findAllLink(browser): # ---------------- FIND ALL LINK START ------------- urls = browser.find_elements_by_xpath("//a") urlMetaData = [] # collect meta data for url in urls: link = url.get_attribute("href") print(link) try: urlMetaObj = {"id":"", "name":"", "href":""} urlMetaObj['id'] = url.get_attribute("id") urlMetaObj['name'] = url.get_attribute("name") urlMetaObj['href'] = url.get_attribute("href") urlMetaData.append(urlMetaObj) except: pass print(urlMetaData) for metaObj in urlMetaData: if metaObj['id'] != '': print(metaObj['id']) url = browser.find_element_by_id(metaObj['id']) print(url) try: if url.get_attribute("name") == 'folderlist': print('--Emm... FOLDER ~ open it!--') url.click() findAllLink(browser) browser.back() elif url.get_attribute("name") == 'filelist': print('--Emm... FILE ~ download it!--') FILEURLSLIST.append(url.get_attribute("href").replace("?preview", "")) except: pass # ---------------- FIND ALL LINK END ------------- def out_put_link(): fo = open("downloadlink.txt", "w") for link in FILEURLSLIST: fo.write(link+'\r\n') # 关闭打开的文件 fo.close() browser = webdriver.Chrome() # 普通模式,会打开浏览器 # browser.get('https://d.shikey.com/') # 2.1.2 Headless方式启动 r''' Headless Chrome 是 Chrome 浏览器的无界面形态,可以在不打开浏览器的前提下,使用所有Chrome 支持的特性运行你的程序。 相比于现代浏览器,Headless Chrome 更加方便测试 web应用,获得网站截图, 做爬虫抓取信息等。 相比于较早的PhantomJS, SlimerJS等, Headless Chrome 则更加贴近浏览器环境。、 Headless Chrome 对Chrome版本要求: 官方文档中介绍,mac和linux环境要求chrome版本是59+,而windows版本的chrome要求是60+,同时chromedriver要求2.30+版本。 ''' # chrome_options = webdriver.ChromeOptions() # # 使用headless无界面浏览器模式 # chrome_options.add_argument('--headless') # 增加无界面选项 # chrome_options.add_argument('--disable-gpu') # 如果不加这个选项,有时定位会出现问题 # # # 启动浏览器,获取网页源代码 # browser = webdriver.Chrome(chrome_options=chrome_options) # mainUrl = "https://d.shikey.com/" # 算法训练营2020/ mainUrl = "https://d.shikey.com/%E6%9E%81%E5%AE%A2%E6%97%B6%E9%97%B4-%E7%AE%97%E6%B3%95%E8%AE%AD%E7%BB%83%E8%90%A52020/" #mainUrl = "https://d.shikey.com/%E6%9E%81%E5%AE%A2%E7%AE%97%E6%B3%95/" browser.get(mainUrl) # print(f"browser text = {browser.page_source}") findAllLink(browser) print('\r\n***********************\r\n\r\n', FILEURLSLIST, '\r\n\r\n**************************\r\n') out_put_link() # 通过name方式定位 # continue_link = browser.find_element_by_link_text('极客算法').click() browser.quit()
import functools import multiprocessing from typing import Dict, List, Tuple from pathlib import Path import click import pandas as pd import numpy as np import tqdm from covid_model_seiir_pipeline.lib import ( cli_tools, static_vars, ) from covid_model_seiir_pipeline.pipeline.forecasting.specification import ( ForecastSpecification, FORECAST_JOBS, ) from covid_model_seiir_pipeline.pipeline.forecasting.data import ForecastDataInterface logger = cli_tools.task_performance_logger def run_compute_beta_scaling_parameters(forecast_version: str, scenario: str, progress_bar: bool): """Pre-compute the parameters for rescaling predicted beta and write out. The predicted beta has two issues we're attempting to adjust. The first issue is that the predicted beta does not share the same y-intercept as the beta we fit from the ODE step. To fix this, we compute an initial scale factor `scale_init` that shifts the whole time series so that it lines up with the fit beta at the day of transition. The second issue is the long-term scaling of the predicted beta. If we use our initial scaling computed from the transition day, we bias the long range forecast heavily towards whatever unexplained variance appears in the regression on the transition day. Instead we use an average of the residual from the regression over some period of time in the past as the long range scaling. For locations with a large number of deaths, the average of the residual mean across draws represents concrete unexplained variance that is biased in a particular direction. For locations with a small number of deaths, the average of the residual mean is susceptible to a lot of noise week to week and so we re-center the distribution of the means about zero. For locations in between, we linearly scale this shift between the distribution of residual means centered around zero and the distribution of residual means centered around the actual average residual mean. We call this final shift `scale_final` Parameters ---------- forecast_version The path to the forecast version to run this process for. scenario Which scenario in the forecast version to run this process for. progress_bar Whether to display the progress bar. Notes ----- The last step of average residual re-centering requires information from all draws. This is the only reason this process exists as separate from the main forecasting process. """ logger.info(f"Computing beta scaling parameters for forecast " f"version {forecast_version} and scenario {scenario}.", context='setup') forecast_spec: ForecastSpecification = ForecastSpecification.from_path( Path(forecast_version) / static_vars.FORECAST_SPECIFICATION_FILE ) num_cores = forecast_spec.workflow.task_specifications[FORECAST_JOBS.scaling].num_cores data_interface = ForecastDataInterface.from_specification(forecast_spec) logger.info('Loading input data.', context='read') beta_scaling = forecast_spec.scenarios[scenario].beta_scaling logger.info('Computing scaling parameters.', context='compute') scaling_data = compute_initial_beta_scaling_parameters(beta_scaling, data_interface, num_cores, progress_bar) logger.info('Writing scaling parameters to disk.', context='write') write_out_beta_scale(scaling_data, scenario, data_interface, num_cores) logger.report() def compute_initial_beta_scaling_parameters(beta_scaling: dict, data_interface: ForecastDataInterface, num_cores: int, progress_bar: bool) -> List[Tuple[pd.DataFrame, pd.DataFrame]]: # Serialization is our bottleneck, so we parallelize draw level data # ingestion and computation across multiple processes. _runner = functools.partial( compute_initial_beta_scaling_parameters_by_draw, beta_scaling=beta_scaling, data_interface=data_interface ) draws = list(range(data_interface.get_n_draws())) with multiprocessing.Pool(num_cores) as pool: scaling_data = list(tqdm.tqdm(pool.imap(_runner, draws), total=len(draws), disable=not progress_bar)) return scaling_data def compute_initial_beta_scaling_parameters_by_draw(draw_id: int, beta_scaling: Dict, data_interface: ForecastDataInterface) -> Tuple[pd.DataFrame, pd.DataFrame]: # Construct a list of pandas Series indexed by location and named # as their column will be in the output dataframe. We'll append # to this list as we construct the parameters. draw_data = [] betas = data_interface.load_betas(draw_id) # Select out the transition day to compute the initial scaling parameter. beta_transition = betas.groupby('location_id').last() draw_data.append(beta_transition['beta'].rename('fit_final')) draw_data.append(beta_transition['beta_hat'].rename('pred_start')) draw_data.append((beta_transition['beta'] / beta_transition['beta_hat']).rename('scale_init')) # Compute the beta residual mean for our parameterization and hang on # to some ancillary information that may be useful for plotting/debugging. rs = np.random.RandomState(draw_id) a = rs.randint(1, beta_scaling['average_over_min']) b = rs.randint(a + 21, beta_scaling['average_over_max']) draw_data.append(pd.Series(a, index=beta_transition.index, name='history_days_start')) draw_data.append(pd.Series(b, index=beta_transition.index, name='history_days_end')) draw_data.append(pd.Series(beta_scaling['window_size'], index=beta_transition.index, name='window_size')) residual_rescale_upper = beta_scaling.get('residual_rescale_upper', 1) residual_rescale_lower = beta_scaling.get('residual_rescale_lower', 4) log_beta_residual = np.log(betas['beta']/betas['beta_hat']).rename('log_beta_residual') scaled_log_beta_residual = log_scale(log_beta_residual, residual_rescale_upper, residual_rescale_lower).rename('scaled_log_beta_residual') log_beta_residual_mean = (scaled_log_beta_residual .groupby(level='location_id') .apply(lambda x: x.iloc[-b: -a].mean()) .rename('log_beta_residual_mean') .fillna(0)) draw_data.append(log_beta_residual_mean) draw_data.append(np.exp(log_beta_residual_mean).rename('scale_final')) draw_data.append(pd.Series(draw_id, index=beta_transition.index, name='draw')) return pd.concat(draw_data, axis=1), pd.concat([log_beta_residual, scaled_log_beta_residual], axis=1) def log_scale(y, n_times_upper, n_times_lower): z = y.copy() for i in range(n_times_upper): z[z > 0] = np.log(z[z > 0] + 1) z = -z for i in range(n_times_lower): z[z > 0] = np.log(z[z > 0] + 1) z = -z return z def write_out_beta_scale(beta_scales: List[Tuple[pd.DataFrame, pd.Series]], scenario: str, data_interface: ForecastDataInterface, num_cores: int) -> None: _runner = functools.partial( write_out_beta_scales_by_draw, data_interface=data_interface, scenario=scenario ) with multiprocessing.Pool(num_cores) as pool: pool.map(_runner, beta_scales) def write_out_beta_scales_by_draw(beta_scales: Tuple[pd.DataFrame, pd.DataFrame], data_interface: ForecastDataInterface, scenario: str) -> None: beta_scales, residual = beta_scales draw_id = beta_scales['draw'].iat[0] data_interface.save_beta_scales(beta_scales, scenario, draw_id) data_interface.save_beta_residual(residual.reset_index(), scenario, draw_id) @click.command() @cli_tools.with_task_forecast_version @cli_tools.with_scenario @cli_tools.with_progress_bar @cli_tools.add_verbose_and_with_debugger def beta_residual_scaling(forecast_version: str, scenario: str, progress_bar: bool, verbose: int, with_debugger: bool): cli_tools.configure_logging_to_terminal(verbose) run = cli_tools.handle_exceptions(run_compute_beta_scaling_parameters, logger, with_debugger) run(forecast_version=forecast_version, scenario=scenario, progress_bar=progress_bar) if __name__ == '__main__': beta_residual_scaling()
import React, { Component } from 'react' import logo from '../assets/logo.png' class Home extends Component { render() { return ( <div className="homepage"> <div className='home-heading-and-links'> <div className='logo'> <img src={logo} alt='saywhat logo' /> <h4>The translation and travel app</h4> </div> <div className='brochure-information'> <div className='translation-info'> <div> <h5>Translations Page</h5> </div> <div> <p>Click the 'Translations' link in the navigation bar to translate any word, or customized sentence into 63 different languages!</p> </div> </div> <div className='countries-info'> <div> <h5>Countries Page</h5> </div> <div> <p>Click the 'Countries' link in the navigation bar to add, edit, or delete the countries you'd like to visit, and save valuable information for each country you add! For each country you can save primary language, currency, up to three sites you'd like to remember to visit, and the wikipedia page for that country.</p> </div> </div> </div> </div> </div> ) } } export default Home
/*! * OpenUI5 * (c) Copyright 2009-2019 SAP SE or an SAP affiliate company. * Licensed under the Apache License, Version 2.0 - see LICENSE.txt. */ // Provides utility class sap.ui.core.BusyIndicatorUtils sap.ui.define(['./BlockLayerUtils', "sap/ui/thirdparty/jquery"], //require of sap/ui/core/library not possible due to cyclic dependencies function(BlockLayerUtils, jQuery) { "use strict"; // Static class /** * @alias sap.ui.core.BusyIndicatorUtils * @namespace * @public */ var BusyIndicatorUtils = function() {}; /** * Returns the HTML content for the busy indicator * styling + animation: LocalBusyIndicator.less * * @param {string} sSize either "Large" or "Medium". Other sizes will be mapped to "Medium" * @returns {DOM.element} the element for the busy indicator */ BusyIndicatorUtils.getElement = function(sSize) { //default size is medium var sSizeClass = "sapUiLocalBusyIndicatorSizeMedium"; if (sSize === "Large") { sSizeClass = "sapUiLocalBusyIndicatorSizeBig"; } var oContainer = document.createElement("div"); oContainer.className = "sapUiLocalBusyIndicator " + sSizeClass + " sapUiLocalBusyIndicatorFade"; BlockLayerUtils.addAriaAttributes(oContainer); addAnimation(oContainer); return oContainer; }; function addAnimation(oContainer, sSizeClass) { sSizeClass = sSizeClass || "sapUiLocalBusyIndicatorAnimStandard"; // set title for screen reader var oResBundle = sap.ui.getCore().getLibraryResourceBundle("sap.ui.core"), sTitle = oResBundle.getText("BUSY_TEXT"); oContainer.setAttribute("title", sTitle); // determine automation size class var oAnimation = document.createElement("div"); oAnimation.className = "sapUiLocalBusyIndicatorAnimation " + sSizeClass; oAnimation.appendChild(document.createElement("div")); oAnimation.appendChild(document.createElement("div")); oAnimation.appendChild(document.createElement("div")); oContainer.appendChild(oAnimation); } function handleAutoAnimationSize(oBusyBlockState, sSize) { var oParentDOM = oBusyBlockState.$parent.get(0), oBlockLayerDOM = oBusyBlockState.$blockLayer.get(0); // get animation container var oAnimation = oBlockLayerDOM.children[0], iWidth = oAnimation.offsetWidth; // We can only determine the actual animation after the browser has // calculated the size of the indicator we need to know the pixel-size of // 3rem, under which the indicator will animate differently if (oParentDOM.offsetWidth < iWidth) { oAnimation.className = "sapUiLocalBusyIndicatorAnimation sapUiLocalBusyIndicatorAnimSmall"; } } /** * Adds the DOM element for the BusyIndicator animation to the contained DOM element in the given block-state. * @param {object} oBusyBlockState The given block-state on which the DOM gets added for the busy animation * @param {sap.ui.core.BusyIndicatorSize} sSize either "Auto", "Large", "Medium" or "Small", determines the size of the * indicator, default is "Medium" * @see sap.ui.core.BusyIndicatorSize */ BusyIndicatorUtils.addHTML = function (oBusyBlockState, sSize) { // Note: to avoid the cycle (Core -> Control -> BusyIndicatorUtils -> library -> Core), // this cannot be modeled as a top-level dependency var BusyIndicatorSize = sap.ui.require("sap/ui/core/library").BusyIndicatorSize, sSizeClass = "sapUiLocalBusyIndicatorSizeMedium", sAnimationSizeClass; switch (sSize) { case BusyIndicatorSize.Small: sSizeClass = "sapUiLocalBusyIndicatorSizeMedium"; sAnimationSizeClass = "sapUiLocalBusyIndicatorAnimSmall"; break; case BusyIndicatorSize.Large: sSizeClass = "sapUiLocalBusyIndicatorSizeBig"; sAnimationSizeClass = "sapUiLocalBusyIndicatorAnimStandard"; break; case BusyIndicatorSize.Auto: sSizeClass = "sapUiLocalBusyIndicatorSizeMedium"; sAnimationSizeClass = "sapUiLocalBusyIndicatorAnimStandard"; break; default: //default size is medium sSizeClass = "sapUiLocalBusyIndicatorSizeMedium"; sAnimationSizeClass = "sapUiLocalBusyIndicatorAnimStandard"; break; } if (!oBusyBlockState) { return; } var oParentDOM = oBusyBlockState.$parent.get(0), oBlockLayerDOM = oBusyBlockState.$blockLayer.get(0); oParentDOM.className += " sapUiLocalBusy"; oBlockLayerDOM.className += " sapUiLocalBusyIndicator " + sSizeClass + " sapUiLocalBusyIndicatorFade"; addAnimation(oBlockLayerDOM, sAnimationSizeClass); if (sSize === BusyIndicatorSize.Auto) { handleAutoAnimationSize(oBusyBlockState); } //Set the actual DOM Element to 'aria-busy' jQuery(oParentDOM).attr('aria-busy', true); }; /** * Obsolete IE9 support, kept for some more time to avoid issues with custom controls, * start/stop now are 'noop's. */ BusyIndicatorUtils.animateIE9 = { start: function () {}, stop: function () {} }; return BusyIndicatorUtils; }, /* bExport= */ true);
/** * @Created by kaicui. * @Date:2014-03-31 10:15 * @Desc: 用于对Date类进行基础扩展,使其支持更多的功能 * 1、增加直接按格式获取日期字符串功能 * 2、增加IE9-等对Date.now的支持 * @Change History: -------------------------------------------- @created:|kaicui| 2014-03-31 10:15. -------------------------------------------- */ //增加IE9-等对Date.now的支持 if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } if (!Date.prototype.format) { Date.prototype.format = function(fmt){ var self = this;//save the this ref var o = { "M+" : self.getMonth()+1, //月份 "d+" : self.getDate(), //日 "h+" : self.getHours(), //小时 "m+" : self.getMinutes(), //分 "s+" : self.getSeconds(), //秒 "q+" : Math.floor((self.getMonth()+3)/3), //季度 "f+" : self.getMilliseconds() //毫秒 }; //将毫秒补位成3位 var less = 3 - (""+ o["f+"]).length; while( less > 0){ o["f+"] = "0" + o["f+"]; less--; } if(/(y+)/.test(fmt)) fmt=fmt.replace(RegExp.$1, (self.getFullYear()+"").substr(4 - RegExp.$1.length)); for(var k in o) if(new RegExp("("+ k +")").test(fmt)) fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length))); return fmt; }; }
"""Aggregator Endpoints."""
var searchData= [ ['navy_2ec',['Navy.c',['../_navy_8c.html',1,'']]] ];
#### NOTICE: THIS FILE IS AUTOGENERATED #### MODIFICATIONS MAY BE LOST IF DONE IMPROPERLY #### PLEASE SEE THE ONLINE DOCUMENTATION FOR EXAMPLES from swgpy.object import * def create(kernel): result = Intangible() result.template = "object/draft_schematic/space/weapon/missile/shared_wpn_launcher_proton_mk3.iff" result.attribute_template_id = -1 result.stfName("string_id_table","") #### BEGIN MODIFICATIONS #### #### END MODIFICATIONS #### return result
import socket class Connection: isConnected = False ip = "" port = -1 service = None def __init__(self,ip,port): self.ip = ip self.port = port self.service = socket.socket() def connect(self): try: self.service.connect((self.ip,self.port)) self.isConnected = True except : raise Exception("Error ") def send(self,msg): if self.isConnected: self.service.send(str.encode(msg + '\n')) def recv(self): result = "" if self.isConnected: result = self.service.recv(1024) result = result.decode("utf-8") result = result.strip() return result def close(self): self.service.close()
// Copyright 2018 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_OBJECTS_EMBEDDER_DATA_SLOT_H_ #define V8_OBJECTS_EMBEDDER_DATA_SLOT_H_ #include <utility> #include "src/common/assert-scope.h" #include "src/common/globals.h" #include "src/objects/slots.h" // Has to be the last include (doesn't have include guards): #include "src/objects/object-macros.h" namespace v8 { namespace internal { class EmbedderDataArray; class JSObject; class Object; // An EmbedderDataSlot instance describes a kEmbedderDataSlotSize field ("slot") // holding an embedder data which may contain raw aligned pointer or a tagged // pointer (smi or heap object). // Its address() is the address of the slot. // The slot's contents can be read and written using respective load_XX() and // store_XX() methods. // Storing heap object through this slot may require triggering write barriers // so this operation must be done via static store_tagged() methods. class EmbedderDataSlot : public SlotBase<EmbedderDataSlot, Address, kTaggedSize> { public: EmbedderDataSlot() : SlotBase(kNullAddress) {} V8_INLINE EmbedderDataSlot(EmbedderDataArray array, int entry_index); V8_INLINE EmbedderDataSlot(JSObject object, int embedder_field_index); #if defined(V8_TARGET_BIG_ENDIAN) && defined(V8_COMPRESS_POINTERS) static constexpr int kTaggedPayloadOffset = kTaggedSize; #else static constexpr int kTaggedPayloadOffset = 0; #endif #ifdef V8_COMPRESS_POINTERS // The raw payload is located in the other "tagged" part of the full pointer // and cotains the upper part of aligned address. The raw part is not expected // to look like a tagged value. // When V8_HEAP_SANDBOX is defined the raw payload contains an index into the // external pointer table. static constexpr int kRawPayloadOffset = kTaggedSize - kTaggedPayloadOffset; #endif static constexpr int kRequiredPtrAlignment = kSmiTagSize; // Opaque type used for storing raw embedder data. using RawData = Address; V8_INLINE void AllocateExternalPointerEntry(Isolate* isolate); V8_INLINE Object load_tagged() const; V8_INLINE void store_smi(Smi value); // Setting an arbitrary tagged value requires triggering a write barrier // which requires separate object and offset values, therefore these static // functions also has the target object parameter. static V8_INLINE void store_tagged(EmbedderDataArray array, int entry_index, Object value); static V8_INLINE void store_tagged(JSObject object, int embedder_field_index, Object value); // Tries reinterpret the value as an aligned pointer and sets *out_result to // the pointer-like value. Note, that some Smis could still look like an // aligned pointers. // Returns true on success. // When V8 heap sandbox is enabled, calling this method when the raw part of // the slot does not contain valid external pointer table index is undefined // behaviour and most likely result in crashes. V8_INLINE bool ToAlignedPointer(PtrComprCageBase isolate_root, void** out_result) const; // Same as ToAlignedPointer() but with a workaround for V8 heap sandbox. // When V8 heap sandbox is enabled, this method doesn't crash when the raw // part of the slot contains "undefined" instead of a correct external table // entry index (see Factory::InitializeJSObjectBody() for details). // Returns true when the external pointer table index was pointing to a valid // entry, otherwise false. // // Call this function if you are not sure whether the slot contains valid // external pointer or not. V8_INLINE bool ToAlignedPointerSafe(PtrComprCageBase isolate_root, void** out_result) const; // Returns true if the pointer was successfully stored or false it the pointer // was improperly aligned. V8_INLINE V8_WARN_UNUSED_RESULT bool store_aligned_pointer(Isolate* isolate, void* ptr); V8_INLINE RawData load_raw(Isolate* isolate, const DisallowGarbageCollection& no_gc) const; V8_INLINE void store_raw(Isolate* isolate, RawData data, const DisallowGarbageCollection& no_gc); private: // Stores given value to the embedder data slot in a concurrent-marker // friendly manner (tagged part of the slot is written atomically). V8_INLINE void gc_safe_store(Isolate* isolate, Address value); }; } // namespace internal } // namespace v8 #include "src/objects/object-macros-undef.h" #endif // V8_OBJECTS_EMBEDDER_DATA_SLOT_H_
import logging from scraper.common import ScrapeResult, Scraper, ScraperFactory class AmazonScrapeResult(ScrapeResult): def parse(self): alert_subject = 'In Stock' alert_content = '' # get name of product tag = self.soup.body.select_one('h1#title > span#productTitle') if tag: alert_content += tag.text.strip() + '\n' else: logging.warning(f'missing title: {self.url}') # get listed price tag = self.soup.body.select_one('div.a-section > span#price_inside_buybox') price_str = self.set_price(tag) if price_str: alert_subject = f'In Stock for {price_str}' # check for add to cart button tag = self.soup.body.select_one('span.a-button-inner > span#submit\\.add-to-cart-announce') if tag and 'add to cart' in tag.text.lower(): self.alert_subject = alert_subject self.alert_content = f'{alert_content.strip()}\n{self.url}' @ScraperFactory.register class AmazonScraper(Scraper): @staticmethod def get_domain(): return 'amazon' @staticmethod def get_result_type(): return AmazonScrapeResult @staticmethod def generate_short_name(url): parts = [i for i in url.path.split('/') if i] if parts: return parts[min(2, len(parts) - 1)]
SCREEN_WIDTH = 1000 SCREEN_HEIGHT = BOX_HEIGHT = 800 WORLD_SIZE = 800 COLORS = { 'white': (255, 255, 255), 'black': (0, 0, 0) } SQUARE_SIZE = int(WORLD_SIZE / 60) SPEED = 333 PADDING = 10 BOX_WIDTH = SCREEN_WIDTH - WORLD_SIZE FONT_SIZE = 18
from django.core.management import BaseCommand from django.db.models import get_app, get_models from django.conf import settings from search.search_utils import index_instance, confirm_model_is_indexable class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument( '--test', action='store_true', dest='test', default=False, help='Provide this if you want to create a test index') def handle(self, *args, **options): # optimize this to index in bulk apps_lists = settings.LOCAL_APPS for app_name in apps_lists: app = get_app(app_name) for model in get_models(app): if model and confirm_model_is_indexable(model): all_instances = model.objects.all()[0:100] \ if options.get('test') else model.objects.all() [ index_instance( obj._meta.app_label, obj.__class__.__name__, str(obj.id)) for obj in all_instances] message = "Indexed {} {}".format( all_instances.count(), model._meta.verbose_name_plural.capitalize()) self.stdout.write(message) else: message = "Not indexing model {}".format( model.__name__) self.stdout.write(message) self.stdout.write("Finished indexing")
# Copyright 2018 The TensorFlow Probability Authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================ """ScaleTriL bijector.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import tensorflow.compat.v2 as tf from tensorflow_probability.python.bijectors import affine_scalar from tensorflow_probability.python.bijectors import chain from tensorflow_probability.python.bijectors import fill_triangular from tensorflow_probability.python.bijectors import softplus from tensorflow_probability.python.bijectors import transform_diagonal __all__ = [ "ScaleTriL", ] class ScaleTriL(chain.Chain): """Transforms unconstrained vectors to TriL matrices with positive diagonal. This is implemented as a simple `tfb.Chain` of `tfb.FillTriangular` followed by `tfb.TransformDiagonal`, and provided mostly as a convenience. The default setup is somewhat opinionated, using a Softplus transformation followed by a small shift (`1e-5`) which attempts to avoid numerical issues from zeros on the diagonal. #### Examples ```python tfb = tfp.distributions.bijectors b = tfb.ScaleTriL( diag_bijector=tfb.Exp(), diag_shift=None) b.forward(x=[0., 0., 0.]) # Result: [[1., 0.], # [0., 1.]] b.inverse(y=[[1., 0], [.5, 2]]) # Result: [log(2), .5, log(1)] # Define a distribution over PSD matrices of shape `[3, 3]`, # with `1 + 2 + 3 = 6` degrees of freedom. dist = tfd.TransformedDistribution( tfd.Normal(tf.zeros(6), tf.ones(6)), tfb.Chain([tfb.CholeskyOuterProduct(), tfb.ScaleTriL()])) # Using an identity transformation, ScaleTriL is equivalent to # tfb.FillTriangular. b = tfb.ScaleTriL( diag_bijector=tfb.Identity(), diag_shift=None) # For greater control over initialization, one can manually encode # pre- and post- shifts inside of `diag_bijector`. b = tfb.ScaleTriL( diag_bijector=tfb.Chain([ tfb.AffineScalar(shift=1e-3), tfb.Softplus(), tfb.AffineScalar(shift=0.5413)]), # softplus_inverse(1.) # = log(expm1(1.)) = 0.5413 diag_shift=None) ``` """ def __init__(self, diag_bijector=None, diag_shift=1e-5, validate_args=False, name="scale_tril"): """Instantiates the `ScaleTriL` bijector. Args: diag_bijector: `Bijector` instance, used to transform the output diagonal to be positive. Default value: `None` (i.e., `tfb.Softplus()`). diag_shift: Float value broadcastable and added to all diagonal entries after applying the `diag_bijector`. Setting a positive value forces the output diagonal entries to be positive, but prevents inverting the transformation for matrices with diagonal entries less than this value. Default value: `1e-5`. validate_args: Python `bool` indicating whether arguments should be checked for correctness. Default value: `False` (i.e., arguments are not validated). name: Python `str` name given to ops managed by this object. Default value: `scale_tril`. """ with tf.name_scope(name) as name: if diag_bijector is None: diag_bijector = softplus.Softplus(validate_args=validate_args) if diag_shift is not None: diag_shift = tf.convert_to_tensor( diag_shift, dtype=diag_bijector.dtype, name="diag_shift") diag_bijector = chain.Chain([ affine_scalar.AffineScalar(shift=diag_shift), diag_bijector ]) super(ScaleTriL, self).__init__( [transform_diagonal.TransformDiagonal(diag_bijector=diag_bijector), fill_triangular.FillTriangular()], validate_args=validate_args, name=name)
// // zappearance.h // ZUtilsX // // Created by Char Aznable on 15/12/14. // Copyright © 2015年 org.cuc.n3. All rights reserved. // #ifndef ZUtilsX_zappearance_h #define ZUtilsX_zappearance_h #import "zobjc.h" #import "zarc.h" #import "zadapt.h" #import "UIImage+ZUX.h" #pragma mark - appearance - #define APPEARANCE [self appearance] #if __IPHONE_OS_VERSION_MIN_REQUIRED >= 90000 # define APPEARANCE_IN_CLASS(clz) [self appearanceWhenContainedInInstancesOfClasses:@[(clz)]] #else # define APPEARANCE_IN_CLASS(clz) (IOS9_OR_LATER?[self appearanceWhenContainedInInstancesOfClasses:@[(clz)]]:[self appearanceWhenContainedIn:(clz), nil]) #endif #pragma mark - titleTextAttribute - ZUX_STATIC_INLINE id titleTextAttributeForKey(id instance, NSString *key) { return [[instance titleTextAttributes] objectForKey:key]; } ZUX_STATIC_INLINE void setTitleTextAttributeForKey(id instance, NSString *key, id value) { NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary: [instance titleTextAttributes]]; [attributes setObject:value forKey:key]; [instance setTitleTextAttributes:attributes]; } ZUX_STATIC_INLINE NSShadow *titleShadowAttribute(id instance) { return titleTextAttributeForKey(instance, NSShadowAttributeName); } ZUX_STATIC_INLINE NSShadow *defaultTitleShadowAttribute(id instance) { return titleShadowAttribute(instance) ?: ZUX_AUTORELEASE([[NSShadow alloc] init]); } ZUX_STATIC_INLINE void setTitleShadowAttribute(id instance, NSShadow *shadow) { setTitleTextAttributeForKey(instance, NSShadowAttributeName, shadow); } #pragma mark - titleTextAttributeForState - ZUX_STATIC_INLINE id titleTextAttributeForStateAndKey(id instance, UIControlState state, NSString *key) { return [[instance titleTextAttributesForState:state] objectForKey:key]; } ZUX_STATIC_INLINE void setTitleTextAttributeForStateAndKey(id instance, UIControlState state, NSString *key, id value) { NSMutableDictionary *attributes = [NSMutableDictionary dictionaryWithDictionary: [instance titleTextAttributesForState:state]]; [attributes setObject:value forKey:key]; [instance setTitleTextAttributes:attributes forState:state]; } ZUX_STATIC_INLINE NSShadow *titleShadowAttributeForState(id instance, UIControlState state) { return titleTextAttributeForStateAndKey(instance, state, NSShadowAttributeName); } ZUX_STATIC_INLINE NSShadow *defaultTitleShadowAttributeForState(id instance, UIControlState state) { return titleShadowAttributeForState(instance, state) ?: ZUX_AUTORELEASE([[NSShadow alloc] init]); } ZUX_STATIC_INLINE void setTitleShadowAttributeForState(id instance, UIControlState state, NSShadow *shadow) { setTitleTextAttributeForStateAndKey(instance, state, NSShadowAttributeName, shadow); } #pragma mark - selectionIndicatorColor - ZUX_STATIC_INLINE UIColor *selectionIndicatorColor (ZUX_KINDOF(UITabBar *) instance) { return [[instance selectionIndicatorImage] dominantColor]; } ZUX_STATIC_INLINE void setSelectionIndicatorColor (ZUX_KINDOF(UITabBar *) instance, UIColor *selectionIndicatorColor) { [instance setSelectionIndicatorImage:[UIImage imagePointWithColor:selectionIndicatorColor]]; } #pragma mark - backgroundImageForBarMetrics - ZUX_STATIC_INLINE UIImage *backgroundImageForBarMetrics (ZUX_KINDOF(UINavigationBar *) instance, UIBarMetrics barMetrics) { return [instance backgroundImageForBarMetrics:barMetrics]; } ZUX_STATIC_INLINE void setBackgroundImageForBarMetrics (ZUX_KINDOF(UINavigationBar *) instance, UIImage *backgroundImage, UIBarMetrics barMetrics) { [instance setBackgroundImage:backgroundImage forBarMetrics:barMetrics]; } #pragma mark - backgroundColorForBarMetrics - ZUX_STATIC_INLINE UIColor *backgroundColorForBarMetrics (ZUX_KINDOF(UINavigationBar *) instance, UIBarMetrics barMetrics) { return [backgroundImageForBarMetrics(instance, barMetrics) dominantColor]; } ZUX_STATIC_INLINE void setBackgroundColorForBarMetrics (ZUX_KINDOF(UINavigationBar *) instance, UIColor *backgroundColor, UIBarMetrics barMetrics) { setBackgroundImageForBarMetrics(instance, [UIImage imagePointWithColor:backgroundColor], barMetrics); } #pragma mark - backgroundImageForStateAndBarMetrics - ZUX_STATIC_INLINE UIImage *backgroundImageForStateAndBarMetrics (ZUX_KINDOF(UIBarButtonItem *) instance, UIControlState state, UIBarMetrics barMetrics) { return [instance backgroundImageForState:state barMetrics:barMetrics]; } ZUX_STATIC_INLINE void setBackgroundImageForStateAndBarMetrics (ZUX_KINDOF(UIBarButtonItem *) instance, UIImage *backgroundImage, UIControlState state, UIBarMetrics barMetrics) { [instance setBackgroundImage:backgroundImage forState:state barMetrics:barMetrics]; } #pragma mark - backgroundColorForStateAndBarMetrics - ZUX_STATIC_INLINE UIColor *backgroundColorForStateAndBarMetrics (ZUX_KINDOF(UIBarButtonItem *) instance, UIControlState state, UIBarMetrics barMetrics) { return [backgroundImageForStateAndBarMetrics(instance, state, barMetrics) dominantColor]; } ZUX_STATIC_INLINE void setBackgroundColorForStateAndBarMetrics (ZUX_KINDOF(UIBarButtonItem *) instance, UIColor *backgroundColor, UIControlState state, UIBarMetrics barMetrics) { setBackgroundImageForStateAndBarMetrics(instance, [UIImage imagePointWithColor:backgroundColor], state, barMetrics); } #pragma mark - backgroundImageForStateAndStyleAndBarMetrics - ZUX_STATIC_INLINE UIImage *backgroundImageForStateAndStyleAndBarMetrics (ZUX_KINDOF(UIBarButtonItem *) instance, UIControlState state, UIBarButtonItemStyle style, UIBarMetrics barMetrics) { return #if __IPHONE_OS_VERSION_MIN_REQUIRED < 60000 BEFORE_IOS6 ? [instance backgroundImageForState:state barMetrics:barMetrics] : #endif [instance backgroundImageForState:state style:style barMetrics:barMetrics]; } ZUX_STATIC_INLINE void setBackgroundImageForStateAndStyleAndBarMetrics (ZUX_KINDOF(UIBarButtonItem *) instance, UIImage *backgroundImage, UIControlState state, UIBarButtonItemStyle style, UIBarMetrics barMetrics) { #if __IPHONE_OS_VERSION_MIN_REQUIRED < 60000 if (BEFORE_IOS6) [instance setBackgroundImage:backgroundImage forState:state barMetrics:barMetrics]; else #endif [instance setBackgroundImage:backgroundImage forState:state style:style barMetrics:barMetrics]; } #pragma mark - backgroundColorForStateAndStyleAndBarMetrics - ZUX_STATIC_INLINE UIColor *backgroundColorForStateAndStyleAndBarMetrics (ZUX_KINDOF(UIBarButtonItem *) instance, UIControlState state, UIBarButtonItemStyle style, UIBarMetrics barMetrics) { return [backgroundImageForStateAndStyleAndBarMetrics(instance, state, style, barMetrics) dominantColor]; } ZUX_STATIC_INLINE void setBackgroundColorForStateAndStyleAndBarMetrics (ZUX_KINDOF(UIBarButtonItem *) instance, UIColor *backgroundColor, UIControlState state, UIBarButtonItemStyle style, UIBarMetrics barMetrics) { setBackgroundImageForStateAndStyleAndBarMetrics (instance, [UIImage imagePointWithColor:backgroundColor], state, style, barMetrics); } #pragma mark - backgroundVerticalPositionAdjustment - ZUX_STATIC_INLINE CGFloat backgroundVerticalPositionAdjustmentForBarMetrics (ZUX_KINDOF(UIBarButtonItem *) instance, UIBarMetrics barMetrics) { return [instance backgroundVerticalPositionAdjustmentForBarMetrics:barMetrics]; } ZUX_STATIC_INLINE void setBackgroundVerticalPositionAdjustmentForBarMetrics (ZUX_KINDOF(UIBarButtonItem *) instance, CGFloat adjustment, UIBarMetrics barMetrics) { [instance setBackgroundVerticalPositionAdjustment:adjustment forBarMetrics:barMetrics]; } #pragma mark - titlePositionAdjustment - ZUX_STATIC_INLINE UIOffset titlePositionAdjustmentForBarMetrics (ZUX_KINDOF(UIBarButtonItem *) instance, UIBarMetrics barMetrics) { return [instance titlePositionAdjustmentForBarMetrics:barMetrics]; } ZUX_STATIC_INLINE void setTitlePositionAdjustmentForBarMetrics (ZUX_KINDOF(UIBarButtonItem *) instance, UIOffset adjustment, UIBarMetrics barMetrics) { [instance setTitlePositionAdjustment:adjustment forBarMetrics:barMetrics]; } #pragma mark - backButtonBackgroundImage - ZUX_STATIC_INLINE UIImage *backButtonBackgroundImageForStateAndBarMetrics (ZUX_KINDOF(UIBarButtonItem *) instance, UIControlState state, UIBarMetrics barMetrics) { return [instance backButtonBackgroundImageForState:state barMetrics:barMetrics]; } ZUX_STATIC_INLINE void setBackButtonBackgroundImageForStateAndBarMetrics (ZUX_KINDOF(UIBarButtonItem *) instance, UIImage *backgroundImage, UIControlState state, UIBarMetrics barMetrics) { [instance setBackButtonBackgroundImage:backgroundImage forState:state barMetrics:barMetrics]; } #pragma mark - backButtonBackgroundColor - ZUX_STATIC_INLINE UIColor *backButtonBackgroundColorForStateAndBarMetrics (ZUX_KINDOF(UIBarButtonItem *) instance, UIControlState state, UIBarMetrics barMetrics) { return [backButtonBackgroundImageForStateAndBarMetrics(instance, state, barMetrics) dominantColor]; } ZUX_STATIC_INLINE void setBackButtonBackgroundColorForStateAndBarMetrics (ZUX_KINDOF(UIBarButtonItem *) instance, UIColor *backgroundColor, UIControlState state, UIBarMetrics barMetrics) { setBackButtonBackgroundImageForStateAndBarMetrics (instance, [UIImage imagePointWithColor:backgroundColor], state, barMetrics); } #pragma mark - backButtonBackgroundVerticalPositionAdjustment - ZUX_STATIC_INLINE CGFloat backButtonBackgroundVerticalPositionAdjustmentForBarMetrics (ZUX_KINDOF(UIBarButtonItem *) instance, UIBarMetrics barMetrics) { return [instance backButtonBackgroundVerticalPositionAdjustmentForBarMetrics:barMetrics]; } ZUX_STATIC_INLINE void setBackButtonBackgroundVerticalPositionAdjustmentForBarMetrics (ZUX_KINDOF(UIBarButtonItem *) instance, CGFloat adjustment, UIBarMetrics barMetrics) { [instance setBackButtonBackgroundVerticalPositionAdjustment:adjustment forBarMetrics:barMetrics]; } #pragma mark - backButtonTitlePositionAdjustment - ZUX_STATIC_INLINE UIOffset backButtonTitlePositionAdjustmentForBarMetrics (ZUX_KINDOF(UIBarButtonItem *) instance, UIBarMetrics barMetrics) { return [instance backButtonTitlePositionAdjustmentForBarMetrics:barMetrics]; } ZUX_STATIC_INLINE void setBackButtonTitlePositionAdjustmentForBarMetrics (ZUX_KINDOF(UIBarButtonItem *) instance, UIOffset adjustment, UIBarMetrics barMetrics) { [instance setBackButtonTitlePositionAdjustment:adjustment forBarMetrics:barMetrics]; } #endif /* ZUtilsX_zappearance_h */
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved import copy import itertools import json import logging import numpy as np import os import pickle from collections import OrderedDict import pycocotools.mask as mask_util import torch from fvcore.common.file_io import PathManager import detectron2.utils.comm as comm from detectron2.data import MetadataCatalog from detectron2.structures import Boxes, BoxMode, pairwise_iou from detectron2.utils.logger import create_small_table from .coco_evaluation import instances_to_coco_json from .evaluator import DatasetEvaluator class LVISEvaluator(DatasetEvaluator): """ Evaluate object proposal and instance detection/segmentation outputs using LVIS's metrics and evaluation API. """ def __init__(self, dataset_name, cfg, distributed, output_dir=None): """ Args: dataset_name (str): name of the dataset to be evaluated. It must have the following corresponding metadata: "json_file": the path to the LVIS format annotation cfg (CfgNode): config instance distributed (True): if True, will collect results from all ranks for evaluation. Otherwise, will evaluate the results in the current process. output_dir (str): optional, an output directory to dump results. """ from lvis import LVIS self._tasks = self._tasks_from_config(cfg) self._distributed = distributed self._output_dir = output_dir self._cpu_device = torch.device("cpu") self._logger = logging.getLogger(__name__) self._metadata = MetadataCatalog.get(dataset_name) json_file = PathManager.get_local_path(self._metadata.json_file) self._lvis_api = LVIS(json_file) # Test set json files do not contain annotations (evaluation must be # performed using the LVIS evaluation server). self._do_evaluation = len(self._lvis_api.get_ann_ids()) > 0 def reset(self): self._predictions = [] self._lvis_results = [] def _tasks_from_config(self, cfg): """ Returns: tuple[str]: tasks that can be evaluated under the given configuration. """ tasks = ("bbox",) if cfg.MODEL.MASK_ON: tasks = tasks + ("segm",) return tasks def process(self, inputs, outputs): """ Args: inputs: the inputs to a LVIS model (e.g., GeneralizedRCNN). It is a list of dict. Each dict corresponds to an image and contains keys like "height", "width", "file_name", "image_id". outputs: the outputs of a LVIS model. It is a list of dicts with key "instances" that contains :class:`Instances`. """ for input, output in zip(inputs, outputs): prediction = {"image_id": input["image_id"]} if "instances" in output: instances = output["instances"].to(self._cpu_device) prediction["instances"] = instances_to_coco_json(instances, input["image_id"]) if "proposals" in output: prediction["proposals"] = output["proposals"].to(self._cpu_device) self._predictions.append(prediction) def evaluate(self): if self._distributed: comm.synchronize() self._predictions = comm.gather(self._predictions, dst=0) self._predictions = list(itertools.chain(*self._predictions)) if not comm.is_main_process(): return if len(self._predictions) == 0: self._logger.warning("[LVISEvaluator] Did not receive valid predictions.") return {} if self._output_dir: PathManager.mkdirs(self._output_dir) file_path = os.path.join(self._output_dir, "instances_predictions.pth") with PathManager.open(file_path, "wb") as f: torch.save(self._predictions, f) self._results = OrderedDict() if "proposals" in self._predictions[0]: self._eval_box_proposals() if "instances" in self._predictions[0]: self._eval_predictions(set(self._tasks)) # Copy so the caller can do whatever with results return copy.deepcopy(self._results) def _eval_predictions(self, tasks): """ Evaluate self._predictions on the given tasks. Fill self._results with the metrics of the tasks. """ self._logger.info("Preparing results in the LVIS format ...") self._lvis_results = list(itertools.chain(*[x["instances"] for x in self._predictions])) # unmap the category ids for LVIS (from 0-indexed to 1-indexed) for result in self._lvis_results: result["category_id"] += 1 if self._output_dir: file_path = os.path.join(self._output_dir, "lvis_instances_results.json") self._logger.info("Saving results to {}".format(file_path)) with PathManager.open(file_path, "w") as f: f.write(json.dumps(self._lvis_results)) f.flush() if not self._do_evaluation: self._logger.info("Annotations are not available for evaluation.") return self._logger.info("Evaluating predictions ...") for task in sorted(tasks): res = _evaluate_predictions_on_lvis( self._lvis_api, self._lvis_results, task, class_names=self._metadata.get("thing_classes"), ) self._results[task] = res def _eval_box_proposals(self): """ Evaluate the box proposals in self._predictions. Fill self._results with the metrics for "box_proposals" task. """ if self._output_dir: # Saving generated box proposals to file. # Predicted box_proposals are in XYXY_ABS mode. bbox_mode = BoxMode.XYXY_ABS.value ids, boxes, objectness_logits = [], [], [] for prediction in self._predictions: ids.append(prediction["image_id"]) boxes.append(prediction["proposals"].proposal_boxes.tensor.numpy()) objectness_logits.append(prediction["proposals"].objectness_logits.numpy()) proposal_data = { "boxes": boxes, "objectness_logits": objectness_logits, "ids": ids, "bbox_mode": bbox_mode, } with PathManager.open(os.path.join(self._output_dir, "box_proposals.pkl"), "wb") as f: pickle.dump(proposal_data, f) if not self._do_evaluation: self._logger.info("Annotations are not available for evaluation.") return self._logger.info("Evaluating bbox proposals ...") res = {} areas = {"all": "", "small": "s", "medium": "m", "large": "l"} for limit in [100, 1000]: for area, suffix in areas.items(): stats = _evaluate_box_proposals( self._predictions, self._lvis_api, area=area, limit=limit ) key = "AR{}@{:d}".format(suffix, limit) res[key] = float(stats["ar"].item() * 100) self._logger.info("Proposal metrics: \n" + create_small_table(res)) self._results["box_proposals"] = res # inspired from Detectron: # https://github.com/facebookresearch/Detectron/blob/a6a835f5b8208c45d0dce217ce9bbda915f44df7/detectron/datasets/json_dataset_evaluator.py#L255 # noqa def _evaluate_box_proposals(dataset_predictions, lvis_api, thresholds=None, area="all", limit=None): """ Evaluate detection proposal recall metrics. This function is a much faster alternative to the official LVIS API recall evaluation code. However, it produces slightly different results. """ # Record max overlap value for each gt box # Return vector of overlap values areas = { "all": 0, "small": 1, "medium": 2, "large": 3, "96-128": 4, "128-256": 5, "256-512": 6, "512-inf": 7, } area_ranges = [ [0 ** 2, 1e5 ** 2], # all [0 ** 2, 32 ** 2], # small [32 ** 2, 96 ** 2], # medium [96 ** 2, 1e5 ** 2], # large [96 ** 2, 128 ** 2], # 96-128 [128 ** 2, 256 ** 2], # 128-256 [256 ** 2, 512 ** 2], # 256-512 [512 ** 2, 1e5 ** 2], ] # 512-inf assert area in areas, "Unknown area range: {}".format(area) area_range = area_ranges[areas[area]] gt_overlaps = [] num_pos = 0 for prediction_dict in dataset_predictions: predictions = prediction_dict["proposals"] # sort predictions in descending order # TODO maybe remove this and make it explicit in the documentation inds = predictions.objectness_logits.sort(descending=True)[1] predictions = predictions[inds] ann_ids = lvis_api.get_ann_ids(img_ids=[prediction_dict["image_id"]]) anno = lvis_api.load_anns(ann_ids) gt_boxes = [ BoxMode.convert(obj["bbox"], BoxMode.XYWH_ABS, BoxMode.XYXY_ABS) for obj in anno ] gt_boxes = torch.as_tensor(gt_boxes).reshape(-1, 4) # guard against no boxes gt_boxes = Boxes(gt_boxes) gt_areas = torch.as_tensor([obj["area"] for obj in anno]) if len(gt_boxes) == 0 or len(predictions) == 0: continue valid_gt_inds = (gt_areas >= area_range[0]) & (gt_areas <= area_range[1]) gt_boxes = gt_boxes[valid_gt_inds] num_pos += len(gt_boxes) if len(gt_boxes) == 0: continue if limit is not None and len(predictions) > limit: predictions = predictions[:limit] overlaps = pairwise_iou(predictions.proposal_boxes, gt_boxes) _gt_overlaps = torch.zeros(len(gt_boxes)) for j in range(min(len(predictions), len(gt_boxes))): # find which proposal box maximally covers each gt box # and get the iou amount of coverage for each gt box max_overlaps, argmax_overlaps = overlaps.max(dim=0) # find which gt box is 'best' covered (i.e. 'best' = most iou) gt_ovr, gt_ind = max_overlaps.max(dim=0) assert gt_ovr >= 0 # find the proposal box that covers the best covered gt box box_ind = argmax_overlaps[gt_ind] # record the iou coverage of this gt box _gt_overlaps[j] = overlaps[box_ind, gt_ind] assert _gt_overlaps[j] == gt_ovr # mark the proposal box and the gt box as used overlaps[box_ind, :] = -1 overlaps[:, gt_ind] = -1 # append recorded iou coverage level gt_overlaps.append(_gt_overlaps) gt_overlaps = torch.cat(gt_overlaps, dim=0) gt_overlaps, _ = torch.sort(gt_overlaps) if thresholds is None: step = 0.05 thresholds = torch.arange(0.5, 0.95 + 1e-5, step, dtype=torch.float32) recalls = torch.zeros_like(thresholds) # compute recall for each iou threshold for i, t in enumerate(thresholds): recalls[i] = (gt_overlaps >= t).float().sum() / float(num_pos) # ar = 2 * np.trapz(recalls, thresholds) ar = recalls.mean() return { "ar": ar, "recalls": recalls, "thresholds": thresholds, "gt_overlaps": gt_overlaps, "num_pos": num_pos, } def _evaluate_predictions_on_lvis(lvis_gt, lvis_results, iou_type, class_names=None): """ Args: iou_type (str): kpt_oks_sigmas (list[float]): class_names (None or list[str]): if provided, will use it to predict per-category AP. Returns: a dict of {metric name: score} """ metrics = { "bbox": ["AP", "AP50", "AP75", "APs", "APm", "APl", "APr", "APc", "APf"], "segm": ["AP", "AP50", "AP75", "APs", "APm", "APl", "APr", "APc", "APf"], }[iou_type] logger = logging.getLogger(__name__) if len(lvis_results) == 0: # TODO: check if needed logger.warn("No predictions from the model! Set scores to -1") return {metric: -1 for metric in metrics} if iou_type == "segm": lvis_results = copy.deepcopy(lvis_results) # When evaluating mask AP, if the results contain bbox, LVIS API will # use the box area as the area of the instance, instead of the mask area. # This leads to a different definition of small/medium/large. # We remove the bbox field to let mask AP use mask area. for c in lvis_results: c.pop("bbox", None) from lvis import LVISEval, LVISResults lvis_results = LVISResults(lvis_gt, lvis_results) lvis_eval = LVISEval(lvis_gt, lvis_results, iou_type) lvis_eval.run() lvis_eval.print_results() # Pull the standard metrics from the LVIS results results = lvis_eval.get_results() results = {metric: float(results[metric] * 100) for metric in metrics} logger.info("Evaluation results for {}: \n".format(iou_type) + create_small_table(results)) return results
import * as React from "react"; import * as Constants from "~/common/constants"; import * as SVG from "~/common/svg"; import * as System from "~/components/system"; import * as Styles from "~/common/styles"; import * as Jumpers from "~/components/system/components/GlobalCarousel/jumpers"; import * as Utilities from "~/common/utilities"; import * as UploadUtilities from "~/common/upload-utilities"; import * as Validations from "~/common/validations"; import * as Actions from "~/common/actions"; import * as Events from "~/common/custom-events"; import { css } from "@emotion/react"; import { Alert } from "~/components/core/Alert"; import { motion, AnimateSharedLayout } from "framer-motion"; import { useDetectTextOverflow, useEscapeKey, useEventListener, useIsomorphicLayoutEffect, useLockScroll, } from "~/common/hooks"; import { Show } from "~/components/utility/Show"; import { ModalPortal } from "~/components/core/ModalPortal"; import { FullHeightLayout } from "~/components/system/components/FullHeightLayout"; import { LoaderSpinner } from "~/components/system/components/Loaders"; import { useUploadStore } from "~/components/core/Upload/store"; import SlateMediaObject from "~/components/core/SlateMediaObject"; import LinkIcon from "~/components/core/LinkIcon"; import ProfilePhoto from "~/components/core/ProfilePhoto"; /* ------------------------------------------------------------------------------------------------- * Carousel Header * -----------------------------------------------------------------------------------------------*/ const VisitLinkButton = ({ file }) => { return ( <System.ButtonTertiary onClick={(e) => e.stopPropagation()} style={{ color: Constants.semantic.textGrayDark, padding: "4px 8px 7px", marginLeft: 16, minHeight: 30, }} href={file.url} target="_blank" rel="noreferrer" type="link" > <LinkIcon file={file} width={16} height={16} style={{ marginRight: 4 }} /> <span style={{ whiteSpace: "nowrap" }}>Visit site</span> </System.ButtonTertiary> ); }; /* -----------------------------------------------------------------------------------------------*/ // NOTE(amine): manage file saving state export const useSaveHandler = ({ file, viewer, onAction }) => { const { saveCopy, isSaving } = useUploadStore((store) => { const selectedFile = store.state.fileLoading[UploadUtilities.getFileKey(file)]; return { isSaving: selectedFile?.status === "uploading", saveCopy: store.handlers.saveCopy }; }); const isSaved = React.useMemo(() => viewer?.libraryCids[file.cid], [ viewer?.libraryCids, file.cid, ]); const handleSave = async () => { if (!viewer) { Events.dispatchCustomEvent({ name: "slate-global-open-cta", detail: {} }); return; } if (isSaved) { const fileLibraryURL = `/_/data?id=${file.id}`; onAction({ type: "NAVIGATE", href: fileLibraryURL, redirect: false, }); return; } saveCopy(file); }; return { handleSave, isSaved, isSaving: isSaving }; }; const SaveFileButton = ({ file, viewer, onAction, ...props }) => { const { handleSave, isSaved, isSaving } = useSaveHandler({ file, viewer, onAction }); return ( <motion.button onClick={handleSave} disabled={isSaving} {...props}> {isSaving ? ( <LoaderSpinner style={{ height: 16, width: 16 }} /> ) : isSaved ? ( <SVG.CheckCircle height={16} style={{ pointerEvents: "none", color: Constants.system.green }} /> ) : ( <SVG.FilePlus height={16} style={{ pointerEvents: "none" }} /> )} </motion.button> ); }; /* -----------------------------------------------------------------------------------------------*/ const useCarouselJumperControls = () => { const [isControlVisible, setControlVisibility] = React.useState(false); const showControl = () => setControlVisibility(true); const hideControl = () => setControlVisibility(false); return [isControlVisible, { showControl, hideControl }]; }; const STYLES_HEADER_WRAPPER = (theme) => css` ${Styles.HORIZONTAL_CONTAINER_CENTERED}; position: absolute; width: 100%; min-height: 64px; padding: 13px 24px 10px; color: ${theme.semantic.textGrayDark}; border-bottom: 1px solid ${theme.semantic.borderGrayLight}; box-shadow: ${theme.shadow.lightSmall}; z-index: 1; background-color: ${theme.semantic.bgWhite}; @supports ((-webkit-backdrop-filter: blur(15px)) or (backdrop-filter: blur(15px))) { background-color: ${theme.semantic.bgBlurWhiteOP}; -webkit-backdrop-filter: blur(15px); backdrop-filter: blur(15px); } `; const STYLES_ACTION_BUTTON = css` ${Styles.BUTTON_RESET}; padding: 8px; `; function CarouselHeader({ isStandalone, viewer, onAction, data, external, isOwner, file, current, total, onClose, enableNextSlide, enablePreviousSlide, onNextSlide, onPreviousSlide, ...props }) { // NOTE(amine): Detect if the text is overflowing to show the MORE button const elementRef = React.useRef(); const isBodyOverflowing = useDetectTextOverflow({ ref: elementRef }, [file]); // NOTE(amine): jumpers handlers const [ isFileDescriptionVisible, { showControl: showFileDescription, hideControl: hideFileDescription }, ] = useCarouselJumperControls(); const [ isMoreInfoVisible, { showControl: showMoreInfo, hideControl: hideMoreInfo }, ] = useCarouselJumperControls(); const [ isEditInfoVisible, { showControl: showEditInfo, hideControl: hideEditInfo }, ] = useCarouselJumperControls(); const [ isShareFileVisible, { showControl: showShareFile, hideControl: hideShareFile }, ] = useCarouselJumperControls(); const [ isEditChannelsVisible, { showControl: showEditChannels, hideControl: hideEditChannels }, ] = useCarouselJumperControls(); const isJumperOpen = isFileDescriptionVisible || isMoreInfoVisible || isEditInfoVisible || isShareFileVisible || isEditChannelsVisible; const [isHeaderVisible, setHeaderVisibility] = React.useState(true); const timeoutRef = React.useRef(); const showHeader = () => { clearTimeout(timeoutRef.current); setHeaderVisibility(true); }; const hideHeader = (ms = 1000) => { timeoutRef.current = setTimeout(() => { if (isJumperOpen) return; setHeaderVisibility(false); }, ms); }; React.useEffect(() => { hideHeader(3000); return () => clearTimeout(timeoutRef.current); }, []); useIsomorphicLayoutEffect(() => { if (isJumperOpen) { return; } hideHeader(); }, [isJumperOpen]); return ( <> <ModalPortal> {isOwner && ( <Jumpers.EditInfo file={file} isOpen={isEditInfoVisible} onClose={hideEditInfo} /> )} {isOwner && ( <Jumpers.EditChannels viewer={viewer} file={file} isOpen={isEditChannelsVisible} onClose={hideEditChannels} /> )} <Jumpers.FileDescription file={file} isOpen={isFileDescriptionVisible} onClose={hideFileDescription} /> <Jumpers.MoreInfo viewer={viewer} external={external} isOwner={isOwner} file={file} isOpen={isMoreInfoVisible} onClose={hideMoreInfo} /> <Jumpers.Share file={file} data={data} viewer={viewer} isOpen={isShareFileVisible} onClose={hideShareFile} /> </ModalPortal> <CarouselControls enableNextSlide={enableNextSlide} enablePreviousSlide={enablePreviousSlide} onNextSlide={onNextSlide} onPreviousSlide={onPreviousSlide} showControls={isHeaderVisible} onClose={onClose} onMouseEnter={showHeader} onMouseOver={showHeader} onMouseLeave={() => hideHeader()} /> <motion.nav css={STYLES_HEADER_WRAPPER} initial={{ opacity: 0 }} animate={{ opacity: isHeaderVisible ? 1 : 0 }} transition={{ ease: "easeInOut", duration: 0.25 }} onMouseEnter={showHeader} onMouseOver={showHeader} onMouseLeave={() => hideHeader()} {...props} > <div> <div css={Styles.HORIZONTAL_CONTAINER}> <System.H5 color="textBlack" as="h1"> {file?.name || file?.filename} </System.H5> <System.H5 color="textGray" as="p" style={{ marginLeft: 32 }}> {current} / {total} </System.H5> </div> <div css={Styles.HORIZONTAL_CONTAINER_CENTERED} style={{ marginRight: 150 }}> <System.P3 ref={elementRef} style={{ marginTop: 1, wordBreak: "break-all" }} nbrOflines={1} color="textBlack" > {file.body} </System.P3> <Show when={isBodyOverflowing}> <System.H6 css={Styles.BUTTON_RESET} color="blue" as="button" onClick={showFileDescription} style={{ marginTop: 1 }} > MORE </System.H6> </Show> </div> </div> <div css={Styles.HORIZONTAL_CONTAINER_CENTERED} style={{ marginLeft: "auto" }}> <AnimateSharedLayout> <div css={Styles.HORIZONTAL_CONTAINER_CENTERED}> {isOwner && ( <motion.button layoutId="jumper-desktop-edit" onClick={showEditInfo} css={STYLES_ACTION_BUTTON} > <SVG.Edit style={{ pointerEvents: "none" }} /> </motion.button> )} {isOwner && ( <motion.button layoutId="jumper-desktop-channels" onClick={showEditChannels} style={{ marginLeft: 4 }} css={STYLES_ACTION_BUTTON} > <SVG.Hash style={{ pointerEvents: "none" }} /> </motion.button> )} {!isOwner && ( <SaveFileButton style={{ marginLeft: 4 }} css={STYLES_ACTION_BUTTON} file={file} viewer={viewer} onAction={onAction} /> )} <motion.button layoutId="jumper-desktop-share" onClick={showShareFile} style={{ marginLeft: 4 }} css={STYLES_ACTION_BUTTON} > <SVG.Share style={{ pointerEvents: "none" }} /> </motion.button> <motion.button layoutId="jumper-desktop-info" onClick={showMoreInfo} style={{ marginLeft: 4 }} css={STYLES_ACTION_BUTTON} > <SVG.InfoCircle style={{ pointerEvents: "none" }} /> </motion.button> {file.isLink ? <VisitLinkButton file={file} /> : null} </div> </AnimateSharedLayout> {isStandalone ? ( <a href={`/${file.owner.username}`} css={Styles.LINK} style={{ marginLeft: 80 }}> <div style={{ gap: 8, maxWidth: "138px", justifyContent: "flex-end" }} css={Styles.HORIZONTAL_CONTAINER_CENTERED} > <div> <ProfilePhoto user={file.owner} style={{ borderRadius: "8px" }} size={20} /> </div> <p css={[Styles.H5, Styles.OVERFLOW_ELLIPSIS]}> {Utilities.getUserDisplayName(file.owner)} </p> </div> </a> ) : ( <div style={{ marginLeft: 80 }}> <button onClick={onClose} css={STYLES_ACTION_BUTTON}> <SVG.Dismiss /> </button> </div> )} </div> </motion.nav> </> ); } const STYLES_CAROUSEL_MOBILE_HEADER = (theme) => css` position: relative; ${Styles.HORIZONTAL_CONTAINER_CENTERED}; padding: 7px 8px 3px; color: ${theme.semantic.textGrayDark}; border-bottom: 1px solid ${theme.semantic.borderGrayLight}; background-color: ${theme.semantic.bgWhite}; @supports ((-webkit-backdrop-filter: blur(15px)) or (backdrop-filter: blur(15px))) { background-color: ${theme.semantic.bgBlurWhiteOP}; -webkit-backdrop-filter: blur(15px); backdrop-filter: blur(15px); } `; const STYLES_CAROUSEL_MOBILE_FOOTER = (theme) => css` ${Styles.HORIZONTAL_CONTAINER_CENTERED}; justify-content: space-between; z-index: 1; width: 100%; padding: 8px 16px; border-top: 1px solid ${theme.semantic.borderGrayLight}; color: ${theme.semantic.textGrayDark}; min-height: 48px; background-color: ${theme.semantic.bgWhite}; @supports ((-webkit-backdrop-filter: blur(15px)) or (backdrop-filter: blur(15px))) { background-color: ${theme.semantic.bgBlurWhite}; -webkit-backdrop-filter: blur(15px); backdrop-filter: blur(15px); } `; const STYLES_CAROUSEL_MOBILE_SLIDE_COUNT = css` position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); `; function CarouselHeaderMobile({ isStandalone, file, current, total, onClose, onNextSlide, onPreviousSlide, }) { const isPreviousButtonDisabled = current === 1; const isNextButtonDisabled = current === total; return ( <nav css={STYLES_CAROUSEL_MOBILE_HEADER} style={{ justifyContent: "space-between" }}> {!isStandalone && ( <> <div style={{ width: 76 }}> <button css={STYLES_ACTION_BUTTON} disabled={isPreviousButtonDisabled} style={isPreviousButtonDisabled ? { color: Constants.system.grayLight3 } : null} onClick={onPreviousSlide} > <SVG.ChevronLeft width={16} height={16} /> </button> <button style={ isNextButtonDisabled ? { color: Constants.system.grayLight3, marginLeft: 12 } : { marginLeft: 12, } } disabled={isNextButtonDisabled} css={STYLES_ACTION_BUTTON} onClick={onNextSlide} > <SVG.ChevronRight width={16} height={16} /> </button> </div> <System.H5 color="textGray" as="p" css={STYLES_CAROUSEL_MOBILE_SLIDE_COUNT}> {current} / {total} </System.H5> </> )} {isStandalone ? ( <div style={{ gap: 8, maxWidth: "138px", justifyContent: "flex-end" }} css={Styles.HORIZONTAL_CONTAINER_CENTERED} > <div> <ProfilePhoto user={file.owner} style={{ borderRadius: "8px" }} size={20} /> </div> <p css={[Styles.H5, Styles.OVERFLOW_ELLIPSIS]}> {Utilities.getUserDisplayName(file.owner)} </p> </div> ) : ( <div style={{ textAlign: "right" }}> <button onClick={onClose} css={STYLES_ACTION_BUTTON}> <SVG.Dismiss /> </button> </div> )} </nav> ); } function CarouselFooterMobile({ file, onAction, external, isOwner, data, viewer }) { const [ isEditInfoVisible, { showControl: showEditInfo, hideControl: hideEditInfo }, ] = useCarouselJumperControls(); const [ isShareFileVisible, { showControl: showShareFile, hideControl: hideShareFile }, ] = useCarouselJumperControls(); const [ isMoreInfoVisible, { showControl: showMoreInfo, hideControl: hideMoreInfo }, ] = useCarouselJumperControls(); const [ isEditChannelsVisible, { showControl: showEditChannels, hideControl: hideEditChannels }, ] = useCarouselJumperControls(); return ( <> <ModalPortal> {isOwner && ( <Jumpers.EditInfoMobile file={file} isOpen={isEditInfoVisible} onClose={hideEditInfo} /> )} {isOwner && ( <Jumpers.EditChannelsMobile viewer={viewer} file={file} isOpen={isEditChannelsVisible} onClose={hideEditChannels} /> )} <Jumpers.ShareMobile file={file} isOpen={isShareFileVisible} data={data} viewer={viewer} onClose={hideShareFile} /> <Jumpers.MoreInfoMobile viewer={viewer} external={external} isOwner={isOwner} file={file} isOpen={isMoreInfoVisible} onClose={hideMoreInfo} /> </ModalPortal> <AnimateSharedLayout> <nav css={STYLES_CAROUSEL_MOBILE_FOOTER}> {isOwner && ( <motion.button layoutId="jumper-mobile-edit" css={STYLES_ACTION_BUTTON} onClick={showEditInfo} > <SVG.Edit /> </motion.button> )} {isOwner && ( <motion.button layoutId="jumper-mobile-channels" style={{ marginLeft: 4 }} css={STYLES_ACTION_BUTTON} onClick={showEditChannels} > <SVG.Hash /> </motion.button> )} {!isOwner && ( <SaveFileButton style={{ marginLeft: 4 }} css={STYLES_ACTION_BUTTON} file={file} viewer={viewer} onAction={onAction} /> )} <motion.button layoutId="jumper-mobile-share" style={{ marginLeft: 4 }} css={STYLES_ACTION_BUTTON} onClick={showShareFile} > <SVG.Share /> </motion.button> <motion.button layoutId="jumper-mobile-info" style={{ marginLeft: 4 }} css={STYLES_ACTION_BUTTON} onClick={showMoreInfo} > <SVG.InfoCircle /> </motion.button> {file.isLink ? <VisitLinkButton file={file} /> : null} </nav> </AnimateSharedLayout> </> ); } /* ------------------------------------------------------------------------------------------------- * Carousel Controls * -----------------------------------------------------------------------------------------------*/ const useCarouselKeyCommands = ({ handleNext, handlePrevious, handleClose }) => { const handleKeyDown = (e) => { const inputs = document.querySelectorAll("input"); for (let elem of inputs) { if (document.activeElement === elem) { return; } } const textareas = document.querySelectorAll("textarea"); for (let elem of textareas) { if (document.activeElement === elem) { return; } } switch (e.key) { case "Right": case "ArrowRight": handleNext(); break; case "Left": case "ArrowLeft": handlePrevious(); break; } }; useEscapeKey(handleClose); useEventListener({ type: "keydown", handler: handleKeyDown }); }; const STYLES_CONTROLS_BUTTON = (theme) => css` ${Styles.BUTTON_RESET}; background-color: ${theme.semantic.bgGrayLight}; border-radius: 8px; border: 1px solid ${theme.semantic.borderGrayLight}; padding: 10px; box-shadow: ${theme.shadow.lightMedium}; svg { display: block; } `; const STYLES_CONTROLS_WRAPPER = css` ${Styles.CONTAINER_CENTERED}; position: absolute; width: 122px; height: 80%; z-index: 1; top: 50%; transform: translateY(-50%); padding-left: 24px; padding-right: 24px; `; function CarouselControls({ enableNextSlide, enablePreviousSlide, onNextSlide, onPreviousSlide, showControls, onClose, ...props }) { useCarouselKeyCommands({ handleNext: onNextSlide, handlePrevious: onPreviousSlide, handleClose: onClose, }); return ( <> <div css={STYLES_CONTROLS_WRAPPER} style={{ left: 0, justifyContent: "flex-start" }} {...props} > {enablePreviousSlide ? ( <motion.button onClick={onPreviousSlide} initial={{ opacity: 0 }} animate={{ opacity: showControls ? 1 : 0 }} transition={{ ease: "easeInOut", duration: 0.25 }} css={STYLES_CONTROLS_BUTTON} > <SVG.ChevronLeft width={16} /> </motion.button> ) : null} </div> <div css={STYLES_CONTROLS_WRAPPER} style={{ right: 0, justifyContent: "flex-end" }} {...props} > {enableNextSlide ? ( <motion.button onClick={onNextSlide} initial={{ opacity: 0 }} animate={{ opacity: showControls ? 1 : 0 }} css={STYLES_CONTROLS_BUTTON} > <SVG.ChevronRight width={16} /> </motion.button> ) : null} </div> </> ); } /* ------------------------------------------------------------------------------------------------- * Carousel Content * -----------------------------------------------------------------------------------------------*/ const STYLES_CONTENT = (theme) => css` position: relative; width: 100%; height: 100%; display: flex; align-items: center; justify-content: center; @media (max-width: ${theme.sizes.mobile}px) { flex-direction: column; overflow-y: auto; justify-content: flex-start; } `; const STYLES_PREVIEW_WRAPPER = (theme) => css` ${Styles.CONTAINER_CENTERED}; position: relative; width: 100%; height: 100%; background-color: ${theme.semantic.bgGrayLight4}; @media (max-width: ${theme.sizes.mobile}px) { min-height: 75vh; height: 75vh; overflow: hidden; } `; export function CarouselContent({ objects, index, data, isMobile, viewer, sidebar, style, onClose, }) { const file = objects?.[index]; useLockScroll(); const { linkHtml, linkIFrameAllowed } = file; const isNFTLink = Validations.isNFTLink(file); // NOTE(amine): hide the title and description when using LinkCard as SlateMediaObject const hideDescription = file.isLink && (!linkHtml || !linkIFrameAllowed || isNFTLink); return ( <> <Alert viewer={viewer} noWarning id={isMobile ? "slate-mobile-alert" : null} /> <div css={STYLES_CONTENT} style={style} onClick={onClose}> <div css={STYLES_PREVIEW_WRAPPER}> <SlateMediaObject file={file} isMobile={isMobile} /> </div> {!hideDescription && ( <div css={Styles.MOBILE_ONLY} style={{ padding: "13px 16px 44px", width: "100%" }}> <System.H5 color="textBlack" as="h1"> {file?.name || file?.filename} </System.H5> <Show when={file?.body}> <System.P2 color="textBlack" style={{ marginTop: 4 }}> {file?.body} </System.P2> </Show> <Show when={file.isLink}> <div style={{ marginTop: 5 }} css={Styles.HORIZONTAL_CONTAINER_CENTERED}> <LinkIcon file={file} width={12} height={12} /> <System.P2 as="a" nbrOflines={1} href={file.url} style={{ marginLeft: 5, textDecoration: "none", color: Constants.system.blue }} > {file.url} </System.P2> </div> </Show> </div> )} </div> </> ); } /* ------------------------------------------------------------------------------------------------- * Global Carousel * -----------------------------------------------------------------------------------------------*/ const useCarouselViaParams = ({ index, params, objects, onChange }) => { const findSelectedIndex = () => { const id = params?.id; if (!id) return -1; let index = objects.findIndex((elem) => elem.id === id); return index; }; React.useEffect(() => { if (index !== -1) return; const selectedIndex = findSelectedIndex(); if (selectedIndex !== index) onChange(index); }, [params?.id]); React.useEffect(() => { if (params?.id) { const index = findSelectedIndex(); onChange(index); } }, [params]); }; const getCarouselHandlers = ({ index, objects, params, onChange, onAction }) => { const handleNext = (e) => { if (e) e.stopPropagation(); let nextIndex = index + 1; if (nextIndex >= objects.length) return; let { id } = objects[nextIndex]; onChange(nextIndex); onAction({ type: "UPDATE_PARAMS", params: { ...params, id }, redirect: true }); }; const handlePrevious = (e) => { if (e) e.stopPropagation(); let prevIndex = index - 1; if (prevIndex < 0) return; let { id } = objects[prevIndex]; onChange(prevIndex); onAction({ type: "UPDATE_PARAMS", params: { ...params, id }, redirect: true }); }; const handleClose = (e) => { if (e) e.stopPropagation(), e.preventDefault(); let params = { ...params }; delete params.id; onAction({ type: "UPDATE_PARAMS", params, redirect: true }); onChange(-1); }; return { handleNext, handlePrevious, handleClose }; }; const STYLES_ROOT = (theme) => css` ${Styles.VERTICAL_CONTAINER}; position: fixed; left: 0; right: 0; bottom: 0; top: 0; color: ${Constants.system.white}; z-index: ${Constants.zindex.modal}; background-color: rgba(0, 0, 0, 0.8); // Note(Amine): we're using the blur filter to fix a weird backdrop-filter's bug in chrome filter: blur(0px); @supports ((-webkit-backdrop-filter: blur(15px)) or (backdrop-filter: blur(15px))) { -webkit-backdrop-filter: blur(15px); backdrop-filter: blur(15px); } @media (max-width: ${Constants.sizes.mobile}px) { background-color: ${theme.semantic.bgWhite}; } @keyframes global-carousel-fade-in { from { transform: translateX(8px); opacity: 0; } to { transform: translateX(0px); opacity: 1; } } animation: global-carousel-fade-in 400ms ease; `; export function GlobalCarousel({ isStandalone, objects, index, params, data, isMobile, onChange, onAction, viewer, external, isOwner, sidebar, style, }) { const file = objects?.[index]; const isCarouselOpen = (index > 0 || index <= objects.length) && !!file; useCarouselViaParams({ index, params, objects, onChange }); if (!isCarouselOpen) return null; const { handleNext, handlePrevious, handleClose } = getCarouselHandlers({ index, objects, params, onChange, onAction, }); return ( <FullHeightLayout css={STYLES_ROOT}> {isMobile ? ( <CarouselHeaderMobile isStandalone={isStandalone} file={file} current={index + 1} total={objects.length} onPreviousSlide={handlePrevious} onNextSlide={handleNext} onClose={handleClose} enableNextSlide={index < objects.length - 1} enablePreviousSlide={index > 0} /> ) : ( <CarouselHeader isStandalone={isStandalone} viewer={viewer} external={external} isOwner={isOwner} data={data} file={file} current={index + 1} total={objects.length} onAction={onAction} enableNextSlide={index < objects.length - 1} enablePreviousSlide={index > 0} onNextSlide={handleNext} onPreviousSlide={handlePrevious} onClose={handleClose} /> )} <CarouselContent objects={objects} index={index} data={data} isMobile={isMobile} viewer={viewer} sidebar={sidebar} style={style} onClose={handleClose} /> {isMobile ? ( <CarouselFooterMobile file={file} viewer={viewer} data={data} external={external} onAction={onAction} isOwner={isOwner} /> ) : null} </FullHeightLayout> ); }
from __future__ import print_function, division, absolute_import import time import numpy as np NORTH = (-1, 0) SOUTH = (1, 0) EAST = (0, 1) WEST = (0, -1) class Carrier(object): def __init__(self, initial_map): self.pos = np.array((0, 0), dtype=int) self.vel = np.array(NORTH, dtype=int) self.infected = set() self.infections_caused = 0 self.initialize_map(initial_map) def initialize_map(self, initial_map): self.infected.clear() n = len(initial_map) c = (n - 1) // 2 for i in range(len(initial_map)): for j in range(len(initial_map[i])): if initial_map[i][j] == '#': self.infected.add((i-c, j-c)) def turn_left(self): drow, dcol = self.vel if (drow, dcol) == NORTH: self.vel[:] = WEST elif (drow, dcol) == EAST: self.vel[:] = NORTH elif (drow, dcol) == SOUTH: self.vel[:] = EAST elif (drow, dcol) == WEST: self.vel[:] = SOUTH def turn_right(self): drow, dcol = self.vel if (drow, dcol) == NORTH: self.vel[:] = EAST elif (drow, dcol) == EAST: self.vel[:] = SOUTH elif (drow, dcol) == SOUTH: self.vel[:] = WEST elif (drow, dcol) == WEST: self.vel[:] = NORTH def burst(self): current_infected = False print(' Initial pos:', tuple(self.pos.tolist())) print(' Initial vel:', tuple(self.vel.tolist())) print(' On Infected:', tuple(self.pos.tolist()) in self.infected) if tuple(self.pos.tolist()) in self.infected: current_infected = True self.turn_right() else: self.turn_left() if current_infected: # Clean self.infected.remove(pos_tup) print(' Action:', 'CLEAN') else: # Infect self.infected.add(tuple(self.pos.tolist())) print(' Action:', 'INFECT') self.infections_caused += 1 self.pos += self.vel print(' Infected population:', len(self.infected)) print(' Final pos:', tuple(self.pos.tolist())) print(' Final vel:', tuple(self.vel.tolist())) print() #self.print_grid() print() def print_grid(self): max_row = np.max(np.abs([i[0] for i in self.infected])) max_col = np.max(np.abs([i[1] for i in self.infected])) n = 2 * max((max_row, max_col)) + 1 c = (n - 1) // 2 mat = np.empty((n, n), dtype=str) mat[:, :] = '.' for (i, j) in self.infected: mat[i+c, j+c] = '#' if tuple(self.pos.tolist()) in self.infected: mat[self.pos[0]+c, self.pos[1]+c] = u'\u25CF' else: mat[self.pos[0]+c, self.pos[1]+c] = u'\u25CB' for row in mat: print(' '.join(row)) class CarrierPart2(Carrier): def __init__(self, initial_map): self.pos = np.array((0, 0), dtype=int) self.vel = np.array(NORTH, dtype=int) self.infections_caused = 0 self.problem_nodes = {} self.initialize_map(initial_map) def initialize_map(self, initial_map): self.problem_nodes.clear() n = len(initial_map) c = (n - 1) // 2 for i in range(len(initial_map)): for j in range(len(initial_map[i])): if initial_map[i][j] == '#': self.problem_nodes[i-c, j-c] = '#' # # def turn_left(self): # drow, dcol = self.vel # if (drow, dcol) == NORTH: # self.vel[:] = WEST # elif (drow, dcol) == EAST: # self.vel[:] = NORTH # elif (drow, dcol) == SOUTH: # self.vel[:] = EAST # elif (drow, dcol) == WEST: # self.vel[:] = SOUTH # # def turn_right(self): # drow, dcol = self.vel # if (drow, dcol) == NORTH: # self.vel[:] = EAST # elif (drow, dcol) == EAST: # self.vel[:] = SOUTH # elif (drow, dcol) == SOUTH: # self.vel[:] = WEST # elif (drow, dcol) == WEST: # self.vel[:] = NORTH def burst(self): pos_tup = tuple(self.pos.tolist()) current_status = self.problem_nodes.get(pos_tup, '.') # print(self.infected) # # print(' Initial pos:', pos_tup) # print(' Initial vel:', tuple(self.vel.tolist())) # print(' On Infected:', current_infected) if current_status == '#': self.problem_nodes[pos_tup] = 'F' self.turn_right() elif current_status == 'W': self.problem_nodes[pos_tup] = '#' self.infections_caused += 1 elif current_status == 'F': self.turn_left() self.turn_left() del self.problem_nodes[pos_tup] else: # Clean self.turn_left() self.problem_nodes[pos_tup] = 'W' self.pos += self.vel # print(' Infected population:', len(self.infected)) # print(' Final pos:', pos_tup) # print(' Final vel:', tuple(self.vel.tolist())) # print() # #self.print_grid() # print() def solve(inp, num_bursts=7): # c = Carrier(inp) # # #c.print_grid() # # print() # # for i in range(num_bursts): # print('Burst', i) # c.burst() # # print('Part 1 Infections caused:', c.infections_caused) c2 = CarrierPart2(inp) print() for i in range(num_bursts): # print('Burst', i) c2.burst() print('Part 2 Infections caused:', c2.infections_caused) # 2510774 if __name__ == '__main__': with open('input.txt', 'r') as f: puzzle_input = [line.strip() for line in f.readlines() if line] t0 = time.time() solve(puzzle_input, num_bursts=10000000) print('Time to solve part 1:', time.time()-t0, 'sec')
import { useEffect } from "react" function PersistGate({persistor = {}, children}) { useEffect(() => { persistor.initialize(); }, [persistor]) return <>{children}</> } export { PersistGate }
const WHITE = '#FFFFFF'; const BLACK = '#000000'; const DARK_RED = '#BD1B26'; const BUTTON_COLOR = '#9E3183'; const BG_YELLOW = '#F8F2D9'; const FONT_XXXL = 40; const FONT_SIZE_30 = 30; const FONT_SIZE_22 = 22; const FONT_XXL = 32; const FONT_XL = 28; const FONT_L = 24; const FONT_REGULAR = 20; const FONT_M = 18; const FONT_S = 16; const FONT_XS = 14; const FONT_XXS = 12; const FONT_XXXS = 10; export default { color_white: WHITE, color_black: BLACK, color_dark_red: DARK_RED, color_button: BUTTON_COLOR, bg_yellow: BG_YELLOW, text_size_xxxl: FONT_XXXL, text_size_xxl: FONT_XXL, text_size_xl: FONT_XL, text_size_l: FONT_L, text_size_regular: FONT_REGULAR, text_size_m: FONT_M, text_size_s: FONT_S, text_size_xs: FONT_XS, text_size_xxs: FONT_XXS, text_size_xxxs: FONT_XXXS, text_size_30: FONT_SIZE_30, text_size_22: FONT_SIZE_22, };
"""Spinbox module.""" from PyQt6 import QtWidgets # type: ignore[import] class SpinBox(QtWidgets.QWidget): """SpinBox class.""" _label: "QtWidgets.QLabel" _spin_box: "QtWidgets.QSpinBox" _lay: "QtWidgets.QHBoxLayout" def __init__(self, parent=None): """Initialize.""" super().__init__(parent) self._lay = QtWidgets.QHBoxLayout(self) self._label = QtWidgets.QLabel() self._spin_box = QtWidgets.QSpinBox() self._lay.addWidget(self._label) self._lay.addWidget(self._spin_box) def getMax(self) -> int: """Return Maximum.""" return self._spin_box.maximum() def setMax(self, max: int) -> None: """Set Maximum.""" self._spin_box.setMaximum(max) def getMin(self) -> int: """Return Minimum.""" return self._spin_box.minimum() def setMin(self, min: int) -> None: """Set Minimum.""" self._spin_box.setMinimum(min) def getValue(self) -> int: """Return value.""" return self._spin_box.value() def setValue(self, value: int) -> None: """Set Minimum.""" self._spin_box.setValue(value) def getLabel(self) -> str: """Return label.""" return self._label.text() def setLabel(self, label: str) -> None: """Set label.""" self._label.setText(label) maximum: int = property(getMax, setMax) # type: ignore [assignment] # noqa: F821 minimum: int = property(getMin, setMin) # type: ignore [assignment] # noqa: F821 value: int = property(getValue, setValue) # type: ignore [assignment] # noqa: F821 label: str = property(getLabel, setLabel) # type: ignore [assignment] # noqa: F821
# This file is part of ranger, the console file manager. # License: GNU GPL version 3, see the file "AUTHORS" for details. from ranger.gui.widgets.view_base import ViewBase from ranger.gui.widgets.browsercolumn import BrowserColumn class ViewMultipane(ViewBase): def __init__(self, win): ViewBase.__init__(self, win) self.fm.signal_bind('tab.layoutchange', self._layoutchange_handler) self.fm.signal_bind('tab.change', self._tabchange_handler) self.rebuild() def _layoutchange_handler(self): if self.fm.ui.browser == self: self.rebuild() def _tabchange_handler(self, signal): if self.fm.ui.browser == self: if signal.old: signal.old.need_redraw = True if signal.new: signal.new.need_redraw = True def rebuild(self): self.columns = [] for child in self.container: self.remove_child(child) child.destroy() for name, tab in self.fm.tabs.items(): column = BrowserColumn(self.win, 0, tab=tab) column.main_column = True column.display_infostring = True if name == self.fm.current_tab: self.main_column = column self.columns.append(column) self.add_child(column) self.resize(self.y, self.x, self.hei, self.wid) def resize(self, y, x, hei, wid): ViewBase.resize(self, y, x, hei, wid) column_width = int((float(wid) - len(self.columns) + 1) / len(self.columns)) left = 0 top = 0 for i, column in enumerate(self.columns): column.resize(top, left, hei, max(1, column_width)) left += column_width + 1 column.need_redraw = True self.need_redraw = True
from os.path import join as pjoin # Format expected by setup.py and doc/source/conf.py: string of form "X.Y.Z" _version_major = 0 _version_minor = 1 _version_micro = 2 # use '' for first of series, number for 1 and above _version_extra = None # Uncomment this for full releases # Construct full version string from these. _ver = [_version_major, _version_minor] if _version_micro: _ver.append(_version_micro) if _version_extra: _ver.append(_version_extra) __version__ = '.'.join(map(str, _ver)) CLASSIFIERS = ["Development Status :: 3 - Alpha", "Environment :: Console", "Intended Audience :: Science/Research", "License :: OSI Approved :: MIT License", "Operating System :: OS Independent", "Programming Language :: Python", "Topic :: Scientific/Engineering"] # Description should be a one-liner: description = "Pure Python PCD reader/writer, MW fork" # Long description will go up on the pypi page long_description = """\ pypcd ======== Pure Python reader/writer for the PCL ``pcd`` data format for point clouds. Please go to the repository README_. .. _README: https://github.com/dimatura/pypcd/blob/master/README.md License ======= ``pypcd`` is licensed under the terms of the MIT license. See the file "LICENSE" for information on the history of this software, terms & conditions for usage, and a DISCLAIMER OF ALL WARRANTIES. All trademarks referenced herein are property of their respective holders. Copyright (c) 2015--, Daniel Maturana """ NAME = "pypcd" MAINTAINER = "Daniel Maturana" MAINTAINER_EMAIL = "dimatura@cmu.edu" DESCRIPTION = description LONG_DESCRIPTION = long_description URL = "http://github.com/dimatura/pypcd" DOWNLOAD_URL = "" LICENSE = "MIT" AUTHOR = "Daniel Maturana" AUTHOR_EMAIL = "dimatura@cmu.edu" PLATFORMS = "OS Independent" MAJOR = _version_major MINOR = _version_minor MICRO = _version_micro VERSION = __version__ PACKAGES = ['pypcd', 'pypcd.tests'] PACKAGE_DATA = {'pypcd': [pjoin('data', '*')]} INSTALL_REQUIRES = ["numpy", "python-lzf"]
import React from 'react'; import { Formik, Field } from 'formik'; import { cleanup, fireEvent, render } from '@testing-library/react'; import { INPUT, INPUT_ERROR, INPUT_FEEDBACK_GROUPING, LABEL } from 'common/constants/testIDs'; import { validationErrorMessages } from 'common/constants/messages'; import createSnapshotTest from 'test-utils/createSnapshotTest'; import Form from '../../Form'; import Input from '../Input'; describe('Input', () => { const requiredProps = { field: { name: 'someInputName', }, form: { touched: { someInputName: false }, errors: { someInputName: '' } }, onBlur: jest.fn(), onChange: jest.fn(), label: 'Some Input:', }; it('should render with required props', () => { createSnapshotTest( <Formik> <Input {...requiredProps} /> </Formik>, ); }); it('should render with label, even if hidden', () => { const component = render( <Formik> <Input {...requiredProps} isLabelHidden /> </Formik>, ); expect(component.container.querySelectorAll('label').length).toBe(1); }); it('should display an error message when a required field is touched', async () => { const label = 'label'; const validate = () => ({ test: 'Required' }); const component = render( <Formik validate={validate}> <Form> <Field id="test" name="test" label={label} component={Input} />, </Form> </Formik>, ); fireEvent.blur(component.queryByLabelText(label)); const Alert = await component.findByTestId(INPUT_ERROR); expect(Alert.textContent).toBe(validationErrorMessages.required); }); it('should render the label after the input for radio inputs', () => { const component = render( <Formik> <Input {...requiredProps} type="radio" /> </Formik>, ); const Radio = component.queryByTestId(INPUT); const InputFeedbackGrouping = component.queryByTestId(INPUT_FEEDBACK_GROUPING); const Label = component.queryByTestId(LABEL); // Selectors are rendered expect(InputFeedbackGrouping).not.toBeNull(); expect(Label).not.toBeNull(); // Grouping has input element expect(InputFeedbackGrouping.firstChild).toBe(component.container.querySelector('input')); // Assert ordering expect(Radio.childNodes[0]).toBe(InputFeedbackGrouping); expect(Radio.childNodes[1]).toBe(Label); }); it('should render the label before the input for all other input types', () => { const otherInputTypes = [ 'button', 'color', 'date', 'datetime-local', 'email', 'file', 'hidden', 'image', 'month', 'number', 'password', 'range', 'reset', 'search', 'submit', 'tel', 'text', 'time', 'url', 'week', ]; // enforce list correctness expect(otherInputTypes).not.toContain('radio'); expect(otherInputTypes).not.toContain('checkbox'); otherInputTypes.forEach(inputType => { const { container, queryByTestId, unmount } = render( <Formik> <Input {...requiredProps} type={inputType} /> </Formik>, ); const SomeInput = queryByTestId(INPUT); const InputFeedbackGrouping = queryByTestId(INPUT_FEEDBACK_GROUPING); const Label = queryByTestId(LABEL); // Selectors are rendered expect(InputFeedbackGrouping).not.toBeNull(); expect(Label).not.toBeNull(); // Grouping has input element expect(InputFeedbackGrouping.firstChild).toBe(container.querySelector('input')); // Assert ordering expect(SomeInput.childNodes[0]).toBe(Label); expect(SomeInput.childNodes[1]).toBe(InputFeedbackGrouping); // The iteration seems to happen faster than the tests... unmount(); cleanup(); }); }); });
import { getDstStr } from './utils'; // TODO: let defaultDenyList = [ // /google/, ]; let denyListLength = defaultDenyList.length; export function setDenyList(denyList) { defaultDenyList = denyList; denyListLength = denyList.length; } export function filter(dstInfo) { const dstStr = getDstStr(dstInfo); let i; for (i = 0; i < denyListLength; i += 1) { if (defaultDenyList[i].test(dstStr)) { return false; } } return true; }
/// Copyright (c) 2012 Ecma International. All rights reserved. /// Ecma International makes this code available under the terms and conditions set /// forth on http://hg.ecmascript.org/tests/test262/raw-file/tip/LICENSE (the /// "Use Terms"). Any redistribution of this code must retain the above /// copyright and this notice and otherwise comply with the Use Terms. /** * @path ch15/15.4/15.4.4/15.4.4.22/15.4.4.22-9-c-ii-21.js * @description Array.prototype.reduceRight - null can be used as accumulator */ function testcase() { var accessed = false; function callbackfn(prevVal, curVal, idx, obj) { accessed = true; return prevVal === null; } var obj = { 0: 11, length: 1 }; return Array.prototype.reduceRight.call(obj, callbackfn, null) === true && accessed; } runTestCase(testcase);
const taskApp = new TaskManager(); taskApp.load(); taskApp.render(); const formValidator = document.querySelector('#todo-form'); const taskInput = document.querySelector('#InputTaskName'); const taskDesc = document.querySelector('#InputTaskDescription'); const taskDueDate = document.querySelector('#duedate'); const taskAssign = document.querySelector('#assigned-name'); const taskStatus = document.querySelector('#task-status'); let rate = 1; // Disable selection of date prior to today's date in html date selector const todayInput = new Date(); let todayDay = todayInput.getDate().toString(); let todayMonth = (todayInput.getMonth() + 1).toString(); const todayYear = todayInput.getFullYear().toString(); console.log(todayInput); console.log(`Day: ${todayDay}, Month: ${todayMonth}, Year: ${todayYear}`); console.log(todayMonth.length); if (todayDay.length < 2) { todayDay = `0${todayDay}`; } if (todayMonth.length < 2) { todayMonth = `0${todayMonth}`; } console.log(`Day: ${todayDay}, Month: ${todayMonth}, Year: ${todayYear}`); const today = `${todayYear}-${todayMonth}-${todayDay}`; console.log(today); document.getElementById('duedate').setAttribute('min', today); function isValidDate(dateString) { // Date format: YYYY-MM-DD const datePattern = /^(19|20)\d\d[- /.](0[1-9]|1[012])[- /.](0[1-9]|[12][0-9]|3[01])$/; // Check if the date string format is a match const matchArray = dateString.match(datePattern); if (matchArray == null) { return false; } // Remove any non digit characters const cleanDateString = dateString.replace(/\D/g, ''); // Parse integer values from date string const year = parseInt(cleanDateString.substr(0, 4)); const month = parseInt(cleanDateString.substr(4, 2)); const day = parseInt(cleanDateString.substr(6, 2)); // Define number of days per month const daysInMonth = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; // Adjust for leap years if (year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)) { daysInMonth[1] = 29; } // check month and day range if (month < 1 || month > 12 || day < 1 || day > daysInMonth[month - 1]) { return false; } // You made it through! return true; } // validating date input const validateDate = (dateString) => { const tdyDate = new Date(today); console.log(tdyDate); const inDate = new Date(dateString.value); console.log(inDate); if (+inDate < +tdyDate) { console.log('Smalleer!'); } else { console.log('looks ok!!'); } if (isValidDate(dateString.value) && +inDate >= +tdyDate) { dateString.classList.add('is-valid'); dateString.classList.remove('is-invalid'); } else { dateString.classList.add('is-invalid'); dateString.classList.remove('is-valid'); } }; // getting the rating value from user document.forms.todoform.stars.forEach((radio) => { radio.addEventListener('change', () => { rate = document.forms.todoform.stars.value; }); }); // function to validate task name, description and asignned-to input from user, // minimum 5 characters. const validFormFieldInput = (data) => { if (data.value.length < 5) { data.classList.add('is-invalid'); data.classList.remove('is-valid'); } else { data.classList.add('is-valid'); data.classList.remove('is-invalid'); } }; const clearForm = () => { formValidator.reset(); taskInput.classList.remove('is-valid'); taskDesc.classList.remove('is-valid'); taskAssign.classList.remove('is-valid'); taskDueDate.classList.remove('is-valid'); }; // Validating inputs & selection from user formValidator.addEventListener('submit', (event) => { event.preventDefault(); validFormFieldInput(taskInput); validFormFieldInput(taskDesc); validFormFieldInput(taskAssign); validateDate(taskDueDate); if (taskInput.classList.contains('is-valid') && taskDesc.classList.contains('is-valid') && taskAssign.classList.contains('is-valid') && taskDueDate.classList.contains('is-valid')) { taskApp.addTask(taskInput.value, taskDesc.value, taskAssign.value, taskDueDate.value, today, taskStatus.value, rate); console.log(taskApp); taskApp.save(); taskApp.render(); clearForm(); } }); const taskList = document.querySelector('#taskOutput'); taskList.addEventListener('click', (event) => { if (event.target.classList.contains('done-button')) { const parentTask = event.target.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement; const findId = Number(parentTask.attributes['data-task-id'].value); const task = taskApp.getTaskById(findId); task[0].status = 'Completed'; taskApp.save(); taskApp.render(); } if (event.target.classList.contains('delete-button')){ const parentTask = event.target.parentElement.parentElement.parentElement.parentElement.parentElement.parentElement; console.log(parentTask); const findId = Number(parentTask.attributes['data-task-id'].value); console.log(`Id to find: ${findId}`); taskApp.deleteTask(findId); taskApp.save(); taskApp.render(); } });
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _Equality2 = require("../Util/Equality"); var _Equality3 = _interopRequireDefault(_Equality2); var _Constants = require("../Constants"); var _ArgumentRegulariser = require("../Util/ArgumentRegulariser"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var User = function (_Equality) { _inherits(User, _Equality); function User(data, client) { _classCallCheck(this, User); var _this = _possibleConstructorReturn(this, (User.__proto__ || Object.getPrototypeOf(User)).call(this)); _this.client = client; _this.username = data.username; _this.discriminator = data.discriminator; _this.id = data.id; _this.avatar = data.avatar; _this.bot = !!data.bot; _this.status = data.status || "offline"; _this.game = data.game || null; _this.typing = { since: null, channel: null }; _this.note = data.note || null; _this.voiceChannel = null; _this.voiceState = {}; _this.speaking = false; return _this; } _createClass(User, [{ key: "mention", value: function mention() { return "<@" + this.id + ">"; } }, { key: "toString", value: function toString() { return this.mention(); } }, { key: "toObject", value: function toObject() { var keys = ['id', 'username', 'discriminator', 'avatar', 'bot', 'status', 'game', 'note', 'voiceState', 'speaking'], obj = {}; var _iteratorNormalCompletion = true; var _didIteratorError = false; var _iteratorError = undefined; try { for (var _iterator = keys[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) { var k = _step.value; obj[k] = this[k]; } } catch (err) { _didIteratorError = true; _iteratorError = err; } finally { try { if (!_iteratorNormalCompletion && _iterator.return) { _iterator.return(); } } finally { if (_didIteratorError) { throw _iteratorError; } } } obj.typing = { since: this.typing.since, channelID: this.typing.channel ? this.typing.channel.id : null }; obj.voiceChannelID = this.voiceChannel ? this.voiceChannel.id : null; return obj; } }, { key: "equalsStrict", value: function equalsStrict(obj) { if (obj instanceof User) return this.id === obj.id && this.username === obj.username && this.discriminator === obj.discriminator && this.avatar === obj.avatar && this.status === obj.status && (this.game === obj.game || this.game && obj.game && this.game.name === obj.game.name);else return false; } }, { key: "equals", value: function equals(obj) { if (obj instanceof User) return this.id === obj.id && this.username === obj.username && this.discriminator === obj.discriminator && this.avatar === obj.avatar;else return false; } }, { key: "sendMessage", value: function sendMessage() { return this.client.sendMessage.apply(this.client, (0, _ArgumentRegulariser.reg)(this, arguments)); } }, { key: "send", value: function send() { return this.client.sendMessage.apply(this.client, (0, _ArgumentRegulariser.reg)(this, arguments)); } }, { key: "sendTTSMessage", value: function sendTTSMessage() { return this.client.sendTTSMessage.apply(this.client, (0, _ArgumentRegulariser.reg)(this, arguments)); } }, { key: "sendTTS", value: function sendTTS() { return this.client.sendTTSMessage.apply(this.client, (0, _ArgumentRegulariser.reg)(this, arguments)); } }, { key: "sendFile", value: function sendFile() { return this.client.sendFile.apply(this.client, (0, _ArgumentRegulariser.reg)(this, arguments)); } }, { key: "startTyping", value: function startTyping() { return this.client.startTyping.apply(this.client, (0, _ArgumentRegulariser.reg)(this, arguments)); } }, { key: "stopTyping", value: function stopTyping() { return this.client.stopTyping.apply(this.client, (0, _ArgumentRegulariser.reg)(this, arguments)); } }, { key: "addTo", value: function addTo(role, callback) { return this.client.addMemberToRole.apply(this.client, [this, role, callback]); } }, { key: "removeFrom", value: function removeFrom(role, callback) { return this.client.removeMemberFromRole.apply(this.client, [this, role, callback]); } }, { key: "getLogs", value: function getLogs() { return this.client.getChannelLogs.apply(this.client, (0, _ArgumentRegulariser.reg)(this, arguments)); } }, { key: "getMessage", value: function getMessage() { return this.client.getMessage.apply(this.client, (0, _ArgumentRegulariser.reg)(this, arguments)); } }, { key: "hasRole", value: function hasRole(role) { return this.client.memberHasRole.apply(this.client, [this, role]); } }, { key: "createdAt", get: function get() { return new Date(+this.id / 4194304 + 1420070400000); } }, { key: "avatarURL", get: function get() { if (!this.avatar) { return null; } else { return _Constants.Endpoints.AVATAR(this.id, this.avatar); } } }, { key: "name", get: function get() { return this.username; } }]); return User; }(_Equality3.default); exports.default = User; //# sourceMappingURL=User.js.map
""" Test various functions regarding chapter 5: Fractional Differentiation. """ import unittest import os import math import numpy as np import pandas as pd from mlfinlab.features import fracdiff class TestFractionalDifferentiation(unittest.TestCase): """ Test get_weights, get_weights_ffd, frac_diff, and frac_diff_ffd """ def setUp(self): """ Set the file path for the sample dollar bars data. """ project_path = os.path.dirname(__file__) self.path = project_path + '/test_data/dollar_bar_sample.csv' self.data = pd.read_csv(self.path, index_col='date_time') self.data.index = pd.to_datetime(self.data.index) def test_get_weights(self): """ get_weights as implemented here matches the code in the book (Snippet 5.1). We test: 1. if the first element of the weights vector is 1.0 2. The length of the weights vector is same as the requested length """ diff_amt = 0.9 number_ele = 100 weights = fracdiff.get_weights(diff_amt, size=number_ele) # Last value in the set is still the same self.assertTrue(weights[-1] == 1.0) # Size matches self.assertTrue(weights.shape[0] == number_ele) # pylint: disable=unsubscriptable-object def test_get_weights_ffd(self): """ get_weights_ffd as implemented here matches the code in the book (Snippet 5.2). We test: 1. if the first element of the weights vector is 1.0 2. The length of the weights vector is equal to 12 """ diff_amt = 0.9 number_ele = 100 thresh = 1e-3 weights = fracdiff.get_weights_ffd(diff_amt, thresh=thresh, lim=number_ele) # Last value in the set is still the same self.assertTrue(weights[-1] == 1.0) # Size matches self.assertTrue(weights.shape[0] == 12) # pylint: disable=unsubscriptable-object def test_frac_diff(self): """ Assert that for any positive real number d, 1. Length of the output is the same as the length of the input 2. First element is NaN """ data_series = self.data['close'].to_frame() for diff_amt in np.arange(0.1, 1, 0.1): fd_series = fracdiff.frac_diff(data_series, diff_amt=diff_amt) self.assertTrue(fd_series.shape[0] == len(data_series)) self.assertTrue(isinstance(fd_series['close'][0], np.float64) and math.isnan(fd_series['close'][0])) def test_frac_diff_ffd(self): """ Assert that for any positive real number d, 1. Length of the output is the same as the length of the input 2. First element is NaN """ data_series = self.data['close'].to_frame() for diff_amt in np.arange(0.1, 1, 0.1): fd_series = fracdiff.frac_diff_ffd(data_series, diff_amt=diff_amt) self.assertTrue(fd_series.shape[0] == len(data_series)) self.assertTrue(isinstance(fd_series['close'][0], np.float64) and math.isnan(fd_series['close'][0]))
const BRIDGE_ERROR = { MISSING_WEB3: new Error('no web3 object found'), MISSING_WALLET: new Error('no wallet found'), MISSING_TXN: new Error('no transaction found'), MISSING_CONTRACTS: new Error('no contracts found'), MISSING_MNEMONIC: new Error('no authentication mnemonic found'), MISSING_URBIT_WALLET: new Error('no urbit wallet found'), MISSING_POINT: new Error('no point found'), INVALID_ROUTE: new Error('invalid route'), INVALID_NETWORK_TYPE: new Error('invalid network type'), INVALID_WALLET_TYPE: new Error('invalid wallet type'), } const renderTxnError = (web3, msg) => { const txnCost = (web3, msg) => { const costWei = msg.match(/upfront cost is: ([0-9]+)/) const costEth = web3.utils.fromWei(costWei[1], 'ether') return parseFloat(costEth).toFixed(4) } const acctBalance = (web3, msg) => { const balWei = msg.match(/sender's account only has: ([0-9]+)/) const balEth = web3.utils.fromWei(balWei[1], 'ether') return parseFloat(balEth).toFixed(4) } return ( msg.includes("doesn't have enough funds") ? "The account doesn't have enough Ether. " + `The up-front transaction cost is ${txnCost(web3, msg)} ETH, but the ` + `account only holds ${acctBalance(web3, msg)} ETH.` : "You may want to verify that the account that has signed the " + "transaction holds sufficient Ether to pay for the gas, and " + "also that you haven't set the gas limit for the transaction " + "too low." ) } export { BRIDGE_ERROR, renderTxnError }
/* * @Author: Caven * @Date: 2020-01-31 18:57:02 * @Last Modified by: Caven * @Last Modified time: 2020-06-25 08:52:43 */ import { Util } from '../../utils' import Transform from '../../transform/Transform' import Parse from '../../parse/Parse' import State from '../../state/State' import Overlay from '../Overlay' const { Cesium } = DC.Namespace class Circle extends Overlay { constructor(center, radius) { super() this._delegate = new Cesium.Entity({ ellipse: {} }) this._center = Parse.parsePosition(center) this._radius = +radius || 0 this._rotateAmount = 0 this._stRotation = 0 this.type = Overlay.getOverlayType('circle') this._state = State.INITIALIZED } set center(center) { this._center = Parse.parsePosition(center) this._delegate.position = Transform.transformWGS84ToCartesian(this._center) return this } get center() { return this._center } set radius(radius) { this._radius = +radius this._delegate.ellipse.semiMajorAxis = this._radius this._delegate.ellipse.semiMinorAxis = this._radius return this } get radius() { return this._redius } set rotateAmount(amount) { this._rotateAmount = +amount if (this._rotateAmount > 0) { this._delegate.ellipse.stRotation = new Cesium.CallbackProperty(time => { if (this._rotateAmount > 0) { this._stRotation += this._rotateAmount if (this._stRotation >= 360) { this._stRotation = 0 } } return this._stRotation }) } return this } get rotateAmount() { return this._rotateAmount } _mountedHook() { /** * set the location */ this.center = this._center /** * initialize the Overlay parameter */ this.radius = this._radius } /** * * @param {*} style */ setStyle(style) { if (!style || Object.keys(style).length === 0) { return this } delete style['semiMajorAxis'] && delete style['semiMinorAxis'] this._style = style Util.merge(this._delegate.ellipse, this._style) return this } } Overlay.registerType('circle') export default Circle
/* * Copyright (c) 2020 Sebastian Kylander https://gaztin.com/ * * This software is provided 'as-is', without any express or implied warranty. In no event will * the authors be held liable for any damages arising from the use of this software. * * Permission is granted to anyone to use this software for any purpose, including commercial * applications, and to alter it and redistribute it freely, subject to the following restrictions: * * 1. The origin of this software must not be misrepresented; you must not claim that you wrote the * original software. If you use this software in a product, an acknowledgment in the product * documentation would be appreciated but is not required. * 2. Altered source versions must be plainly marked as such, and must not be misrepresented as * being the original software. * 3. This notice may not be removed or altered from any source distribution. */ #pragma once #include "Orbit/Core/Event/EventSubscription.h" #include "Orbit/Core/Utility/Utility.h" #include <algorithm> #include <functional> #include <list> #include <mutex> #include <tuple> #include <vector> ORB_NAMESPACE_BEGIN template< typename... Types > class EventDispatcher { public: EventDispatcher( void ) = default; virtual ~EventDispatcher( void ) = default; ORB_DISABLE_COPY_AND_MOVE( EventDispatcher ); public: template< typename Functor > [[ nodiscard ]] EventSubscription Subscribe( Functor&& functor ) const { using Arg = std::remove_const_t< std::remove_reference_t< FirstArgument< Functor > > >; const uint64_t unique_id = GenerateUniqueID(); { const Queue< Arg >& queue = std::get< Queue< Arg > >( queues_ ); Subscriber< Arg > subscriber = { unique_id, std::forward< Functor >( functor ) }; std::scoped_lock lock = std::scoped_lock( queue.mutex ); queue.subscribers.push_back( subscriber ); } EventSubscription::Deleter deleter; deleter.user_data = this; deleter.functor = []( uint64_t id, const void* user_data ) { const EventDispatcher* self = reinterpret_cast< const EventDispatcher* >( user_data ); self->Unsubscribe< Arg >( id ); }; return EventSubscription( unique_id, deleter ); } template< typename T > void QueueEvent( const T& e ) { Queue< T >& queue = std::get< Queue< T > >( queues_ ); std::scoped_lock lock = std::scoped_lock( queue.mutex ); queue.events.push_back( e ); } protected: void SendEvents( void ) { ( SendEventsInQueue( std::get< Queue< Types > >( queues_ ) ), ... ); } private: template< typename T > struct Subscriber { uint64_t id; std::function< void( const T& ) > function; }; template< typename T > struct Queue { std::vector< T > events; mutable std::list< Subscriber< T > > subscribers; mutable std::mutex mutex; }; private: uint64_t GenerateUniqueID( void ) const { static std::atomic_uint64_t counter = 0; return ++counter; } template< typename T > void Unsubscribe( uint64_t id ) const { const Queue< T >& queue = std::get< Queue< T > >( queues_ ); std::scoped_lock lock = std::scoped_lock( queue.mutex ); for( auto it = queue.subscribers.begin(); it != queue.subscribers.end(); ++it ) { if( it->id == id ) { queue.subscribers.erase( it ); break; } } } template< typename T > void SendEventsInQueue( Queue< T >& queue ) const { std::scoped_lock lock( queue.mutex ); for( const T& e : queue.events ) { for( Subscriber< T >& sub : queue.subscribers ) sub.function( e ); } queue.events.clear(); } private: std::tuple< Queue< Types >... > queues_; }; ORB_NAMESPACE_END
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); /** * @ignore */ const debug = () => { }; /** * @ignore */ const LTK_INFO_SIZE = 36; /** * @ignore */ const MGMT_OP_LOAD_LONG_TERM_KEYS = 0x0013; /** * @ignore */ class Mgmt { constructor(hciProtocol) { this._ltkInfos = []; this._hci = hciProtocol; } nSocketData(data) { debug('on data ->' + data.toString('hex')); } nSocketError(error) { debug('on error ->' + error.message); } ddLongTermKey(address, addressType, authenticated, master, ediv, rand, key) { const ltkInfo = Buffer.alloc(LTK_INFO_SIZE); address.copy(ltkInfo, 0); ltkInfo.writeUInt8(addressType.readUInt8(0) + 1, 6); // BDADDR_LE_PUBLIC = 0x01, BDADDR_LE_RANDOM 0x02, so add one ltkInfo.writeUInt8(authenticated, 7); ltkInfo.writeUInt8(master, 8); ltkInfo.writeUInt8(key.length, 9); ediv.copy(ltkInfo, 10); rand.copy(ltkInfo, 12); key.copy(ltkInfo, 20); this._ltkInfos.push(ltkInfo); this.loadLongTermKeys(); } learLongTermKeys() { this._ltkInfos = []; this.loadLongTermKeys(); } oadLongTermKeys() { const numLongTermKeys = this._ltkInfos.length; const op = Buffer.alloc(2 + numLongTermKeys * LTK_INFO_SIZE); op.writeUInt16LE(numLongTermKeys, 0); for (let i = 0; i < numLongTermKeys; i++) { this._ltkInfos[i].copy(op, 2 + i * LTK_INFO_SIZE); } this.write(MGMT_OP_LOAD_LONG_TERM_KEYS, 0, op); } } exports.default = Mgmt;
import styled from "styled-components"; export const Section = styled.section` display: flex; justify-content: center; align-items: center; min-height:700px; height:100vh; width:100%; background-image:url('./images/Dragon.jpg'); background-position:top; background-size:cover; background-repeat:no-repeat; position: relative; &::after{ content:''; position:absolute; top:0; left:0; right:0; bottom: 0; background-color:rgba(0,0,0,.7); z-index:0; } `; export const Counter = styled.div` position: relative; display: flex; flex-direction: column; border-radius: 25px; background-color: ${({ theme }) => theme.Alpha}; z-index: 1; padding: 60px 24px; @media (min-width: 768px) { padding: 60px 80px; } & h1 { font-size: 48px; text-transform: uppercase; text-align: center; margin: 0; } `; export const Info = styled.div` justify-content: space-between; padding-top: 40px; text-align:center; & p{ margin:0; padding-bottom:10px; text-transform:capitalize; } & span{ text-transform:uppercase; color: #00ab66; } `; export const NumberContainer = styled.div` display: flex; justify-content:space-between; padding-top:40px; text-align:center; justify-content:center; & small{ font-size:40px; } `; export const Number = styled.div` position: relative; display: flex; flex-direction: column; align-items: center; justify-content: center; z-index: 1; & p { margin: 0; font-size: 25px; padding-left: 24px; padding-right: 24px; width:20px; text-align:center; @media (min-width: 768px) { padding-left: 40px; padding-right: 40px; font-size: 80px; width:92px } } & small { margin: 0; font-size: 18px; text-transform: uppercase; @media (min-width: 768px) { font-size: 24px; } } `;
/*========================================================================= * * Copyright Insight Software Consortium * * 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.txt * * 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. * *=========================================================================*/ #ifndef itkDynamicLoader_h #define itkDynamicLoader_h #include "itkObject.h" #include "itkObjectFactory.h" #include "itksys/DynamicLoader.hxx" namespace itk { /** \class DynamicLoader * \brief Portable loading of dynamic libraries or dll's. * * DynamicLoader provides a portable interface to loading dynamic * libraries or dll's into a process. * * \ingroup OSSystemObjects * \ingroup ITKCommon */ // BTX using LibHandle = itksys::DynamicLoader::LibraryHandle; // Cannot use this as this is a void (*)() but ITK old API used to be void* using SymbolPointer = itksys::DynamicLoader::SymbolPointer; // ETX class ITKCommon_EXPORT DynamicLoader : public Object { public: ITK_DISALLOW_COPY_AND_ASSIGN(DynamicLoader); /** Standard class type aliases. */ using Self = DynamicLoader; using Superclass = Object; using Pointer = SmartPointer<Self>; using ConstPointer = SmartPointer<const Self>; /** Method for creation through the object factory. */ itkNewMacro(Self); /** Run-time type information (and related methods). */ itkTypeMacro(DynamicLoader, Object); /** Load a dynamic library into the current process. * The returned LibHandle can be used to access the symbols in the * library. */ static LibHandle OpenLibrary(const char *); /** Attempt to detach a dynamic library from the * process. A value of true is returned if it is successful. */ static int CloseLibrary(LibHandle); /** Find the address of the symbol in the given library. */ static void * GetSymbolAddress(LibHandle, const char *); /** Return the library prefix for the given architecture */ static const char * LibPrefix(); /** Return the library extension for the given architecture. */ static const char * LibExtension(); /** Return the last error produced from a calls made on this class. */ static const char * LastError(); protected: DynamicLoader(); ~DynamicLoader() override; }; } // end namespace itk #endif
/* Altera DE2I-150 FPGA Driver for Linux made by Matheus Souza (github.com/mfbsouza) for the MusicBox Project, A Music Instrument Simulator using Arduino Uno and FPGA */ #include <linux/kernel.h> #include <linux/module.h> #include <linux/pci.h> #include <linux/init.h> #include <linux/fs.h> #include <asm/uaccess.h> MODULE_LICENSE("Dual MIT/GPL"); MODULE_DESCRIPTION("FPGA Driver for MusicBox Project"); MODULE_AUTHOR("Matheus Souza"); #define DISPLAY_L 1 #define DISPLAY_R 2 #define SWITCHES 3 #define PUSHBUTTON 4 #define GREENLEDS 5 #define REDLEDS 6 /* General Purpose Variables for Driver */ static uint32_t last_pbuttons = 0; static uint32_t last_switches = 0; static uint32_t data; static int flag = 0; static int access_count = 0; // pointers to FPGA IO hardware static void *display_r, *switches_, *p_buttons; static void *display_l, *green_leds, *red_leds; /* --- CHAR DEVICE INFORMATION & FUNCTIONS --- */ static int MAJOR_NUMBER = 91; static int dev_open (struct inode *, struct file *); static int dev_release (struct inode *, struct file *); static ssize_t dev_read (struct file * , char * , size_t, loff_t *); static ssize_t dev_write (struct file * , const char *, size_t, loff_t *); static struct file_operations file_opts = { .read = dev_read, .open = dev_open, .write = dev_write, .release = dev_release }; /* Char Driver Functions implementations */ static int dev_open(struct inode *inodep, struct file *filep) { access_count++; printk(KERN_ALERT "FPGA device opened %d time(s)\n", access_count); return 0; } static int dev_release(struct inode *inodep, struct file *filep) { printk(KERN_ALERT "FPGA device closed.\n"); return 0; } static ssize_t dev_read(struct file *filep, char *buf, size_t opt, loff_t *off) { data = 0; switch(opt) { case DISPLAY_L: data = ioread32(display_l); break; case DISPLAY_R: data = ioread32(display_r); break; case SWITCHES: data = ioread32(switches_); if(data != last_switches) { flag = 1; } last_switches = data; break; case PUSHBUTTON: data = ioread32(p_buttons); if(data != last_pbuttons && data != 15) { flag = 1; } last_pbuttons = data; break; case GREENLEDS: data = ioread32(green_leds); break; case REDLEDS: data = ioread32(red_leds); break; default: printk(KERN_ALERT "Invalid Option from Read().\n"); return -1; // send error to user space } if(flag == 1) { // send data to user space copy_to_user(buf, &data, sizeof(uint32_t)); printk(KERN_ALERT "SEND: %d", data); flag = 0; // reset flag return 4; // red 4 bytes } else { return 0; // red 0 bytes } } static ssize_t dev_write(struct file *filep, const char *buf, size_t opt, loff_t *off) { data = 0; // get data from the user space to kernel space copy_from_user(&data, buf, sizeof(uint32_t)); switch(opt) { case DISPLAY_L: iowrite32(data, display_l); break; case DISPLAY_R: iowrite32(data, display_r); break; case GREENLEDS: iowrite32(data, green_leds); break; case REDLEDS: iowrite32(data, red_leds); break; default: printk(KERN_ALERT "Invalid Option from Write().\n"); return -1; } printk(KERN_ALERT "WROTE: %d", data); return 4; } /* --- PCI INTERFACE INFORMATION & FUNCTIONS --- */ static int pci_probe (struct pci_dev *dev, const struct pci_device_id *id); static void pci_remove (struct pci_dev *dev); static struct pci_device_id pci_ids[] = { { PCI_DEVICE(0x1172, 0x0004), }, { 0, } }; MODULE_DEVICE_TABLE(pci, pci_ids); static struct pci_driver pci_driver = { .name = "alterahello", .id_table = pci_ids, .probe = pci_probe, .remove = pci_remove, }; static unsigned char pci_get_revision(struct pci_dev *dev) { u8 revision; pci_read_config_byte(dev, PCI_REVISION_ID, &revision); return revision; } static int pci_probe(struct pci_dev *dev, const struct pci_device_id *id) { int vendor, retval; unsigned long resource; retval = pci_enable_device(dev); if (pci_get_revision(dev) != 0x01) { printk(KERN_ALERT "ERROR: cannot find PCI device\n"); return -ENODEV; } pci_read_config_dword(dev, 0, &vendor); printk(KERN_ALERT "PCI Device Found. Vendor: %x\n", vendor); resource = pci_resource_start(dev, 0); printk(KERN_ALERT "PCI device resources start at bar 0: %lx\n", resource); display_r = ioremap_nocache(resource + 0XC000, 0x20); display_l = ioremap_nocache(resource + 0XC140, 0x20); switches_ = ioremap_nocache(resource + 0XC040, 0x20); p_buttons = ioremap_nocache(resource + 0XC080, 0x20); green_leds = ioremap_nocache(resource + 0XC0F0, 0x20); red_leds = ioremap_nocache(resource + 0XC0B0, 0x20); return 0; } static void pci_remove(struct pci_dev *dev) { iounmap(display_r); iounmap(display_l); iounmap(switches_); iounmap(p_buttons); iounmap(green_leds); iounmap(red_leds); } /* --- Driver Registration --- */ static int __init altera_driver_init(void) { int t = register_chrdev(MAJOR_NUMBER, "de2i150_altera", &file_opts); t = t | pci_register_driver(&pci_driver); if(t<0) printk(KERN_ALERT "ERROR: cannot register char or pci.\n"); else printk(KERN_ALERT "PCI Device registred.\n"); return t; } static void __exit altera_driver_exit(void) { printk(KERN_ALERT "Closing Driver...\n"); unregister_chrdev(MAJOR_NUMBER, "de2i150_altera"); pci_unregister_driver(&pci_driver); } module_init(altera_driver_init); module_exit(altera_driver_exit);
const handleFetchErrors = (res) => { if (!res.ok) { const error = new Error(res.statusText); error.code = res.status; throw error; } return res; }; export default handleFetchErrors;
import pygame import sys from battleship.tim.TimController import TimController as Controller class MenuController(Controller): def input(self, events): super().input(events) scene = self.engine.world for e in events: if e.type == pygame.KEYDOWN: if e.key == pygame.K_UP: scene.select(-1) elif e.key == pygame.K_DOWN: scene.select(1) elif e.key == pygame.K_RETURN: if scene.menu_choice == 0: self.engine.switch_scene('battleship') self.engine.world.start() elif scene.menu_choice == 3: sys.exit(0) elif e.type == pygame.KEYUP: if e.key == pygame.K_RETURN: scene.menu_pick = False
import os os.environ["CUDA_VISIBLE_DEVICES"]="0" #for training on gpu import tensorflow as tf import numpy as np import pickle import time from random import shuffle from tensorflow import keras from tensorflow.python.keras.utils import to_categorical from tensorflow.python.keras.models import Sequential, load_model from tensorflow.python.keras.layers import Dense, Conv1D, MaxPooling1D, Dropout, GlobalAveragePooling1D, Reshape #%% from dataset import create_dataset from subplots import plot_signal, plot_signals, plot_examples files_path = "data_emg/" #path to your directory with 10 data.txt files train_signals, train_labels, val_signals, val_labels, test_signals, test_labels = create_dataset(files_path) #path to data files path = r'./data_new/' #path where you want to save trained model and some other files sec_path = r'./pretrained_model/' num_classes = 9 num_sensors = 1 input_size = train_signals.shape[1] model = Sequential() model.add(Reshape((input_size, num_sensors), input_shape=(input_size, ))) model.add(Conv1D(50, 10, activation='relu', input_shape=(input_size, num_sensors))) model.add(Conv1D(25, 10, activation='relu')) model.add(MaxPooling1D(4)) model.add(Conv1D(100, 10, activation='relu')) model.add(Conv1D(50, 10, activation='relu')) model.add(MaxPooling1D(4)) model.add(Dropout(0.5)) #next layers will be retrained model.add(Conv1D(100, 10, activation='relu')) model.add(GlobalAveragePooling1D()) model.add(Dense(num_classes, activation='softmax')) print(model.summary()) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['accuracy']) start_time = time.time() history = model.fit(train_signals, train_labels, steps_per_epoch=25, epochs=25, batch_size=None, validation_data=(val_signals, val_labels), validation_steps=25 ) elapsed_time = time.time() - start_time # training time loss, accuracy = model.evaluate(test_signals, test_labels) # evaluating model on test data loss = float("{0:.3f}".format(loss)) accuracy = float("{0:.3f}".format(accuracy)) elapsed_time = float("{0:.3f}".format(elapsed_time)) #saving some data f = open(sec_path + "info.txt", 'w') f.writelines(["loss: ", str(loss), '\n', "accuracy: ", str(accuracy), '\n', "elapsed_time: ", str(elapsed_time), '\n']) #saving model model.save(sec_path + "pretrained_model.h5") #saving test data just in case cc = list(zip(test_signals, test_labels)) with open(sec_path + "pretrained_model_test_data.txt", "wb") as fp: pickle.dump(cc, fp) #saving history with open(sec_path + "pretrained_model_history.h5", "wb") as fp: pickle.dump(history.history, fp) #%% encoder = load_model(r'./weights/conv_encoder.h5') encoded_data = encoder.predict(test_signals) plot_examples(test_signals, encoded_data)
import re from Products.ZenRRD.CommandParser \ import CommandParser from Products.ZenUtils.Utils \ import prepId class get(CommandParser): def processResults(self, cmd, result): """" Example output pool0 size 399431958528 - """ get_regex = r'^(?P<pool>\S+)\t(?P<key>\S+)\t(?P<value>\S+)\t\S+$' pools = dict() for line in cmd.result.output.splitlines(): get_match = re.match(get_regex, line) if get_match: pool = get_match.group('pool') key = get_match.group('key') value = get_match.group('value') if pool not in pools: pools[pool] = dict() if value.endswith('%') or re.match(r'^\d+\.\d{2}x$', value): value = value[:-1] elif value == '-': value = None pools[pool][key] = value datapoints = [ 'allocated', 'capacity', 'free', ] floats = [ 'dedupratio', 'fragmentation', ] datapoints += floats components = dict() for pool in pools: comp_id = prepId('pool_{0}'.format(pool)) if comp_id not in components: components[comp_id] = dict() for measure in datapoints: if measure in pools[pool]: if measure in floats: value = float(pools[pool].get(measure)) else: value = int(pools[pool].get(measure)) components[comp_id][measure] = value for point in cmd.points: if point.component in components: values = components[point.component] if point.id in values: result.values.append((point, values[point.id]))
from __future__ import print_function from __future__ import absolute_import from __future__ import division import rhinoscriptsyntax as rs __all__ = [ 'uv_points_from_surface', ] def uv_points_from_surface(srf, u_div, v_div): """Creates a nested uv point list from a surface. Parameters ---------- srf : Rhino surface The object identifier u_div : int Number of poinst in u direction v_div : int Number of poinst in v direction Returns ------- 2D array (nested list) Points for every uv division. """ u_domain = rs.SurfaceDomain(srf, 0) v_domain = rs.SurfaceDomain(srf, 1) u_step = (u_domain[1] - u_domain[0]) / (u_div - 1) v_step = (v_domain[1] - v_domain[0]) / (v_div - 1) uv_points = [[None for _ in range(v_div)] for _ in range(u_div)] for u in range(u_div): for v in range(v_div): uv = (u_domain[0] + u_step * u, v_domain[0] + v_step * v) uv_points[u][v] = rs.EvaluateSurface(srf, uv[0], uv[1]) return uv_points # ============================================================================== # Main # ============================================================================== if __name__ == "__main__": pass
// Copyright 2018 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #ifndef V8_WASM_WASM_LINKAGE_H_ #define V8_WASM_WASM_LINKAGE_H_ #include "src/assembler-arch.h" #include "src/machine-type.h" #include "src/signature.h" #include "src/wasm/value-type.h" namespace v8 { namespace internal { namespace wasm { #if V8_TARGET_ARCH_IA32 // =========================================================================== // == ia32 =================================================================== // =========================================================================== constexpr Register kGpParamRegisters[] = {esi, eax, edx, ecx, ebx}; constexpr Register kGpReturnRegisters[] = {eax, edx}; constexpr DoubleRegister kFpParamRegisters[] = {xmm1, xmm2, xmm3, xmm4, xmm5, xmm6}; constexpr DoubleRegister kFpReturnRegisters[] = {xmm1, xmm2}; #elif V8_TARGET_ARCH_X64 // =========================================================================== // == x64 ==================================================================== // =========================================================================== constexpr Register kGpParamRegisters[] = {rsi, rax, rdx, rcx, rbx, rdi}; constexpr Register kGpReturnRegisters[] = {rax, rdx}; constexpr DoubleRegister kFpParamRegisters[] = {xmm1, xmm2, xmm3, xmm4, xmm5, xmm6}; constexpr DoubleRegister kFpReturnRegisters[] = {xmm1, xmm2}; #elif V8_TARGET_ARCH_ARM // =========================================================================== // == arm ==================================================================== // =========================================================================== constexpr Register kGpParamRegisters[] = {r3, r0, r1, r2}; constexpr Register kGpReturnRegisters[] = {r0, r1}; constexpr DoubleRegister kFpParamRegisters[] = {d0, d1, d2, d3, d4, d5, d6, d7}; constexpr DoubleRegister kFpReturnRegisters[] = {d0, d1}; #elif V8_TARGET_ARCH_ARM64 // =========================================================================== // == arm64 ==================================================================== // =========================================================================== constexpr Register kGpParamRegisters[] = {x7, x0, x1, x2, x3, x4, x5, x6}; constexpr Register kGpReturnRegisters[] = {x0, x1}; constexpr DoubleRegister kFpParamRegisters[] = {d0, d1, d2, d3, d4, d5, d6, d7}; constexpr DoubleRegister kFpReturnRegisters[] = {d0, d1}; #elif V8_TARGET_ARCH_MIPS // =========================================================================== // == mips =================================================================== // =========================================================================== constexpr Register kGpParamRegisters[] = {a0, a1, a2, a3}; constexpr Register kGpReturnRegisters[] = {v0, v1}; constexpr DoubleRegister kFpParamRegisters[] = {f2, f4, f6, f8, f10, f12, f14}; constexpr DoubleRegister kFpReturnRegisters[] = {f2, f4}; #elif V8_TARGET_ARCH_MIPS64 // =========================================================================== // == mips64 ================================================================= // =========================================================================== constexpr Register kGpParamRegisters[] = {a0, a1, a2, a3, a4, a5, a6, a7}; constexpr Register kGpReturnRegisters[] = {v0, v1}; constexpr DoubleRegister kFpParamRegisters[] = {f2, f4, f6, f8, f10, f12, f14}; constexpr DoubleRegister kFpReturnRegisters[] = {f2, f4}; #elif V8_TARGET_ARCH_PPC || V8_TARGET_ARCH_PPC64 // =========================================================================== // == ppc & ppc64 ============================================================ // =========================================================================== constexpr Register kGpParamRegisters[] = {r10, r3, r4, r5, r6, r7, r8, r9}; constexpr Register kGpReturnRegisters[] = {r3, r4}; constexpr DoubleRegister kFpParamRegisters[] = {d1, d2, d3, d4, d5, d6, d7, d8}; constexpr DoubleRegister kFpReturnRegisters[] = {d1, d2}; #elif V8_TARGET_ARCH_S390X // =========================================================================== // == s390x ================================================================== // =========================================================================== constexpr Register kGpParamRegisters[] = {r6, r2, r3, r4, r5}; constexpr Register kGpReturnRegisters[] = {r2, r3}; constexpr DoubleRegister kFpParamRegisters[] = {d0, d2, d4, d6}; constexpr DoubleRegister kFpReturnRegisters[] = {d0, d2, d4, d6}; #elif V8_TARGET_ARCH_S390 // =========================================================================== // == s390 =================================================================== // =========================================================================== constexpr Register kGpParamRegisters[] = {r6, r2, r3, r4, r5}; constexpr Register kGpReturnRegisters[] = {r2, r3}; constexpr DoubleRegister kFpParamRegisters[] = {d0, d2}; constexpr DoubleRegister kFpReturnRegisters[] = {d0, d2}; #else // =========================================================================== // == unknown ================================================================ // =========================================================================== // Do not use any registers, we will just always use the stack. constexpr Register kGpParamRegisters[] = {}; constexpr Register kGpReturnRegisters[] = {}; constexpr DoubleRegister kFpParamRegisters[] = {}; constexpr DoubleRegister kFpReturnRegisters[] = {}; #endif // The parameter index where the instance parameter should be placed in wasm // call descriptors. This is used by the Int64Lowering::LowerNode method. constexpr int kWasmInstanceParameterIndex = 0; class LinkageAllocator { public: template <size_t kNumGpRegs, size_t kNumFpRegs> constexpr LinkageAllocator(const Register (&gp)[kNumGpRegs], const DoubleRegister (&fp)[kNumFpRegs]) : LinkageAllocator(gp, kNumGpRegs, fp, kNumFpRegs) {} constexpr LinkageAllocator(const Register* gp, int gpc, const DoubleRegister* fp, int fpc) : gp_count_(gpc), gp_regs_(gp), fp_count_(fpc), fp_regs_(fp) {} bool has_more_gp_regs() const { return gp_offset_ < gp_count_; } bool has_more_fp_regs() const { return fp_offset_ < fp_count_; } Register NextGpReg() { DCHECK_LT(gp_offset_, gp_count_); return gp_regs_[gp_offset_++]; } DoubleRegister NextFpReg() { DCHECK_LT(fp_offset_, fp_count_); return fp_regs_[fp_offset_++]; } // Stackslots are counted upwards starting from 0 (or the offset set by // {SetStackOffset}. int NumStackSlots(MachineRepresentation type) { return std::max(1, ElementSizeInBytes(type) / kPointerSize); } // Stackslots are counted upwards starting from 0 (or the offset set by // {SetStackOffset}. If {type} needs more than // one stack slot, the lowest used stack slot is returned. int NextStackSlot(MachineRepresentation type) { int num_stack_slots = NumStackSlots(type); int offset = stack_offset_; stack_offset_ += num_stack_slots; return offset; } // Set an offset for the stack slots returned by {NextStackSlot} and // {NumStackSlots}. Can only be called before any call to {NextStackSlot}. void SetStackOffset(int num) { DCHECK_LE(0, num); DCHECK_EQ(0, stack_offset_); stack_offset_ = num; } int NumStackSlots() const { return stack_offset_; } private: const int gp_count_; int gp_offset_ = 0; const Register* const gp_regs_; const int fp_count_; int fp_offset_ = 0; const DoubleRegister* const fp_regs_; int stack_offset_ = 0; }; } // namespace wasm } // namespace internal } // namespace v8 #endif // V8_WASM_WASM_LINKAGE_H_
H5P.Question = (function ($, EventDispatcher, JoubelUI) { /** * Extending this class make it alot easier to create tasks for other * content types. * * @class H5P.Question * @extends H5P.EventDispatcher * @param {string} type */ function Question(type) { var self = this; // Inheritance EventDispatcher.call(self); // Register default section order self.order = ['video', 'image', 'introduction', 'content', 'explanation', 'feedback', 'scorebar', 'buttons', 'read']; // Keep track of registered sections var sections = {}; // Buttons var buttons = {}; var buttonOrder = []; // Wrapper when attached var $wrapper; // Click element var clickElement; // ScoreBar var scoreBar; // Keep track of the feedback's visual status. var showFeedback; // Keep track of which buttons are scheduled for hiding. var buttonsToHide = []; // Keep track of which buttons are scheduled for showing. var buttonsToShow = []; // Keep track of the hiding and showing of buttons. var toggleButtonsTimer; var toggleButtonsTransitionTimer; var buttonTruncationTimer; // Keeps track of initialization of question var initialized = false; /** * @type {Object} behaviour Behaviour of Question * @property {Boolean} behaviour.disableFeedback Set to true to disable feedback section */ var behaviour = { disableFeedback: false, disableReadSpeaker: false }; // Keeps track of thumb state var imageThumb = true; // Keeps track of image transitions var imageTransitionTimer; // Keep track of whether sections is transitioning. var sectionsIsTransitioning = false; // Keep track of auto play state var disableAutoPlay = false; // Feedback transition timer var feedbackTransitionTimer; // Used when reading messages to the user var $read, readText; /** * Register section with given content. * * @private * @param {string} section ID of the section * @param {(string|H5P.jQuery)} [content] */ var register = function (section, content) { sections[section] = {}; var $e = sections[section].$element = $('<div/>', { 'class': 'h5p-question-' + section, }); if (content) { $e[content instanceof $ ? 'append' : 'html'](content); } }; /** * Update registered section with content. * * @private * @param {string} section ID of the section * @param {(string|H5P.jQuery)} content */ var update = function (section, content) { if (content instanceof $) { sections[section].$element.html('').append(content); } else { sections[section].$element.html(content); } }; /** * Insert element with given ID into the DOM. * * @private * @param {array|Array|string[]} order * List with ordered element IDs * @param {string} id * ID of the element to be inserted * @param {Object} elements * Maps ID to the elements * @param {H5P.jQuery} $container * Parent container of the elements */ var insert = function (order, id, elements, $container) { // Try to find an element id should be after for (var i = 0; i < order.length; i++) { if (order[i] === id) { // Found our pos while (i > 0 && (elements[order[i - 1]] === undefined || !elements[order[i - 1]].isVisible)) { i--; } if (i === 0) { // We are on top. elements[id].$element.prependTo($container); } else { // Add after element elements[id].$element.insertAfter(elements[order[i - 1]].$element); } elements[id].isVisible = true; break; } } }; /** * Make feedback into a popup and position relative to click. * * @private * @param {string} [closeText] Text for the close button */ var makeFeedbackPopup = function (closeText) { var $element = sections.feedback.$element; var $parent = sections.content.$element; var $click = (clickElement != null ? clickElement.$element : null); $element.appendTo($parent).addClass('h5p-question-popup'); if (sections.scorebar) { sections.scorebar.$element.appendTo($element); } $parent.addClass('h5p-has-question-popup'); // Draw the tail var $tail = $('<div/>', { 'class': 'h5p-question-feedback-tail' }).hide() .appendTo($parent); // Draw the close button var $close = $('<div/>', { 'class': 'h5p-question-feedback-close', 'tabindex': 0, 'title': closeText, on: { click: function (event) { $element.remove(); $tail.remove(); event.preventDefault(); }, keydown: function (event) { switch (event.which) { case 13: // Enter case 32: // Space $element.remove(); $tail.remove(); event.preventDefault(); } } } }).hide().appendTo($element); if ($click != null) { if ($click.hasClass('correct')) { $element.addClass('h5p-question-feedback-correct'); $close.show(); sections.buttons.$element.hide(); } else { sections.buttons.$element.appendTo(sections.feedback.$element); } } positionFeedbackPopup($element, $click); }; /** * Position the feedback popup. * * @private * @param {H5P.jQuery} $element Feedback div * @param {H5P.jQuery} $click Visual click div */ var positionFeedbackPopup = function ($element, $click) { var $container = $element.parent(); var $tail = $element.siblings('.h5p-question-feedback-tail'); var popupWidth = $element.outerWidth(); var popupHeight = setElementHeight($element); var space = 15; var disableTail = false; var positionY = $container.height() / 2 - popupHeight / 2; var positionX = $container.width() / 2 - popupWidth / 2; var tailX = 0; var tailY = 0; var tailRotation = 0; if ($click != null) { // Edge detection for click, takes space into account var clickNearTop = ($click[0].offsetTop < space); var clickNearBottom = ($click[0].offsetTop + $click.height() > $container.height() - space); var clickNearLeft = ($click[0].offsetLeft < space); var clickNearRight = ($click[0].offsetLeft + $click.width() > $container.width() - space); // Click is not in a corner or close to edge, calculate position normally positionX = $click[0].offsetLeft - popupWidth / 2 + $click.width() / 2; positionY = $click[0].offsetTop - popupHeight - space; tailX = positionX + popupWidth / 2 - $tail.width() / 2; tailY = positionY + popupHeight - ($tail.height() / 2); tailRotation = 225; // If popup is outside top edge, position under click instead if (popupHeight + space > $click[0].offsetTop) { positionY = $click[0].offsetTop + $click.height() + space; tailY = positionY - $tail.height() / 2 ; tailRotation = 45; } // If popup is outside left edge, position left if (positionX < 0) { positionX = 0; } // If popup is outside right edge, position right if (positionX + popupWidth > $container.width()) { positionX = $container.width() - popupWidth; } // Special cases such as corner clicks, or close to an edge, they override X and Y positions if met if (clickNearTop && (clickNearLeft || clickNearRight)) { positionX = $click[0].offsetLeft + (clickNearLeft ? $click.width() : -popupWidth); positionY = $click[0].offsetTop + $click.height(); disableTail = true; } else if (clickNearBottom && (clickNearLeft || clickNearRight)) { positionX = $click[0].offsetLeft + (clickNearLeft ? $click.width() : -popupWidth); positionY = $click[0].offsetTop - popupHeight; disableTail = true; } else if (!clickNearTop && !clickNearBottom) { if (clickNearLeft || clickNearRight) { positionY = $click[0].offsetTop - popupHeight / 2 + $click.width() / 2; positionX = $click[0].offsetLeft + (clickNearLeft ? $click.width() + space : -popupWidth + -space); // Make sure this does not position the popup off screen if (positionX < 0) { positionX = 0; disableTail = true; } else { tailX = positionX + (clickNearLeft ? - $tail.width() / 2 : popupWidth - $tail.width() / 2); tailY = positionY + popupHeight / 2 - $tail.height() / 2; tailRotation = (clickNearLeft ? 315 : 135); } } } // Contain popup from overflowing bottom edge if (positionY + popupHeight > $container.height()) { positionY = $container.height() - popupHeight; if (popupHeight > $container.height() - ($click[0].offsetTop + $click.height() + space)) { disableTail = true; } } } else { disableTail = true; } // Contain popup from ovreflowing top edge if (positionY < 0) { positionY = 0; } $element.css({top: positionY, left: positionX}); $tail.css({top: tailY, left: tailX}); if (!disableTail) { $tail.css({ 'left': tailX, 'top': tailY, 'transform': 'rotate(' + tailRotation + 'deg)' }).show(); } else { $tail.hide(); } }; /** * Set element max height, used for animations. * * @param {H5P.jQuery} $element */ var setElementHeight = function ($element) { if (!$element.is(':visible')) { // No animation $element.css('max-height', 'none'); return; } // If this element is shown in the popup, we can't set width to 100%, // since it already has a width set in CSS var isFeedbackPopup = $element.hasClass('h5p-question-popup'); // Get natural element height var $tmp = $element.clone() .css({ 'position': 'absolute', 'max-height': 'none', 'width': isFeedbackPopup ? '' : '100%' }) .appendTo($element.parent()); // Need to take margins into account when calculating available space var sideMargins = parseFloat($element.css('margin-left')) + parseFloat($element.css('margin-right')); var tmpElWidth = $tmp.css('width') ? $tmp.css('width') : '100%'; $tmp.css('width', 'calc(' + tmpElWidth + ' - ' + sideMargins + 'px)'); // Apply height to element var h = Math.round($tmp.get(0).getBoundingClientRect().height); var fontSize = parseFloat($element.css('fontSize')); var relativeH = h / fontSize; $element.css('max-height', relativeH + 'em'); $tmp.remove(); if (h > 0 && sections.buttons && sections.buttons.$element === $element) { // Make sure buttons section is visible showSection(sections.buttons); // Resize buttons after resizing button section setTimeout(resizeButtons, 150); } return h; }; /** * Does the actual job of hiding the buttons scheduled for hiding. * * @private * @param {boolean} [relocateFocus] Find a new button to focus */ var hideButtons = function (relocateFocus) { for (var i = 0; i < buttonsToHide.length; i++) { hideButton(buttonsToHide[i].id); } buttonsToHide = []; if (relocateFocus) { self.focusButton(); } }; /** * Does the actual hiding. * @private * @param {string} buttonId */ var hideButton = function (buttonId) { // Using detach() vs hide() makes it harder to cheat. buttons[buttonId].$element.detach(); buttons[buttonId].isVisible = false; }; /** * Shows the buttons on the next tick. This is to avoid buttons flickering * If they're both added and removed on the same tick. * * @private */ var toggleButtons = function () { // If no buttons section, return if (sections.buttons === undefined) { return; } // Clear transition timer, reevaluate if buttons will be detached clearTimeout(toggleButtonsTransitionTimer); // Show buttons for (var i = 0; i < buttonsToShow.length; i++) { insert(buttonOrder, buttonsToShow[i].id, buttons, sections.buttons.$element); buttons[buttonsToShow[i].id].isVisible = true; } buttonsToShow = []; // Hide buttons var numToHide = 0; var relocateFocus = false; for (var j = 0; j < buttonsToHide.length; j++) { var button = buttons[buttonsToHide[j].id]; if (button.isVisible) { numToHide += 1; } if (button.$element.is(':focus')) { // Move focus to the first visible button. relocateFocus = true; } } var animationTimer = 150; if (sections.feedback && sections.feedback.$element.hasClass('h5p-question-popup')) { animationTimer = 0; } if (numToHide === sections.buttons.$element.children().length) { // All buttons are going to be hidden. Hide container using transition. hideSection(sections.buttons); // Detach buttons hideButtons(relocateFocus); } else { hideButtons(relocateFocus); // Show button section if (!sections.buttons.$element.is(':empty')) { showSection(sections.buttons); setElementHeight(sections.buttons.$element); // Trigger resize after animation toggleButtonsTransitionTimer = setTimeout(function () { self.trigger('resize'); }, animationTimer); } // Resize buttons to fit container resizeButtons(); } toggleButtonsTimer = undefined; }; /** * Allows for scaling of the question image. */ var scaleImage = function () { var $imgSection = sections.image.$element; clearTimeout(imageTransitionTimer); // Add this here to avoid initial transition of the image making // content overflow. Alternatively we need to trigger a resize. $imgSection.addClass('animatable'); if (imageThumb) { // Expand image $(this).attr('aria-expanded', true); $imgSection.addClass('h5p-question-image-fill-width'); imageThumb = false; imageTransitionTimer = setTimeout(function () { self.trigger('resize'); }, 600); } else { // Scale down image $(this).attr('aria-expanded', false); $imgSection.removeClass('h5p-question-image-fill-width'); imageThumb = true; imageTransitionTimer = setTimeout(function () { self.trigger('resize'); }, 600); } }; /** * Get scrollable ancestor of element * * @private * @param {H5P.jQuery} $element * @param {Number} [currDepth=0] Current recursive calls to ancestor, stop at maxDepth * @param {Number} [maxDepth=5] Maximum depth for finding ancestor. * @returns {H5P.jQuery} Parent element that is scrollable */ var findScrollableAncestor = function ($element, currDepth, maxDepth) { if (!currDepth) { currDepth = 0; } if (!maxDepth) { maxDepth = 5; } // Check validation of element or if we have reached document root if (!$element || !($element instanceof $) || document === $element.get(0) || currDepth >= maxDepth) { return; } if ($element.css('overflow-y') === 'auto') { return $element; } else { return findScrollableAncestor($element.parent(), currDepth + 1, maxDepth); } }; /** * Scroll to bottom of Question. * * @private */ var scrollToBottom = function () { if (!$wrapper || ($wrapper.hasClass('h5p-standalone') && !H5P.isFullscreen)) { return; // No scroll } var scrollableAncestor = findScrollableAncestor($wrapper); // Scroll to bottom of scrollable ancestor if (scrollableAncestor) { scrollableAncestor.animate({ scrollTop: $wrapper.css('height') }, "slow"); } }; /** * Resize buttons to fit container width * * @private */ var resizeButtons = function () { if (!buttons || !sections.buttons) { return; } var go = function () { // Don't do anything if button elements are not visible yet if (!sections.buttons.$element.is(':visible')) { return; } // Width of all buttons var buttonsWidth = { max: 0, min: 0, current: 0 }; for (var i in buttons) { var button = buttons[i]; if (button.isVisible) { setButtonWidth(buttons[i]); buttonsWidth.max += button.width.max; buttonsWidth.min += button.width.min; buttonsWidth.current += button.isTruncated ? button.width.min : button.width.max; } } var makeButtonsFit = function (availableWidth) { if (buttonsWidth.max < availableWidth) { // It is room for everyone on the right side of the score bar (without truncating) if (buttonsWidth.max !== buttonsWidth.current) { // Need to make everyone big restoreButtonLabels(buttonsWidth.current, availableWidth); } return true; } else if (buttonsWidth.min < availableWidth) { // Is it room for everyone on the right side of the score bar with truncating? if (buttonsWidth.current > availableWidth) { removeButtonLabels(buttonsWidth.current, availableWidth); } else { restoreButtonLabels(buttonsWidth.current, availableWidth); } return true; } return false; }; toggleFullWidthScorebar(false); var buttonSectionWidth = Math.floor(sections.buttons.$element.width()) - 1; if (!makeButtonsFit(buttonSectionWidth)) { // If we get here we need to wrap: toggleFullWidthScorebar(true); buttonSectionWidth = Math.floor(sections.buttons.$element.width()) - 1; makeButtonsFit(buttonSectionWidth); } }; // If visible, resize right away if (sections.buttons.$element.is(':visible')) { go(); } else { // If not visible, try on the next tick // Clear button truncation timer if within a button truncation function if (buttonTruncationTimer) { clearTimeout(buttonTruncationTimer); } buttonTruncationTimer = setTimeout(function () { buttonTruncationTimer = undefined; go(); }, 0); } }; var toggleFullWidthScorebar = function (enabled) { if (sections.scorebar && sections.scorebar.$element && sections.scorebar.$element.hasClass('h5p-question-visible')) { sections.buttons.$element.addClass('has-scorebar'); sections.buttons.$element.toggleClass('wrap', enabled); sections.scorebar.$element.toggleClass('full-width', enabled); } else { sections.buttons.$element.removeClass('has-scorebar'); } }; /** * Remove button labels until they use less than max width. * * @private * @param {Number} buttonsWidth Total width of all buttons * @param {Number} maxButtonsWidth Max width allowed for buttons */ var removeButtonLabels = function (buttonsWidth, maxButtonsWidth) { // Reverse traversal for (var i = buttonOrder.length - 1; i >= 0; i--) { var buttonId = buttonOrder[i]; var button = buttons[buttonId]; if (!button.isTruncated && button.isVisible) { var $button = button.$element; buttonsWidth -= button.width.max - button.width.min; // Remove label button.$element.attr('aria-label', $button.text()).html('').addClass('truncated'); button.isTruncated = true; if (buttonsWidth <= maxButtonsWidth) { // Buttons are small enough. return; } } } }; /** * Restore button labels until it fills maximum possible width without exceeding the max width. * * @private * @param {Number} buttonsWidth Total width of all buttons * @param {Number} maxButtonsWidth Max width allowed for buttons */ var restoreButtonLabels = function (buttonsWidth, maxButtonsWidth) { for (var i = 0; i < buttonOrder.length; i++) { var buttonId = buttonOrder[i]; var button = buttons[buttonId]; if (button.isTruncated && button.isVisible) { // Calculate new total width of buttons with a static pixel for consistency cross-browser buttonsWidth += button.width.max - button.width.min + 1; if (buttonsWidth > maxButtonsWidth) { return; } // Restore label button.$element.html(button.text); button.$element.removeClass('truncated'); button.isTruncated = false; } } }; /** * Helper function for finding index of keyValue in array * * @param {String} keyValue Value to be found * @param {String} key In key * @param {Array} array In array * @returns {number} */ var existsInArray = function (keyValue, key, array) { var i; for (i = 0; i < array.length; i++) { if (array[i][key] === keyValue) { return i; } } return -1; }; /** * Show a section * @param {Object} section */ var showSection = function (section) { section.$element.addClass('h5p-question-visible'); section.isVisible = true; }; /** * Hide a section * @param {Object} section */ var hideSection = function (section) { section.$element.css('max-height', ''); section.isVisible = false; setTimeout(function () { // Only hide if section hasn't been set to visible in the meantime if (!section.isVisible) { section.$element.removeClass('h5p-question-visible'); } }, 150); }; /** * Set behaviour for question. * * @param {Object} options An object containing behaviour that will be extended by Question */ self.setBehaviour = function (options) { $.extend(behaviour, options); }; /** * A video to display above the task. * * @param {object} params */ self.setVideo = function (params) { sections.video = { $element: $('<div/>', { 'class': 'h5p-question-video' }) }; if (disableAutoPlay && params.params.playback) { params.params.playback.autoplay = false; } // Never fit to wrapper if (!params.params.visuals) { params.params.visuals = {}; } params.params.visuals.fit = false; sections.video.instance = H5P.newRunnable(params, self.contentId, sections.video.$element, true); var fromVideo = false; // Hack to avoid never ending loop sections.video.instance.on('resize', function () { fromVideo = true; self.trigger('resize'); fromVideo = false; }); self.on('resize', function () { if (!fromVideo) { sections.video.instance.trigger('resize'); } }); return self; }; /** * Will stop any playback going on in the task. */ self.pause = function () { if (sections.video && sections.video.isVisible) { sections.video.instance.pause(); } }; /** * Start playback of video */ self.play = function () { if (sections.video && sections.video.isVisible) { sections.video.instance.play(); } }; /** * Disable auto play, useful in editors. */ self.disableAutoPlay = function () { disableAutoPlay = true; }; /** * Add task image. * * @param {string} path Relative * @param {Object} [options] Options object * @param {string} [options.alt] Text representation * @param {string} [options.title] Hover text * @param {Boolean} [options.disableImageZooming] Set as true to disable image zooming */ self.setImage = function (path, options) { options = options ? options : {}; sections.image = {}; // Image container sections.image.$element = $('<div/>', { 'class': 'h5p-question-image h5p-question-image-fill-width' }); // Inner wrap var $imgWrap = $('<div/>', { 'class': 'h5p-question-image-wrap', appendTo: sections.image.$element }); // Image element var $img = $('<img/>', { src: H5P.getPath(path, self.contentId), alt: (options.alt === undefined ? '' : options.alt), title: (options.title === undefined ? '' : options.title), on: { load: function () { self.trigger('imageLoaded', this); self.trigger('resize'); } }, appendTo: $imgWrap }); // Disable image zooming if (options.disableImageZooming) { $img.css('maxHeight', 'none'); // Make sure we are using the correct amount of width at all times var determineImgWidth = function () { // Remove margins if natural image width is bigger than section width var imageSectionWidth = sections.image.$element.get(0).getBoundingClientRect().width; // Do not transition, for instant measurements $imgWrap.css({ '-webkit-transition': 'none', 'transition': 'none' }); // Margin as translateX on both sides of image. var diffX = 2 * ($imgWrap.get(0).getBoundingClientRect().left - sections.image.$element.get(0).getBoundingClientRect().left); if ($img.get(0).naturalWidth >= imageSectionWidth - diffX) { sections.image.$element.addClass('h5p-question-image-fill-width'); } else { // Use margin for small res images sections.image.$element.removeClass('h5p-question-image-fill-width'); } // Reset transition rules $imgWrap.css({ '-webkit-transition': '', 'transition': '' }); }; // Determine image width if ($img.is(':visible')) { determineImgWidth(); } else { $img.on('load', determineImgWidth); } // Skip adding zoom functionality return; } var sizeDetermined = false; var determineSize = function () { if (sizeDetermined || !$img.is(':visible')) { return; // Try again next time. } $imgWrap.addClass('h5p-question-image-scalable') .attr('aria-expanded', false) .attr('role', 'button') .attr('tabIndex', '0') .on('click', function (event) { if (event.which === 1) { scaleImage.apply(this); // Left mouse button click } }).on('keypress', function (event) { if (event.which === 32) { event.preventDefault(); // Prevent default behaviour; page scroll down scaleImage.apply(this); // Space bar pressed } }); sections.image.$element.removeClass('h5p-question-image-fill-width'); sizeDetermined = true; // Prevent any futher events }; self.on('resize', determineSize); return self; }; /** * Add the introduction section. * * @param {(string|H5P.jQuery)} content */ self.setIntroduction = function (content) { register('introduction', content); return self; }; /** * Add the content section. * * @param {(string|H5P.jQuery)} content * @param {Object} [options] * @param {string} [options.class] */ self.setContent = function (content, options) { register('content', content); if (options && options.class) { sections.content.$element.addClass(options.class); } return self; }; /** * Force readspeaker to read text. Useful when you have to use * setTimeout for animations. */ self.read = function (content) { if (!$read) { return; // Not ready yet } if (readText) { // Combine texts if called multiple times readText += (readText.substr(-1, 1) === '.' ? ' ' : '. ') + content; } else { readText = content; } // Set text $read.html(readText); setTimeout(function () { // Stop combining when done reading readText = null; $read.html(''); }, 100); }; /** * Read feedback */ self.readFeedback = function () { var invalidFeedback = behaviour.disableReadSpeaker || !showFeedback || !sections.feedback || !sections.feedback.$element; if (invalidFeedback) { return; } var $feedbackText = $('.h5p-question-feedback-content-text', sections.feedback.$element); if ($feedbackText && $feedbackText.html() && $feedbackText.html().length) { self.read($feedbackText.html()); } }; /** * Remove feedback * * @return {H5P.Question} */ self.removeFeedback = function () { clearTimeout(feedbackTransitionTimer); if (sections.feedback && showFeedback) { showFeedback = false; // Hide feedback & scorebar hideSection(sections.scorebar); hideSection(sections.feedback); sectionsIsTransitioning = true; // Detach after transition feedbackTransitionTimer = setTimeout(function () { // Avoiding Transition.onTransitionEnd since it will register multiple events, and there's no way to cancel it if the transition changes back to "show" while the animation is happening. if (!showFeedback) { sections.feedback.$element.children().detach(); sections.scorebar.$element.children().detach(); // Trigger resize after animation self.trigger('resize'); } sectionsIsTransitioning = false; scoreBar.setScore(0); }, 150); if ($wrapper) { $wrapper.find('.h5p-question-feedback-tail').remove(); } } return self; }; /** * Set feedback message. * * @param {string} [content] * @param {number} score The score * @param {number} maxScore The maximum score for this question * @param {string} [scoreBarLabel] Makes it easier for readspeakers to identify the scorebar * @param {string} [helpText] Help text that describes the score inside a tip icon * @param {object} [popupSettings] Extra settings for popup feedback * @param {boolean} [popupSettings.showAsPopup] Should the feedback display as popup? * @param {string} [popupSettings.closeText] Translation for close button text * @param {object} [popupSettings.click] Element representing where user clicked on screen */ self.setFeedback = function (content, score, maxScore, scoreBarLabel, helpText, popupSettings, scoreExplanationButtonLabel) { // Feedback is disabled if (behaviour.disableFeedback) { return self; } // Need to toggle buttons right away to avoid flickering/blinking // Note: This means content types should invoke hide/showButton before setFeedback toggleButtons(); clickElement = (popupSettings != null && popupSettings.click != null ? popupSettings.click : null); clearTimeout(feedbackTransitionTimer); var $feedback = $('<div>', { 'class': 'h5p-question-feedback-container' }); var $feedbackContent = $('<div>', { 'class': 'h5p-question-feedback-content' }).appendTo($feedback); // Feedback text $('<div>', { 'class': 'h5p-question-feedback-content-text', 'html': content }).appendTo($feedbackContent); var $scorebar = $('<div>', { 'class': 'h5p-question-scorebar-container' }); if (scoreBar === undefined) { scoreBar = JoubelUI.createScoreBar(maxScore, scoreBarLabel, helpText, scoreExplanationButtonLabel); } scoreBar.appendTo($scorebar); $feedbackContent.toggleClass('has-content', content !== undefined && content.length > 0); // Feedback for readspeakers if (!behaviour.disableReadSpeaker && scoreBarLabel) { self.read(scoreBarLabel.replace(':num', score).replace(':total', maxScore) + '. ' + (content ? content : '')); } showFeedback = true; if (sections.feedback) { // Update section update('feedback', $feedback); update('scorebar', $scorebar); } else { // Create section register('feedback', $feedback); register('scorebar', $scorebar); if (initialized && $wrapper) { insert(self.order, 'feedback', sections, $wrapper); insert(self.order, 'scorebar', sections, $wrapper); } } showSection(sections.feedback); showSection(sections.scorebar); resizeButtons(); if (popupSettings != null && popupSettings.showAsPopup == true) { makeFeedbackPopup(popupSettings.closeText); scoreBar.setScore(score); } else { // Show feedback section feedbackTransitionTimer = setTimeout(function () { setElementHeight(sections.feedback.$element); setElementHeight(sections.scorebar.$element); sectionsIsTransitioning = true; // Scroll to bottom after showing feedback scrollToBottom(); // Trigger resize after animation feedbackTransitionTimer = setTimeout(function () { sectionsIsTransitioning = false; self.trigger('resize'); scoreBar.setScore(score); }, 150); }, 0); } return self; }; /** * Set feedback content (no animation). * * @param {string} content * @param {boolean} [extendContent] True will extend content, instead of replacing it */ self.updateFeedbackContent = function (content, extendContent) { if (sections.feedback && sections.feedback.$element) { if (extendContent) { content = $('.h5p-question-feedback-content', sections.feedback.$element).html() + ' ' + content; } // Update feedback content html $('.h5p-question-feedback-content', sections.feedback.$element).html(content).addClass('has-content'); // Make sure the height is correct setElementHeight(sections.feedback.$element); // Need to trigger resize when feedback has finished transitioning setTimeout(self.trigger.bind(self, 'resize'), 150); } return self; }; /** * Set the content of the explanation / feedback panel * * @param {Object} data * @param {string} data.correct * @param {string} data.wrong * @param {string} data.text * @param {string} title Title for explanation panel * * @return {H5P.Question} */ self.setExplanation = function (data, title) { if (data) { var explainer = new H5P.Question.Explainer(title, data); if (sections.explanation) { // Update section update('explanation', explainer.getElement()); } else { register('explanation', explainer.getElement()); if (initialized && $wrapper) { insert(self.order, 'explanation', sections, $wrapper); } } } else if (sections.explanation) { // Hide explanation section sections.explanation.$element.children().detach(); } return self; }; /** * Checks to see if button is registered. * * @param {string} id * @returns {boolean} */ self.hasButton = function (id) { return (buttons[id] !== undefined); }; /** * @typedef {Object} ConfirmationDialog * @property {boolean} [enable] Must be true to show confirmation dialog * @property {Object} [instance] Instance that uses confirmation dialog * @property {jQuery} [$parentElement] Append to this element. * @property {Object} [l10n] Translatable fields * @property {string} [l10n.header] Header text * @property {string} [l10n.body] Body text * @property {string} [l10n.cancelLabel] * @property {string} [l10n.confirmLabel] */ /** * Register buttons for the task. * * @param {string} id * @param {string} text label * @param {function} clicked * @param {boolean} [visible=true] * @param {Object} [options] Options for button * @param {Object} [extras] Extra options * @param {ConfirmationDialog} [extras.confirmationDialog] Confirmation dialog */ self.addButton = function (id, text, clicked, visible, options, extras) { if (buttons[id]) { return self; // Already registered } if (sections.buttons === undefined) { // We have buttons, register wrapper register('buttons'); if (initialized) { insert(self.order, 'buttons', sections, $wrapper); } } extras = extras || {}; extras.confirmationDialog = extras.confirmationDialog || {}; options = options || {}; var confirmationDialog = self.addConfirmationDialogToButton(extras.confirmationDialog, clicked); /** * Handle button clicks through both mouse and keyboard * @private */ var handleButtonClick = function () { if (extras.confirmationDialog.enable && confirmationDialog) { // Show popups section if used if (!extras.confirmationDialog.$parentElement) { sections.popups.$element.removeClass('hidden'); } confirmationDialog.show($e.position().top); } else { clicked(); } }; buttons[id] = { isTruncated: false, text: text, isVisible: false }; // The button might be <button> or <a> // (dependent on options.href set or not) var isAnchorTag = (options.href !== undefined); var $e = buttons[id].$element = JoubelUI.createButton($.extend({ 'class': 'h5p-question-' + id, html: text, title: text, on: { click: function (event) { handleButtonClick(); if (isAnchorTag) { event.preventDefault(); } } } }, options)); buttonOrder.push(id); // The button might be <button> or <a>. If <a>, the space key is not // triggering the click event, must therefore handle this here: if (isAnchorTag) { $e.on('keypress', function (event) { if (event.which === 32) { // Space handleButtonClick(); event.preventDefault(); } }); } if (visible === undefined || visible) { // Button should be visible $e.appendTo(sections.buttons.$element); buttons[id].isVisible = true; showSection(sections.buttons); } return self; }; var setButtonWidth = function (button) { var $button = button.$element; var $tmp = $button.clone() .css({ 'position': 'absolute', 'white-space': 'nowrap', 'max-width': 'none' }).removeClass('truncated') .html(button.text) .appendTo($button.parent()); // Calculate max width (button including text) button.width = { max: Math.ceil($tmp.outerWidth() + parseFloat($tmp.css('margin-left')) + parseFloat($tmp.css('margin-right'))) }; // Calculate min width (truncated, icon only) $tmp.html('').addClass('truncated'); button.width.min = Math.ceil($tmp.outerWidth() + parseFloat($tmp.css('margin-left')) + parseFloat($tmp.css('margin-right'))); $tmp.remove(); }; /** * Add confirmation dialog to button * @param {ConfirmationDialog} options * A confirmation dialog that will be shown before click handler of button * is triggered * @param {function} clicked * Click handler of button * @return {H5P.ConfirmationDialog|undefined} * Confirmation dialog if enabled */ self.addConfirmationDialogToButton = function (options, clicked) { options = options || {}; if (!options.enable) { return; } // Confirmation dialog var confirmationDialog = new H5P.ConfirmationDialog({ instance: options.instance, headerText: options.l10n.header, dialogText: options.l10n.body, cancelText: options.l10n.cancelLabel, confirmText: options.l10n.confirmLabel }); // Determine parent element if (options.$parentElement) { confirmationDialog.appendTo(options.$parentElement.get(0)); } else { // Create popup section and append to that if (sections.popups === undefined) { register('popups'); if (initialized) { insert(self.order, 'popups', sections, $wrapper); } sections.popups.$element.addClass('hidden'); self.order.push('popups'); } confirmationDialog.appendTo(sections.popups.$element.get(0)); } // Add event listeners confirmationDialog.on('confirmed', function () { if (!options.$parentElement) { sections.popups.$element.addClass('hidden'); } clicked(); // Trigger to content type self.trigger('confirmed'); }); confirmationDialog.on('canceled', function () { if (!options.$parentElement) { sections.popups.$element.addClass('hidden'); } // Trigger to content type self.trigger('canceled'); }); return confirmationDialog; }; /** * Show registered button with given identifier. * * @param {string} id * @param {Number} [priority] */ self.showButton = function (id, priority) { var aboutToBeHidden = existsInArray(id, 'id', buttonsToHide) !== -1; if (buttons[id] === undefined || (buttons[id].isVisible === true && !aboutToBeHidden)) { return self; } priority = priority || 0; // Skip if already being shown var indexToShow = existsInArray(id, 'id', buttonsToShow); if (indexToShow !== -1) { // Update priority if (buttonsToShow[indexToShow].priority < priority) { buttonsToShow[indexToShow].priority = priority; } return self; } // Check if button is going to be hidden on next tick var exists = existsInArray(id, 'id', buttonsToHide); if (exists !== -1) { // Skip hiding if higher priority if (buttonsToHide[exists].priority <= priority) { buttonsToHide.splice(exists, 1); buttonsToShow.push({id: id, priority: priority}); } } // If button is not shown else if (!buttons[id].$element.is(':visible')) { // Show button on next tick buttonsToShow.push({id: id, priority: priority}); } if (!toggleButtonsTimer) { toggleButtonsTimer = setTimeout(toggleButtons, 0); } return self; }; /** * Hide registered button with given identifier. * * @param {string} id * @param {number} [priority] */ self.hideButton = function (id, priority) { var aboutToBeShown = existsInArray(id, 'id', buttonsToShow) !== -1; if (buttons[id] === undefined || (buttons[id].isVisible === false && !aboutToBeShown)) { return self; } priority = priority || 0; // Skip if already being hidden var indexToHide = existsInArray(id, 'id', buttonsToHide); if (indexToHide !== -1) { // Update priority if (buttonsToHide[indexToHide].priority < priority) { buttonsToHide[indexToHide].priority = priority; } return self; } // Check if buttons is going to be shown on next tick var exists = existsInArray(id, 'id', buttonsToShow); if (exists !== -1) { // Skip showing if higher priority if (buttonsToShow[exists].priority <= priority) { buttonsToShow.splice(exists, 1); buttonsToHide.push({id: id, priority: priority}); } } else if (!buttons[id].$element.is(':visible')) { // Make sure it is detached in case the container is hidden. hideButton(id); } else { // Hide button on next tick. buttonsToHide.push({id: id, priority: priority}); } if (!toggleButtonsTimer) { toggleButtonsTimer = setTimeout(toggleButtons, 0); } return self; }; /** * Set focus to the given button. If no button is given the first visible * button gets focused. This is useful if you lose focus. * * @param {string} [id] */ self.focusButton = function (id) { if (id === undefined) { // Find first button that is visible. for (var i = 0; i < buttonOrder.length; i++) { var button = buttons[buttonOrder[i]]; if (button && button.isVisible) { // Give that button focus button.$element.focus(); break; } } } else if (buttons[id] && buttons[id].$element.is(':visible')) { // Set focus to requested button buttons[id].$element.focus(); } return self; }; /** * Toggle readspeaker functionality * @param {boolean} [disable] True to disable, false to enable. */ self.toggleReadSpeaker = function (disable) { behaviour.disableReadSpeaker = disable || !behaviour.disableReadSpeaker; }; /** * Set new element for section. * * @param {String} id * @param {H5P.jQuery} $element */ self.insertSectionAtElement = function (id, $element) { if (sections[id] === undefined) { register(id); } sections[id].parent = $element; // Insert section if question is not initialized if (!initialized) { insert([id], id, sections, $element); } return self; }; /** * Attach content to given container. * * @param {H5P.jQuery} $container */ self.attach = function ($container) { if (self.isRoot()) { self.setActivityStarted(); } // The first time we attach we also create our DOM elements. if ($wrapper === undefined) { if (self.registerDomElements !== undefined && (self.registerDomElements instanceof Function || typeof self.registerDomElements === 'function')) { // Give the question type a chance to register before attaching self.registerDomElements(); } // Create section for reading messages $read = $('<div/>', { 'aria-live': 'polite', 'class': 'h5p-hidden-read' }); register('read', $read); self.trigger('registerDomElements'); } // Prepare container $wrapper = $container; $container.html('') .addClass('h5p-question h5p-' + type); // Add sections in given order var $sections = []; for (var i = 0; i < self.order.length; i++) { var section = self.order[i]; if (sections[section]) { if (sections[section].parent) { // Section has a different parent sections[section].$element.appendTo(sections[section].parent); } else { $sections.push(sections[section].$element); } sections[section].isVisible = true; } } // Only append once to DOM for optimal performance $container.append($sections); // Let others react to dom changes self.trigger('domChanged', { '$target': $container, 'library': self.libraryInfo.machineName, 'contentId': self.contentId, 'key': 'newLibrary' }, {'bubbles': true, 'external': true}); // ?? initialized = true; return self; }; /** * Detach all sections from their parents */ self.detachSections = function () { // Deinit Question initialized = false; // Detach sections for (var section in sections) { sections[section].$element.detach(); } return self; }; // Listen for resize self.on('resize', function () { // Allow elements to attach and set their height before resizing if (!sectionsIsTransitioning && sections.feedback && showFeedback) { // Resize feedback to fit setElementHeight(sections.feedback.$element); } // Re-position feedback popup if in use var $element = sections.feedback; var $click = clickElement; if ($element != null && $element.$element != null && $click != null && $click.$element != null) { setTimeout(function () { positionFeedbackPopup($element.$element, $click.$element); }, 10); } resizeButtons(); }); } // Inheritance Question.prototype = Object.create(EventDispatcher.prototype); Question.prototype.constructor = Question; /** * Determine the overall feedback to display for the question. * Returns empty string if no matching range is found. * * @param {Object[]} feedbacks * @param {number} scoreRatio * @return {string} */ Question.determineOverallFeedback = function (feedbacks, scoreRatio) { scoreRatio = Math.floor(scoreRatio * 100); for (var i = 0; i < feedbacks.length; i++) { var feedback = feedbacks[i]; var hasFeedback = (feedback.feedback !== undefined && feedback.feedback.trim().length !== 0); if (feedback.from <= scoreRatio && feedback.to >= scoreRatio && hasFeedback) { return feedback.feedback; } } return ''; }; return Question; })(H5P.jQuery, H5P.EventDispatcher, H5P.JoubelUI);
/** * Copyright (C) 2016, BMW AG * Author: Stefan Holder (stefan.holder@bmw.de) * C++ Conversion: Junho Han (junhohan.kr@gmail.com) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef TRANSITION_H_ #define TRANSITION_H_ #include <iostream> namespace hmm { template <typename S> class Transition; template <typename S> bool operator==(const Transition<S>& lhs, const Transition<S>& rhs); template <typename S> bool operator<(const Transition<S>& lhs, const Transition<S>& rhs); template <typename S> class Transition { public: const S fromCandidate; const S toCandidate; friend bool operator==<>(const Transition<S>& lhs, const Transition<S>& rhs); friend bool operator< <>(const Transition<S>& lhs, const Transition<S>& rhs); Transition(S fromCandidate, S toCandidate) : fromCandidate(fromCandidate), toCandidate(toCandidate) {} ~Transition() {} std::string ToString() { return "Transition [fromCandidate=" + fromCandidate + ", toCandidate=" + toCandidate + "]"; } }; template <typename S> bool operator==(const Transition<S>& lhs, const Transition<S>& rhs) { auto rst = lhs.fromCandidate == rhs.fromCandidate && lhs.toCandidate == rhs.toCandidate; return rst; } template <typename S> bool operator<(Transition<S> const& lhs, Transition<S> const& rhs) { if (lhs.fromCandidate < rhs.fromCandidate) { return true; } else if (lhs.fromCandidate == rhs.fromCandidate) { if (lhs.toCandidate < rhs.toCandidate) { return true; } } return false; } } // namespace hmm #endif // TRANSITION_H_
import _plotly_utils.basevalidators class ColorValidator(_plotly_utils.basevalidators.ColorValidator): def __init__(self, plotly_name="color", parent_name="mesh3d.contour", **kwargs): super(ColorValidator, self).__init__( plotly_name=plotly_name, parent_name=parent_name, edit_type=kwargs.pop("edit_type", "calc"), **kwargs, )
module.exports = { name: 'Google Search', section: 'Other Stuff', subtitle (data) { const info = ['Title', 'URL', 'Snippet'] return `Google Result ${info[parseInt(data.info)]}` }, variableStorage (data, varType) { const type = parseInt(data.storage) if (type !== varType) return const info = parseInt(data.info) let dataType = 'Unknown Google Type' switch (info) { case 0: dataType = 'Google Result Title' break case 1: dataType = 'Google Result URL' break case 2: dataType = 'Google Result Snippet' break } return ([data.varName, dataType]) }, fields: ['string', 'info', 'resultNo', 'storage', 'varName'], html (isEvent, data) { return ` <div style="width: 95%; padding-top: 8px;"> String(s) to Search on Google:<br> <textarea id="string" rows="5" placeholder="Write something or use variables to Google search it..." style="width: 100%; font-family: monospace; white-space: nowrap; resize: none;"></textarea> </div><br> <div style="float: left; width: 45%; padding-top: 8px;"> Source Info:<br> <select id="info" class="round"> <option value="0">Result Title</option> <option value="1">Result URL</option> <option value="2">Result Snippet (Description)</option> </select> </div> <div style="float: left; width: 50%; padding-left: 10px; padding-top: 8px;"> Result Number:<br> <select id="resultNo" class="round"> <option value="0">1st Result</option> <option value="1">2nd Result</option> <option value="2">3rd Result</option> <option value="3">4th Result</option> <option value="4">5th Result</option> <option value="5">6th Result</option> <option value="6">7th Result</option> <option value="7">8th Result</option> <option value="8">9th Result</option> <option value="9">10th Result</option> </select> </div><br><br> <div style="float: left; width: 43%; padding-top: 8px;"> Store In:<br> <select id="storage" class="round" onchange="glob.variableChange(this, 'varNameContainer')"> ${data.variables[0]} </select> </div> <div id="varNameContainer" style="float: right; width: 53%; padding-top: 8px;"> Variable Name:<br> <input id="varName" class="round" type="text"><br> </div>` }, init () { const { glob, document } = this glob.variableChange(document.getElementById('storage'), 'varNameContainer') }, action (cache) { const data = cache.actions[cache.index] const info = parseInt(data.info) const string = this.evalMessage(data.string, cache).replace(/[\u{0080}-\u{FFFF}]/gu, '') // The replace thing is very new, it's just replacing the invalid characters so command won't stuck when you use other languages. const resultNumber = parseInt(data.resultNo) if (!string) return console.log('Please write something to Google it!') const Mods = this.getMods() const googleIt = Mods.require('google-it') googleIt({ query: `${string}`, 'no-display': 1, limit: 10 }).then((results) => { let result switch (info) { case 0: result = results[resultNumber].title break case 1: result = results[resultNumber].link break case 2: result = results[resultNumber].snippet break default: break } if (result !== undefined) { const storage = parseInt(data.storage) const varName2 = this.evalMessage(data.varName, cache) this.storeValue(result, storage, varName2, cache) this.callNextAction(cache) } else { this.callNextAction(cache) } }).catch((e) => { console.log(`An error in Google Search MOD: ${e}`) this.callNextAction(cache) }) }, mod () {} }
#!/usr/bin/python3 # read the lines from the file fh = open('lines.txt') for line in fh.readlines(): print(line)
from service_capacity_modeling.capacity_planner import planner from service_capacity_modeling.interface import CapacityDesires from service_capacity_modeling.interface import certain_int from service_capacity_modeling.interface import DataShape from service_capacity_modeling.interface import Interval from service_capacity_modeling.interface import QueryPattern user_desires = CapacityDesires( service_tier=0, query_pattern=QueryPattern( estimated_read_per_second=certain_int(100000), estimated_write_per_second=certain_int(100000), estimated_mean_read_size_bytes=Interval( low=10, mid=100, high=1000, confidence=0.98 ), ), data_shape=DataShape( estimated_state_size_gib=certain_int(10), ), ) def test_cassandra_merge(): cass_defaults = planner.models["org.netflix.cassandra"].default_desires( user_desires, {} ) merged = user_desires.merge_with(cass_defaults) # Should come from the user assert merged.service_tier == 0 assert merged.query_pattern.estimated_read_per_second.mid == 100000 assert merged.query_pattern.estimated_mean_read_size_bytes.low == 10 assert merged.data_shape.estimated_state_size_gib.mid == 10 # Should come from cassandra assert merged.query_pattern.estimated_mean_read_latency_ms.mid == 2.0 assert merged.query_pattern.estimated_mean_write_latency_ms.mid == 1.0 # Should come from overall defaults assert merged.data_shape.estimated_state_item_count is None assert merged.core_reference_ghz == 2.3
import React, { Component } from 'react'; class About extends Component { render() { if(this.props.data){ var name = this.props.data.name; var profilepic= "images/"+this.props.data.image; var bio = this.props.data.bio; var street = this.props.data.address.street; var city = this.props.data.address.city; var state = this.props.data.address.state; var zip = this.props.data.address.zip; var phone= this.props.data.phone; var email = this.props.data.email; var resumeDownload = this.props.data.resumedownload; } return ( <section id="about"> <div className="row"> <div className="three columns"> <img className="profile-pic" src={profilepic} alt="Mehmood Ayaz Profile Pic" /> </div> <div className="nine columns main-col"> <h2>About Me</h2> <p>{bio}</p> <div className="row"> <div className="columns contact-details"> <h2>Contact Details</h2> <p className="address"> <span>{name}</span><br /> <span>{street}<br /> {city} {state}, {zip} </span><br /> <span>{phone}</span><br /> <span>{email}</span> </p> </div> <div className="columns download"> <p> <a href={resumeDownload} className="button"><i className="fa fa-download"></i>Download Resume</a> </p> </div> </div> </div> </div> </section> ); } } export default About;
/** * 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 typeof * as FeatureFlagsType from 'shared/ReactFeatureFlags'; import typeof * as FeatureFlagsShimType from './ReactFeatureFlags.www'; // Re-export dynamic flags from the www version. export const { debugRenderPhaseSideEffects, debugRenderPhaseSideEffectsForStrictMode, replayFailedUnitOfWorkWithInvokeGuardedCallback, warnAboutDeprecatedLifecycles, disableInputAttributeSyncing, warnAboutShorthandPropertyCollision, warnAboutDeprecatedSetNativeProps, revertPassiveEffectsChange, enableUserBlockingEvents, } = require('ReactFeatureFlags'); // In www, we have experimental support for gathering data // from User Timing API calls in production. By default, we // only emit performance.mark/measure calls in __DEV__. But if // somebody calls addUserTimingListener() which is exposed as an // experimental FB-only export, we call performance.mark/measure // as long as there is more than a single listener. export let enableUserTimingAPI = __DEV__; export const enableProfilerTimer = __PROFILE__; export const enableSchedulerTracing = __PROFILE__; export const enableSchedulerDebugging = true; export const enableStableConcurrentModeAPIs = false; export const enableSuspenseServerRenderer = true; export const disableJavaScriptURLs = true; let refCount = 0; export function addUserTimingListener() { if (__DEV__) { // Noop. return () => {}; } refCount++; updateFlagOutsideOfReactCallStack(); return () => { refCount--; updateFlagOutsideOfReactCallStack(); }; } // The flag is intentionally updated in a timeout. // We don't support toggling it during reconciliation or // commit since that would cause mismatching user timing API calls. let timeout = null; function updateFlagOutsideOfReactCallStack() { if (!timeout) { timeout = setTimeout(() => { timeout = null; enableUserTimingAPI = refCount > 0; }); } } export const enableFlareAPI = true; export const enableJSXTransformAPI = true; export const warnAboutMissingMockScheduler = true; // Flow magic to verify the exports of this file match the original version. // eslint-disable-next-line no-unused-vars type Check<_X, Y: _X, X: Y = _X> = null; // eslint-disable-next-line no-unused-expressions (null: Check<FeatureFlagsShimType, FeatureFlagsType>);
// // Datatypes.h // backendlessAPI /* * ********************************************************************************************************************* * * BACKENDLESS.COM CONFIDENTIAL * * ******************************************************************************************************************** * * Copyright 2018 BACKENDLESS.COM. All Rights Reserved. * * NOTICE: All information contained herein is, and remains the property of Backendless.com and its suppliers, * if any. The intellectual and technical concepts contained herein are proprietary to Backendless.com and its * suppliers and may be covered by U.S. and Foreign Patents, patents in process, and are protected by trade secret * or copyright law. Dissemination of this information or reproduction of this material is strictly forbidden * unless prior written permission is obtained from Backendless.com. * * ******************************************************************************************************************** */ typedef enum amf_protocol_encoding ProtocolEncoding; typedef enum amf0_datatype amf0_datatype_t; typedef enum amf3_datatype amf3_datatype_t; typedef enum rtmp_datatype rtmp_datatype_t; enum amf_protocol_encoding { AMF0 = 0, AMF3 = 3, }; enum amf0_datatype { NUMBER_DATATYPE_V1 = 0, // 0x00 BOOLEAN_DATATYPE_V1 = 1, // 0x01 UTFSTRING_DATATYPE_V1 = 2, // 0x02 OBJECT_DATATYPE_V1 = 3, // 0x03 NULL_DATATYPE_V1 = 5, // 0x05 UNKNOWN_DATATYPE_V1 = 6, // 0x06 POINTER_DATATYPE_V1 = 7, // 0x07 OBJECTARRAY_DATATYPE_V1 = 8, // 0x08 ENDOFOBJECT_DATATYPE_V1 = 9, // 0x09 ARRAY_DATATYPE_V1 = 10, // 0x0A DATE_DATATYPE_V1 = 11, // 0x0B LONGUTFSTRING_DATATYPE_V1 = 12, // 0x0C REMOTEREFERENCE_DATATYPE_V1 = 13, // 0x0D RECORDSET_DATATYPE_V1 = 14, // 0x0E PARSEDXML_DATATYPE_V1 = 15, // 0x0F NAMEDOBJECT_DATATYPE_V1 = 16, // 0x10 V3_DATATYPE = 17, // 0x11 TOTAL_V1TYPES = 18, // 0x12 }; enum amf3_datatype { UNKNOWN_DATATYPE_V3 = 0, // 0x00 NULL_DATATYPE_V3 = 1, // 0x01 BOOLEAN_DATATYPE_FALSEV3 = 2, // 0x02 BOOLEAN_DATATYPE_TRUEV3 = 3, // 0x03 INTEGER_DATATYPE_V3 = 4, // 0x04 DOUBLE_DATATYPE_V3 = 5, // 0x05 UTFSTRING_DATATYPE_V3 = 6, // 0x06 XML_DATATYPE_V3 = 7, // 0x07 DATE_DATATYPE_V3 = 8, // 0x08 ARRAY_DATATYPE_V3 = 9, // 0x09 OBJECT_DATATYPE_V3 = 10, // 0x0A LONGXML_DATATYPE_V3 = 11, // 0x0B BYTEARRAY_DATATYPE_V3 = 12, // 0x0C INT_VECTOR_V3 = 13, // 0x0D UINT_VECTOR_V3 = 14, // 0x0E DOUBLE_VECTOR_V3 = 15, // 0x0F OBJECT_VECTOR_V3 = 16, // 0x10 TOTAL_V3TYPES = 17, // 0x11 }; enum rtmp_datatype { RTMP_DATATYPE_SKIPTYPE = 0, // 0x00 RTMP_DATATYPE_NULL = 1, // 0x01 RTMP_DATATYPE_BOOLEAN = 2, // 0x02 RTMP_DATATYPE_NUMBER = 3, // 0x03 RTMP_DATATYPE_STRING = 4, // 0x04 RTMP_DATATYPE_DATE = 5, // 0x05 RTMP_DATATYPE_ARRAY = 6, // 0x06 RTMP_DATATYPE_MAP = 7, // 0x07 RTMP_DATATYPE_XML = 8, // 0x08 RTMP_DATATYPE_OBJECT = 9, // 0x09 RTMP_DATATYPE_REFERENCE = 10, // 0x0A TOTAL_RTMPTYPES = 11, // 0x0B };
#include "sqlite3.c" #include "sqlc.h" /* types needed for SQLiteNative_JNI.c */ #include "SQLiteNative_JNI.c" #include "jsmn.c" #include "sqlc.c"
/* * This header is generated by classdump-dyld 1.0 * on Tuesday, November 5, 2019 at 3:11:38 PM Mountain Standard Time * Operating System: Version 13.0 (Build 17J586) * Image Source: /usr/libexec/gamed * classdump-dyld is licensed under GPLv3, Copyright © 2013-2016 by Elias Limneos. */ #import <gamed/gamed-Structs.h> #import <gamed/GKDatabaseWriter.h> @class GKDatabaseConnection, NSString; @interface GKDelayedSetPlayerStatusCacheWriter : NSObject <GKDatabaseWriter> { GKDatabaseConnection* _connection; } @property (nonatomic,retain) GKDatabaseConnection * connection; //@synthesize connection=_connection - In the implementation block @property (readonly) unsigned long long hash; @property (readonly) Class superclass; @property (copy,readonly) NSString * description; @property (copy,readonly) NSString * debugDescription; @property (nonatomic,readonly) GKDatabaseConnection * databaseConnection; +(id)writerWithDatabaseConnection:(id)arg1 ; -(void)dealloc; -(void)setConnection:(GKDatabaseConnection *)arg1 ; -(GKDatabaseConnection *)connection; -(id)initWithDatabaseConnection:(id)arg1 ; -(GKDatabaseConnection *)databaseConnection; -(void)writeToDatabase:(sqlite3Ref)arg1 statementStore:(id)arg2 withInsertSQL:(id)arg3 updateSQL:(id)arg4 bindOperation:(/*^block*/id)arg5 ; -(void)writeResources:(id)arg1 handler:(/*^block*/id)arg2 ; -(id)requestsInsertSQL; -(void)bindParametersForRequestsStatement:(sqlite3_stmtRef)arg1 playerID:(id)arg2 ; -(id)getOldStatusesSQL; -(id)deleteOldStatusesSQL; -(void)bindParametersForGetOldStatusesStatement:(sqlite3_stmtRef)arg1 playerID:(id)arg2 ; -(void)bindParametersForDeleteOldStatusesStatement:(sqlite3_stmtRef)arg1 requestsRowID:(long long)arg2 ; -(id)statusInsertSQL; -(void)bindParametersForStatusStatement:(sqlite3_stmtRef)arg1 status:(id)arg2 requestsRowID:(long long)arg3 ; @end
/** * First we will load all of this project's JavaScript dependencies which * includes Vue and other libraries. It is a great starting point when * building robust, powerful web applications using Vue and Laravel. */ require('./bootstrap'); window.Vue = require('vue'); //chat-scroll import Vue from 'vue' import VueChatScroll from 'vue-chat-scroll' Vue.use(VueChatScroll) /// for notifications import Toaster from 'v-toaster' import 'v-toaster/dist/v-toaster.css' Vue.use(Toaster, {timeout: 5000}) //emoji mart import { Picker } from 'emoji-mart-vue' /** * The following block of code may be used to automatically register your * Vue components. It will recursively scan this directory for the Vue * components and automatically register them with their "basename". * * Eg. ./components/ExampleComponent.vue -> <example-component></example-component> */ // const files = require.context('./', true, /\.vue$/i) // files.keys().map(key => Vue.component(key.split('/').pop().split('.')[0], files(key).default)) Vue.component('message', require('./components/ChatComponent.vue').default); /** * Next, we will create a fresh Vue application instance and attach it to * the page. Then, you may begin adding components to this application * or customize the JavaScript scaffolding to fit your unique needs. */ const app = new Vue({ el: '#app', data:{ message:'', chat:{ message:[], user:[], color:[], time:[] }, typing:'', numberOfUsers:0, emoStatus:false, }, watch:{ message(){ Echo.private('chat') .whisper('typing', { name: this.message }); } }, methods:{ send(){ if (this.message.length != 0) { this.chat.message.push(this.message); this.chat.color.push('success'); this.chat.user.push('you'); this.chat.time.push(this.getTime()); axios.post('/send', { message : this.message, chat:this.chat }) .then(response => { console.log(response); this.message = '' }) .catch(error => { console.log(error); }); } }, getTime(){ let time = new Date(); return time.getHours()+':'+time.getMinutes(); }, getOldMessages(){ axios.post('/getOldMessage') .then(response => { console.log(response); if (response.data != '') { this.chat = response.data; } }) .catch(error => { console.log(error); }); }, deleteSession(){ axios.post('/deleteSession') .then(response=> this.$toaster.success('Chat history is deleted') ); }, }, mounted(){ this.getOldMessages(); Echo.private('chat') .listen('ChatEvent', (e) => { this.chat.message.push(e.message); this.chat.user.push(e.user); this.chat.color.push('warning'); this.chat.time.push(this.getTime()); axios.post('/saveToSession',{ chat : this.chat }) .then(response => { }) .catch(error => { console.log(error); }); // console.log(e); }) .listenForWhisper('typing', (e) => { if (e.name != '') { this.typing = 'typing...' }else{ this.typing = '' } }) Echo.join(`chat`) .here((users) => { this.numberOfUsers = users.length; }) .joining((user) => { this.numberOfUsers += 1; // console.log(user); this.$toaster.success(user.name+' is joined the chat room'); }) .leaving((user) => { this.numberOfUsers -= 1; this.$toaster.warning(user.name+' is leaved the chat room'); }); } });
import Mixin from '@ember/object/mixin'; import $ from 'jquery'; export let Serializer = Mixin.create({ getAttrs: function () { let parentAttrs = this._super(); let attrs = { class: { serialize: 'odata-id', deserialize: 'records' }, parameters: { serialize: false, deserialize: 'records' } }; return $.extend(true, {}, parentAttrs, attrs); }, init: function () { this.set('attrs', this.getAttrs()); this._super(...arguments); } });
from abc import ABCMeta, abstractmethod from celery.result import AsyncResult from decimal import Decimal PROGRESS_STATE = 'PROGRESS' class AbtractProgressRecorder(object): __metaclass__ = ABCMeta @abstractmethod def set_progress(self, current, total): pass class ConsoleProgressRecorder(AbtractProgressRecorder): def set_progress(self, current, total): print('processed {} items of {}'.format(current, total)) class ProgressRecorder(AbtractProgressRecorder): def __init__(self, task): self.task = task def set_progress(self, current, total): percent = round((Decimal(current) / Decimal(total)) * Decimal(100), 2) if total > 0 else 0 self.task.update_state( state=PROGRESS_STATE, meta={ 'current': current, 'total': total, 'percent': percent, } ) def stop_task(self, current, total, exc): self.task.update_state( state='FAILURE', meta={ 'current': current, 'total': total, 'percent': 100.0, 'exc_message': str(exc), 'exc_type': str(type(exc)) } ) class Progress(object): def __init__(self, task_id): self.task_id = task_id self.result = AsyncResult(task_id) def get_info(self): if self.result.ready(): return { 'complete': True, 'success': self.result.successful(), 'progress': _get_completed_progress() } elif self.result.state == PROGRESS_STATE: return { 'complete': False, 'success': None, 'progress': self.result.info, } elif self.result.state in ['PENDING', 'STARTED']: return { 'complete': False, 'success': None, 'progress': _get_unknown_progress(), } return self.result.info def _get_completed_progress(): return { 'current': 100, 'total': 100, 'percent': 100, } def _get_unknown_progress(): { 'current': 0, 'total': 100, 'percent': 0, }
// Scrapes all the airing dramas const puppeteer = require('puppeteer'); const url = 'https://wiki.d-addicts.com/List_of_Dramas_aired_in_Korea_by_Network_in_2018'; (async () => { const browser = await puppeteer.launch(); const page = await browser.newPage(); await page.goto(url); await page.waitForSelector('.mw-parser-output'); // Make dramas have loaded before continuing const airing = await page.$$('#airing > td:nth-child(3) > a:nth-child(1)'); // Get drama anchors elements // extract href attribute from anchors for (let i = 0; i < airing.length; i++) { let dramaURL = await (await airing[i].getProperty('href')).jsonValue(); console.log(dramaURL); } await browser.close(); })();
# https://programmers.co.kr/learn/courses/30/lessons/42584 def solution(prices): answer = [] length = len(prices) for i in range(length): now_value = prices[i] for j in range(i+1, length): if prices[j] < now_value or j == length -1: answer.append(j-i) break answer.append(0) return answer
import {CustomFunctionValidationRule} from '../../src/validation-rules'; import {Expectations} from '../expectations'; //No need to test empty values, they are filtered out by the "ValidationProperty" depending if they are 'isNotEmpty()' describe('Tests on CustomFunctionValidationRule', () => { it('should be working with simple funtions', (done) => { var expectations = new Expectations(expect, done); var rule = new CustomFunctionValidationRule((newValue, threshold) => { return newValue !== '1337'; }); expectations.expectAsync(rule.validate('1337')).toBe(false); var rule = new CustomFunctionValidationRule((newValue, threshold) => { return newValue === '1337'; }); expectations.expectAsync(rule.validate('1337')).toBe(true); expectations.validate(); }); it('should be passing the threshold around to the onValidate method', (done) => { var expectations = new Expectations(expect, done); var randomObject = {randomProperty: '1337'}; var rule = new CustomFunctionValidationRule((newValue, threshold) => { return newValue === threshold.randomProperty; }, randomObject); expectations.expectAsync(rule.validate('1336')).toBe(false); expectations.expectAsync(rule.validate('1337')).toBe(true); randomObject.randomProperty = '1336'; expectations.expectAsync(rule.validate('1336')).toBe(true); expectations.expectAsync(rule.validate('1337')).toBe(false); expectations.validate(); }); it('should be passing the threshold around to the message', (done) => { var expectations = new Expectations(expect, done); var randomObject = {randomProperty: '1337'}; var rule = new CustomFunctionValidationRule((newValue, threshold) => { return newValue === threshold.randomProperty; }, randomObject); rule.withMessage((newValue, threshold) => { return `Cool ${threshold.randomProperty}`; }); expectations.expectAsync(rule.validate('1336')).toBe(false); expectations.expectAsync( () => { return rule.explain();}).toBe('Cool 1337'); expectations.validate(); }); it('should succeed when the function returns true', (done) => { var expectations = new Expectations(expect, done); var rule = new CustomFunctionValidationRule((newValue, threshold) => { return true ; }); expectations.expectAsync(rule.validate('')).toBe(true); expectations.validate(); }); it('should succeed when the function returns null', (done) => { var expectations = new Expectations(expect, done); var rule = new CustomFunctionValidationRule((newValue, threshold) => { return null ; }); expectations.expectAsync(rule.validate('')).toBe(true); expectations.validate(); }); it('should succeed when the function returns undefined', (done) => { var expectations = new Expectations(expect, done); var rule = new CustomFunctionValidationRule((newValue, threshold) => { return undefined ; }); expectations.expectAsync(rule.validate('')).toBe(true); expectations.validate(); }); it('should succeed when the function returns an empty string', (done) => { var expectations = new Expectations(expect, done); var rule = new CustomFunctionValidationRule((newValue, threshold) => { return '' ; }); expectations.expectAsync(rule.validate('')).toBe(true); expectations.validate(); }); it('should fail when the function returns false', (done) => { var expectations = new Expectations(expect, done); var rule = new CustomFunctionValidationRule((newValue, threshold) => { return false ; }); expectations.expectAsync(rule.validate('')).toBe(false); expectations.validate(); }); it('should fail when the function returns a message', (done) => { var expectations = new Expectations(expect, done); var rule = new CustomFunctionValidationRule((newValue, threshold) => { return 'this is not good' ; }); expectations.expectAsync(rule.validate('')).toBe(false); expectations.assert( () => { expect(rule.explain()).toBe('this is not good'); return Promise.resolve(true); }, true); expectations.validate(); }); it('should succeed when the function returns a promise that resolves to true', (done) => { var expectations = new Expectations(expect, done); var rule = new CustomFunctionValidationRule((newValue, threshold) => { return Promise.resolve(true) ; }); expectations.expectAsync(rule.validate('')).toBe(true); expectations.validate(); }); it('should succeed when the function returns a promise that resolves to null', (done) => { var expectations = new Expectations(expect, done); var rule = new CustomFunctionValidationRule((newValue, threshold) => { return Promise.resolve(null) ; }); expectations.expectAsync(rule.validate('')).toBe(true); expectations.validate(); }); it('should succeed when the function returns a promise that resolves to undefined', (done) => { var expectations = new Expectations(expect, done); var rule = new CustomFunctionValidationRule((newValue, threshold) => { return Promise.resolve(undefined) ; }); expectations.expectAsync(rule.validate('')).toBe(true); expectations.validate(); }); it('should succeed when the function returns a promise that resolves to an empty string', (done) => { var expectations = new Expectations(expect, done); var rule = new CustomFunctionValidationRule((newValue, threshold) => { return Promise.resolve('') ; }); expectations.expectAsync(rule.validate('')).toBe(true); expectations.validate(); }); it('should fail when the function returns a promise that resolves to false', (done) => { var expectations = new Expectations(expect, done); var rule = new CustomFunctionValidationRule((newValue, threshold) => { return Promise.resolve(false) ; }); expectations.expectAsync(rule.validate('')).toBe(false); expectations.validate(); }); it('should fail when the function returns a promise that resolves to a message', (done) => { var expectations = new Expectations(expect, done); var rule = new CustomFunctionValidationRule((newValue, threshold) => { return Promise.resolve('this is not good') ; }); expectations.expectAsync(rule.validate('')).toBe(false); expectations.expectAsync( () => { return rule.explain();}).toBe('this is not good'); expectations.validate(); }); it('should fail when the function returns a promise that rejects', (done) => { var expectations = new Expectations(expect, done); var rule = new CustomFunctionValidationRule((newValue, threshold) => { return Promise.reject() ; }); expectations.expectAsync(rule.validate('')).toBe(false); expectations.validate(); }); it('should fail when the function returns a promise that rejects to a true', (done) => { var expectations = new Expectations(expect, done); var rule = new CustomFunctionValidationRule((newValue, threshold) => { return Promise.reject(true); }); expectations.expectAsync(rule.validate('')).toBe(false); expectations.validate(); }); it('should fail when the function returns a promise that rejects to a undefined', (done) => { var expectations = new Expectations(expect, done); var rule = new CustomFunctionValidationRule((newValue, threshold) => { return Promise.reject( undefined); }); expectations.expectAsync(rule.validate('')).toBe(false); expectations.validate(); }); it('should fail when the function returns a promise that rejects to a null', (done) => { var expectations = new Expectations(expect, done); var rule = new CustomFunctionValidationRule((newValue, threshold) => { return Promise.reject( null) ; }); expectations.expectAsync(rule.validate('')).toBe(false); expectations.validate(); }); it('should fail when the function returns a promise that rejects to a message', (done) => { var expectations = new Expectations(expect, done); var rule = new CustomFunctionValidationRule((newValue, threshold) => { return Promise.reject('this is not good') ; }); expectations.expectAsync(rule.validate('')).toBe(false); expectations.expectAsync( () => { return rule.explain(); }).toBe('this is not good'); expectations.validate(); }); });
import { FaReact, FaBootstrap, FaNodeJs } from 'react-icons/fa'; import { SiMongodb, SiWebpack, SiHandlebarsdotjs, SiMysql, SiExpress, } from 'react-icons/si'; const Technologies = [ { id: 1, name: 'React', icon: <FaReact />, }, { id: 2, name: 'MongoDB', icon: <SiMongodb />, }, { id: 3, name: 'Handlebars', icon: <SiHandlebarsdotjs />, }, { id: 4, name: 'Bootstrap', icon: <FaBootstrap />, }, { id: 5, name: 'MySQL', icon: <SiMysql />, }, { id: 6, name: 'NodeJS', icon: <FaNodeJs />, }, { id: 7, name: 'Webpack', icon: <SiWebpack />, }, { id: 8, name: 'Express', icon: <SiExpress />, }, ]; export default Technologies;
import React, { Component } from "react"; import axios from "axios"; const urls = require("../../../config/config.json"); class ResumeDropdown extends Component { // Adding default state as a placeholder constructor(props) { super(props); this.state = { toggled: false, edit: false }; } // fillState = () => { // if (this.props.context.userInfo.resumes.length !== 0) { // const temp = this.props.context.userInfo.resumes.filter(resume => { // return this.props.context.userInfo.currentresume === resume._id; // }); // if (temp.length > 0) return temp[0].content; // else return "Select a Resume"; // } else return "Select a Resume"; // }; // componentDidMount = () => { // this.setState({ selected: this.fillState() }); // } handleEdit = editToggle => { if (editToggle === "toggle") this.setState({ edit: !this.state.toggled }); else { const tempObj = this.props.context.userInfo.resumes[this.props.index]; tempObj.name = this.props.resumeName; axios .put( `${urls[urls.basePath]}/resume/` + this.props.context.userInfo.resumes[this.props.index]._id, tempObj, { headers: { Authorization: "Bearer " + localStorage.getItem("token") } } ) .then(response => { axios .put( `${urls[urls.basePath]}/users/info/${ this.props.context.userInfo.id }`, { currentresume: response.data.resume._id }, { headers: { Authorization: "Bearer " + localStorage.getItem("token") } } ) .then(response => { console.log("success"); this.setState({ edit: !this.state.edit }); // this.props.context.actions.setElement(this.state.index, "resumes", response.data.Resume); }) .catch(err => { console.log("err", err); }); }) .catch(err => { console.log("err", err); }); } }; // Toggles the drop down menu to appear based on the boolean value of state handleToggle = () => { this.setState({ toggled: !this.state.toggled }); }; // Allows us to select an li and set our state with the given value handleClick = (data, index) => { this.setState({ toggled: false }); // this updates template page index this.props.context.actions.setSingleElement("currentresume", data._id); // console.log("handleClick UpdateResumeIndex(newIndex: " + index + ")") this.props.updateResumeIndex(index); // this.props.updateResumeName(index); // console.log("resumedropdown newcurrentres", data._id); }; render() { const { toggled } = this.state; let selectedResume = null; const list = this.props.context.userInfo.resumes.map((data, index) => { console.log( "RENDERED so go thorugh", this.props.context.userInfo.resumes[index].name ); if (data._id === this.props.context.userInfo.currentresume) { selectedResume = data.name === "Untitled" ? "Untitled " + (index + 1) : data.name; } return ( <li className="list-group-item" key={data._id} onClick={() => this.handleClick(data, index)} style={{ cursor: "pointer" }} > {data.name === "Untitled" ? "Untitled " + (index + 1) : data.name} </li> ); }); return ( <div className="template-card card dropdown m-0"> <div className="container resume-name"> {this.state.edit ? ( <React.Fragment> <input id="resumeName" type="text" value={ this.props.resumeName !== null ? this.props.resumeName : "" } onChange={this.props.onInputChange} className="form-control edit-name" placeholder={selectedResume} onKeyDown={event => { if (event.key === "Enter") { event.target.blur(); event.preventDefault(); event.stopPropagation(); //!fix this.handleEdit(); } }} autoFocus /> <i onClick={() => this.handleEdit()} className="fa fa-check fa-lg" /> </React.Fragment> ) : ( <React.Fragment> <h4 style={{ marginRight: "1%" , fontWeight: "600", textShadow: "-1px -1px 1px white", color: "black"}}> {selectedResume} </h4> <i onClick={() => this.handleEdit("toggle")} className="fa fa-pencil fa-lg" /> </React.Fragment> )} </div> <h6 style={{ textTransform: "uppercase", fontWeight: "600" }}> Choose an option:{" "} <i // Dynamically assigns a classname based on the value of this.toggled className={ toggled ? "fa fa-angle-up fa-sm" : "fa fa-angle-down fa-sm" } style={{ cursor: "pointer" }} onClick={this.handleToggle} /> </h6> {toggled ? <ul className="list-group">{list}</ul> : null} </div> ); } } export default ResumeDropdown;
(function (angular) { "use strict"; angular.module("mfl.facility_mgmt.states.publish", [ "ui.router" ]) .config(["$stateProvider", function ($stateProvider) { $stateProvider .state("facilities_publish", { parent: "facility_mgmt", url: "^/facilities_publish/", views: { "main-content@facility_mgmt": { templateUrl: "facility_mgmt/tpls/facilities_grid.tpl.html", controller: "mfl.facility_mgmt.controllers.facilities_publish" } }, permission: "facilities.publish_facilities,facilities.view_facility" }) .state("facilities_publish.publish", { url: ":facility_id/", views: { "main-content@facility_mgmt": { templateUrl: "facility_mgmt/tpls/facility_publish.tpl.html", controller: "mfl.facility_mgmt.controllers.facility_publish" } }, permission: "facilities.publish_facilities,facilities.view_facility" }) .state("facilities_publish.publish.basic", { url: "basic/", views: { "form-view@facilities_publish.publish" : { templateUrl: "facility_mgmt/tpls/facility_approve.basic.tpl.html" } }, permission: "facilities.publish_facilities,facilities.view_facility" }) .state("facilities_publish.publish.services", { url: "services/", views: { "form-view@facilities_publish.publish" : { templateUrl: "facility_mgmt/tpls/facility_approve.services.tpl.html" } }, permission: "facilities.publish_facilities,facilities.view_facility" }) .state("facilities_publish.publish.units", { url: "units/", views: { "form-view@facilities_publish.publish" : { templateUrl: "facility_mgmt/tpls/facility_approve.units.tpl.html" } }, permission: "facilities.publish_facilities,facilities.view_facility" }); }]); })(window.angular);
import { compileToFunctions } from 'vue-template-compiler'; import mount from '../../../../src/mount'; import PropsComponent from '../../../resources/components/data-components/PropsComponent.vue'; import Watch from '../../../resources/components/watch/Watch.vue'; import DependantWatch from '../../../resources/components/watch/DependantWatch.vue'; describe('setProps', () => { it('sets component props and updates DOM when called on Vue instance', () => { const prop1 = 'prop 1'; const prop2 = 'prop 2'; const propsData = { prop1: 'a prop', prop2 }; const wrapper = mount(PropsComponent, { propsData }); wrapper.setProps({ prop1 }); expect(wrapper.find('.prop-1')[0].text()).to.equal(prop1); expect(wrapper.find('.prop-2')[0].text()).to.equal(prop2); }); it('sets component props, and updates DOM when propsData was not initially passed', () => { const prop1 = 'prop 1'; const prop2 = 'prop s'; const wrapper = mount(PropsComponent); wrapper.setProps({ prop1, prop2 }); expect(wrapper.find('.prop-1')[0].text()).to.equal(prop1); expect(wrapper.find('.prop-2')[0].text()).to.equal(prop2); }); it('runs watch function when updating a prop', () => { const wrapper = mount(Watch); const prop1 = 'testest'; wrapper.setProps({ prop1 }); expect(wrapper.vm.prop2).to.equal(prop1); }); it('updates all props before running watch', () => { const warn = sinon.stub(console, 'warn'); const wrapper = mount(DependantWatch); wrapper.setProps({ show: true, value: 'abc' }); expect(warn).to.have.been.calledWith('show watch : true,abc'); warn.restore(); }); it('throws an error if node is not a Vue instance', () => { const message = 'wrapper.setProps() can only be called on a Vue instance'; const compiled = compileToFunctions('<div><p></p></div>'); const wrapper = mount(compiled); const input = wrapper.find('p')[0]; expect(() => input.setProps({ ready: true })).throw(Error, message); }); });
from numpy import random # Este es una pésima implementación de k-means. Retorna centroides aleatorios. def kmeans(puntos,k): # Acá debería ir la lógica correcta de k-means centroides = random.randn(k,2) return centroides
""" Test Tool execution and state handling logic. """ from unittest import TestCase import galaxy.model from galaxy.tools.parameters import params_to_incoming from galaxy.util.bunch import Bunch from galaxy.util.odict import odict import tools_support from paste import httpexceptions BASE_REPEAT_TOOL_CONTENTS = '''<tool id="test_tool" name="Test Tool"> <command>echo "$param1" #for $r in $repeat# "$r.param2" #end for# &lt; $out1</command> <inputs> <param type="text" name="param1" value="" /> <repeat name="repeat1" label="Repeat 1"> %s </repeat> </inputs> <outputs> <data name="out1" format="data" /> </outputs> </tool> ''' # Tool with a repeat parameter, to test state update. REPEAT_TOOL_CONTENTS = BASE_REPEAT_TOOL_CONTENTS % '''<param type="text" name="param2" value="" />''' REPEAT_COLLECTION_PARAM_CONTENTS = BASE_REPEAT_TOOL_CONTENTS % '''<param type="data_collection" name="param2" collection_type="paired" />''' class ToolExecutionTestCase( TestCase, tools_support.UsesApp, tools_support.UsesTools ): def setUp(self): self.setup_app() self.history = galaxy.model.History() self.trans = MockTrans( self.app, self.history ) self.app.dataset_collections_service = MockCollectionService() self.tool_action = MockAction( self.trans ) def tearDown(self): self.tear_down_app() def test_state_new( self ): self._init_tool( tools_support.SIMPLE_TOOL_CONTENTS ) vars = self.__handle_with_incoming( param1="moo" ) state = self.__assert_rerenders_tool_without_errors( vars ) assert state[ "param1" ] == "moo" def test_execute( self ): self._init_tool( tools_support.SIMPLE_TOOL_CONTENTS ) vars = self.__handle_with_incoming( param1="moo" ) self.__assert_executed( vars ) # Didn't specify a rerun_remap_id so this should be None assert self.tool_action.execution_call_args[ 0 ][ "rerun_remap_job_id" ] is None def test_execute_exception( self ): self._init_tool( tools_support.SIMPLE_TOOL_CONTENTS ) self.tool_action.raise_exception( ) try: self.__handle_with_incoming( param1="moo" ) except Exception, e: assert 'Error executing tool' in str( e ) def test_execute_errors( self ): self._init_tool( tools_support.SIMPLE_TOOL_CONTENTS ) self.tool_action.return_error( ) try: self.__handle_with_incoming( param1="moo" ) except Exception, e: assert 'Test Error Message' in str( e ) def test_redirect( self ): self._init_tool( tools_support.SIMPLE_TOOL_CONTENTS ) self.tool_action.expect_redirect = True redirect_raised = False try: self.__handle_with_incoming( param1="moo" ) except httpexceptions.HTTPFound: redirect_raised = True assert redirect_raised def test_remap_job( self ): self._init_tool( tools_support.SIMPLE_TOOL_CONTENTS ) vars = self.__handle_with_incoming( param1="moo", rerun_remap_job_id=self.app.security.encode_id(123) ) self.__assert_executed( vars ) assert self.tool_action.execution_call_args[ 0 ][ "rerun_remap_job_id" ] == 123 def test_invalid_remap_job( self ): self._init_tool( tools_support.SIMPLE_TOOL_CONTENTS ) try: self.__handle_with_incoming( param1="moo", rerun_remap_job_id='123' ) except Exception, e: assert 'invalid job' in str( e ) def test_data_param_execute( self ): self._init_tool( tools_support.SIMPLE_CAT_TOOL_CONTENTS ) hda = self.__add_dataset( 1 ) # Execute tool action vars = self.__handle_with_incoming( param1=1 ) self.__assert_executed( vars ) # Tool 'executed' once, with hda as param1 assert len( self.tool_action.execution_call_args ) == 1 assert self.tool_action.execution_call_args[ 0 ][ "incoming" ][ "param1" ] == hda def test_data_param_state_update( self ): self._init_tool( tools_support.SIMPLE_CAT_TOOL_CONTENTS ) hda = self.__add_dataset( 1 ) # Update state vars = self.__handle_with_incoming( param1=1 ) state = self.__assert_rerenders_tool_without_errors( vars ) assert hda == state[ "param1" ] def __handle_with_incoming( self, previous_state=None, **kwds ): """ Execute tool.handle_input with incoming specified by kwds (optionally extending a previous state). """ if previous_state: incoming = self.__to_incoming( previous_state, **kwds) else: incoming = kwds return self.tool.handle_input( trans=self.trans, incoming=incoming ) def __to_incoming( self, state, **kwds ): new_incoming = {} params_to_incoming( new_incoming, self.tool.inputs, state.inputs, self.app ) new_incoming[ "tool_state" ] = self.__state_to_string( state ) new_incoming.update( kwds ) return new_incoming def __add_dataset( self, id, state='ok' ): hda = galaxy.model.HistoryDatasetAssociation() hda.id = id hda.dataset = galaxy.model.Dataset() hda.dataset.state = 'ok' self.trans.sa_session.model_objects[ galaxy.model.HistoryDatasetAssociation ][ id ] = hda self.history.datasets.append( hda ) return hda def __add_collection_dataset( self, id, collection_type="paired", *hdas ): hdca = galaxy.model.HistoryDatasetCollectionAssociation() hdca.id = id collection = galaxy.model.DatasetCollection() hdca.collection = collection collection.elements = [ galaxy.model.DatasetCollectionElement(element=self.__add_dataset( 1 )) ] collection.type = collection_type self.trans.sa_session.model_objects[ galaxy.model.HistoryDatasetCollectionAssociation ][ id ] = hdca self.history.dataset_collections.append( hdca ) return hdca def __assert_rerenders_tool_without_errors( self, vars ): self.__assert_no_errors( vars ) return self.tool_action.execution_call_args[ 0 ][ "incoming" ] def __assert_executed( self, vars ): self.__assert_no_errors( vars ) assert len( vars[ 'jobs' ] ) > 0 def __assert_no_errors( self, vars ): assert "job_errors" in vars assert not vars[ "job_errors" ] class MockAction( object ): def __init__( self, expected_trans ): self.expected_trans = expected_trans self.execution_call_args = [] self.expect_redirect = False self.exception_after_exection = None self.error_message_after_excution = None def execute( self, tool, trans, **kwds ): assert self.expected_trans == trans self.execution_call_args.append( kwds ) num_calls = len( self.execution_call_args ) if self.expect_redirect: raise httpexceptions.HTTPFound( "http://google.com" ) if self.exception_after_exection is not None: if num_calls > self.exception_after_exection: raise Exception( "Test Exception" ) if self.error_message_after_excution is not None: if num_calls > self.error_message_after_excution: return None, "Test Error Message" return galaxy.model.Job(), odict(dict(out1="1")) def raise_exception( self, after_execution=0 ): self.exception_after_exection = after_execution def return_error( self, after_execution=0 ): self.error_message_after_excution = after_execution class MockTrans( object ): def __init__( self, app, history ): self.app = app self.history = history self.user = None self.history._active_datasets_children_and_roles = filter( lambda hda: hda.active and hda.history == history, self.app.model.context.model_objects[ galaxy.model.HistoryDatasetAssociation ] ) self.workflow_building_mode = False self.webapp = Bunch( name="galaxy" ) self.sa_session = self.app.model.context def get_history( self, **kwargs ): return self.history def get_current_user_roles( self ): return [] class MockCollectionService( object ): def __init__( self ): self.collection_info = object() def match_collections( self, collections_to_match ): return self.collection_info
/****************************************************************************** * * This file is provided under a dual BSD/GPLv2 license. When using or * redistributing this file, you may do so under either license. * * GPL LICENSE SUMMARY * * Copyright(c) 2005 - 2009 Intel Corporation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110, * USA * * The full GNU General Public License is included in this distribution * in the file called LICENSE.GPL. * * Contact Information: * Intel Linux Wireless <ilw@linux.intel.com> * Intel Corporation, 5200 N.E. Elam Young Parkway, Hillsboro, OR 97124-6497 * * BSD LICENSE * * Copyright(c) 2005 - 2009 Intel Corporation. All rights reserved. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in * the documentation and/or other materials provided with the * distribution. * * Neither the name Intel Corporation nor the names of its * contributors may be used to endorse or promote products derived * from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * *****************************************************************************/ #ifndef __iwl_fh_h__ #define __iwl_fh_h__ /****************************/ /* Flow Handler Definitions */ /****************************/ /** * This I/O area is directly read/writable by driver (e.g. Linux uses writel()) * Addresses are offsets from device's PCI hardware base address. */ #define FH_MEM_LOWER_BOUND (0x1000) #define FH_MEM_UPPER_BOUND (0x2000) /** * Keep-Warm (KW) buffer base address. * * Driver must allocate a 4KByte buffer that is used by 4965 for keeping the * host DRAM powered on (via dummy accesses to DRAM) to maintain low-latency * DRAM access when 4965 is Txing or Rxing. The dummy accesses prevent host * from going into a power-savings mode that would cause higher DRAM latency, * and possible data over/under-runs, before all Tx/Rx is complete. * * Driver loads FH_KW_MEM_ADDR_REG with the physical address (bits 35:4) * of the buffer, which must be 4K aligned. Once this is set up, the 4965 * automatically invokes keep-warm accesses when normal accesses might not * be sufficient to maintain fast DRAM response. * * Bit fields: * 31-0: Keep-warm buffer physical base address [35:4], must be 4K aligned */ #define FH_KW_MEM_ADDR_REG (FH_MEM_LOWER_BOUND + 0x97C) /** * TFD Circular Buffers Base (CBBC) addresses * * 4965 has 16 base pointer registers, one for each of 16 host-DRAM-resident * circular buffers (CBs/queues) containing Transmit Frame Descriptors (TFDs) * (see struct iwl_tfd_frame). These 16 pointer registers are offset by 0x04 * bytes from one another. Each TFD circular buffer in DRAM must be 256-byte * aligned (address bits 0-7 must be 0). * * Bit fields in each pointer register: * 27-0: TFD CB physical base address [35:8], must be 256-byte aligned */ #define FH_MEM_CBBC_LOWER_BOUND (FH_MEM_LOWER_BOUND + 0x9D0) #define FH_MEM_CBBC_UPPER_BOUND (FH_MEM_LOWER_BOUND + 0xA10) /* Find TFD CB base pointer for given queue (range 0-15). */ #define FH_MEM_CBBC_QUEUE(x) (FH_MEM_CBBC_LOWER_BOUND + (x) * 0x4) /** * Rx SRAM Control and Status Registers (RSCSR) * * These registers provide handshake between driver and 4965 for the Rx queue * (this queue handles *all* command responses, notifications, Rx data, etc. * sent from 4965 uCode to host driver). Unlike Tx, there is only one Rx * queue, and only one Rx DMA/FIFO channel. Also unlike Tx, which can * concatenate up to 20 DRAM buffers to form a Tx frame, each Receive Buffer * Descriptor (RBD) points to only one Rx Buffer (RB); there is a 1:1 * mapping between RBDs and RBs. * * Driver must allocate host DRAM memory for the following, and set the * physical address of each into 4965 registers: * * 1) Receive Buffer Descriptor (RBD) circular buffer (CB), typically with 256 * entries (although any power of 2, up to 4096, is selectable by driver). * Each entry (1 dword) points to a receive buffer (RB) of consistent size * (typically 4K, although 8K or 16K are also selectable by driver). * Driver sets up RB size and number of RBDs in the CB via Rx config * register FH_MEM_RCSR_CHNL0_CONFIG_REG. * * Bit fields within one RBD: * 27-0: Receive Buffer physical address bits [35:8], 256-byte aligned * * Driver sets physical address [35:8] of base of RBD circular buffer * into FH_RSCSR_CHNL0_RBDCB_BASE_REG [27:0]. * * 2) Rx status buffer, 8 bytes, in which 4965 indicates which Rx Buffers * (RBs) have been filled, via a "write pointer", actually the index of * the RB's corresponding RBD within the circular buffer. Driver sets * physical address [35:4] into FH_RSCSR_CHNL0_STTS_WPTR_REG [31:0]. * * Bit fields in lower dword of Rx status buffer (upper dword not used * by driver; see struct iwl4965_shared, val0): * 31-12: Not used by driver * 11- 0: Index of last filled Rx buffer descriptor * (4965 writes, driver reads this value) * * As the driver prepares Receive Buffers (RBs) for 4965 to fill, driver must * enter pointers to these RBs into contiguous RBD circular buffer entries, * and update the 4965's "write" index register, * FH_RSCSR_CHNL0_RBDCB_WPTR_REG. * * This "write" index corresponds to the *next* RBD that the driver will make * available, i.e. one RBD past the tail of the ready-to-fill RBDs within * the circular buffer. This value should initially be 0 (before preparing any * RBs), should be 8 after preparing the first 8 RBs (for example), and must * wrap back to 0 at the end of the circular buffer (but don't wrap before * "read" index has advanced past 1! See below). * NOTE: 4965 EXPECTS THE WRITE INDEX TO BE INCREMENTED IN MULTIPLES OF 8. * * As the 4965 fills RBs (referenced from contiguous RBDs within the circular * buffer), it updates the Rx status buffer in host DRAM, 2) described above, * to tell the driver the index of the latest filled RBD. The driver must * read this "read" index from DRAM after receiving an Rx interrupt from 4965. * * The driver must also internally keep track of a third index, which is the * next RBD to process. When receiving an Rx interrupt, driver should process * all filled but unprocessed RBs up to, but not including, the RB * corresponding to the "read" index. For example, if "read" index becomes "1", * driver may process the RB pointed to by RBD 0. Depending on volume of * traffic, there may be many RBs to process. * * If read index == write index, 4965 thinks there is no room to put new data. * Due to this, the maximum number of filled RBs is 255, instead of 256. To * be safe, make sure that there is a gap of at least 2 RBDs between "write" * and "read" indexes; that is, make sure that there are no more than 254 * buffers waiting to be filled. */ #define FH_MEM_RSCSR_LOWER_BOUND (FH_MEM_LOWER_BOUND + 0xBC0) #define FH_MEM_RSCSR_UPPER_BOUND (FH_MEM_LOWER_BOUND + 0xC00) #define FH_MEM_RSCSR_CHNL0 (FH_MEM_RSCSR_LOWER_BOUND) /** * Physical base address of 8-byte Rx Status buffer. * Bit fields: * 31-0: Rx status buffer physical base address [35:4], must 16-byte aligned. */ #define FH_RSCSR_CHNL0_STTS_WPTR_REG (FH_MEM_RSCSR_CHNL0) /** * Physical base address of Rx Buffer Descriptor Circular Buffer. * Bit fields: * 27-0: RBD CD physical base address [35:8], must be 256-byte aligned. */ #define FH_RSCSR_CHNL0_RBDCB_BASE_REG (FH_MEM_RSCSR_CHNL0 + 0x004) /** * Rx write pointer (index, really!). * Bit fields: * 11-0: Index of driver's most recent prepared-to-be-filled RBD, + 1. * NOTE: For 256-entry circular buffer, use only bits [7:0]. */ #define FH_RSCSR_CHNL0_RBDCB_WPTR_REG (FH_MEM_RSCSR_CHNL0 + 0x008) #define FH_RSCSR_CHNL0_WPTR (FH_RSCSR_CHNL0_RBDCB_WPTR_REG) /** * Rx Config/Status Registers (RCSR) * Rx Config Reg for channel 0 (only channel used) * * Driver must initialize FH_MEM_RCSR_CHNL0_CONFIG_REG as follows for * normal operation (see bit fields). * * Clearing FH_MEM_RCSR_CHNL0_CONFIG_REG to 0 turns off Rx DMA. * Driver should poll FH_MEM_RSSR_RX_STATUS_REG for * FH_RSSR_CHNL0_RX_STATUS_CHNL_IDLE (bit 24) before continuing. * * Bit fields: * 31-30: Rx DMA channel enable: '00' off/pause, '01' pause at end of frame, * '10' operate normally * 29-24: reserved * 23-20: # RBDs in circular buffer = 2^value; use "8" for 256 RBDs (normal), * min "5" for 32 RBDs, max "12" for 4096 RBDs. * 19-18: reserved * 17-16: size of each receive buffer; '00' 4K (normal), '01' 8K, * '10' 12K, '11' 16K. * 15-14: reserved * 13-12: IRQ destination; '00' none, '01' host driver (normal operation) * 11- 4: timeout for closing Rx buffer and interrupting host (units 32 usec) * typical value 0x10 (about 1/2 msec) * 3- 0: reserved */ #define FH_MEM_RCSR_LOWER_BOUND (FH_MEM_LOWER_BOUND + 0xC00) #define FH_MEM_RCSR_UPPER_BOUND (FH_MEM_LOWER_BOUND + 0xCC0) #define FH_MEM_RCSR_CHNL0 (FH_MEM_RCSR_LOWER_BOUND) #define FH_MEM_RCSR_CHNL0_CONFIG_REG (FH_MEM_RCSR_CHNL0) #define FH_RCSR_CHNL0_RX_CONFIG_RB_TIMEOUT_MSK (0x00000FF0) /* bits 4-11 */ #define FH_RCSR_CHNL0_RX_CONFIG_IRQ_DEST_MSK (0x00001000) /* bits 12 */ #define FH_RCSR_CHNL0_RX_CONFIG_SINGLE_FRAME_MSK (0x00008000) /* bit 15 */ #define FH_RCSR_CHNL0_RX_CONFIG_RB_SIZE_MSK (0x00030000) /* bits 16-17 */ #define FH_RCSR_CHNL0_RX_CONFIG_RBDBC_SIZE_MSK (0x00F00000) /* bits 20-23 */ #define FH_RCSR_CHNL0_RX_CONFIG_DMA_CHNL_EN_MSK (0xC0000000) /* bits 30-31*/ #define FH_RCSR_RX_CONFIG_RBDCB_SIZE_POS (20) #define FH_RCSR_RX_CONFIG_REG_IRQ_RBTH_POS (4) #define RX_RB_TIMEOUT (0x10) #define FH_RCSR_RX_CONFIG_CHNL_EN_PAUSE_VAL (0x00000000) #define FH_RCSR_RX_CONFIG_CHNL_EN_PAUSE_EOF_VAL (0x40000000) #define FH_RCSR_RX_CONFIG_CHNL_EN_ENABLE_VAL (0x80000000) #define FH_RCSR_RX_CONFIG_REG_VAL_RB_SIZE_4K (0x00000000) #define FH_RCSR_RX_CONFIG_REG_VAL_RB_SIZE_8K (0x00010000) #define FH_RCSR_RX_CONFIG_REG_VAL_RB_SIZE_12K (0x00020000) #define FH_RCSR_RX_CONFIG_REG_VAL_RB_SIZE_16K (0x00030000) #define FH_RCSR_CHNL0_RX_IGNORE_RXF_EMPTY (0x00000004) #define FH_RCSR_CHNL0_RX_CONFIG_IRQ_DEST_NO_INT_VAL (0x00000000) #define FH_RCSR_CHNL0_RX_CONFIG_IRQ_DEST_INT_HOST_VAL (0x00001000) #define FH_RSCSR_FRAME_SIZE_MSK (0x00003FFF) /* bits 0-13 */ /** * Rx Shared Status Registers (RSSR) * * After stopping Rx DMA channel (writing 0 to * FH_MEM_RCSR_CHNL0_CONFIG_REG), driver must poll * FH_MEM_RSSR_RX_STATUS_REG until Rx channel is idle. * * Bit fields: * 24: 1 = Channel 0 is idle * * FH_MEM_RSSR_SHARED_CTRL_REG and FH_MEM_RSSR_RX_ENABLE_ERR_IRQ2DRV * contain default values that should not be altered by the driver. */ #define FH_MEM_RSSR_LOWER_BOUND (FH_MEM_LOWER_BOUND + 0xC40) #define FH_MEM_RSSR_UPPER_BOUND (FH_MEM_LOWER_BOUND + 0xD00) #define FH_MEM_RSSR_SHARED_CTRL_REG (FH_MEM_RSSR_LOWER_BOUND) #define FH_MEM_RSSR_RX_STATUS_REG (FH_MEM_RSSR_LOWER_BOUND + 0x004) #define FH_MEM_RSSR_RX_ENABLE_ERR_IRQ2DRV\ (FH_MEM_RSSR_LOWER_BOUND + 0x008) #define FH_RSSR_CHNL0_RX_STATUS_CHNL_IDLE (0x01000000) #define FH_MEM_TFDIB_REG1_ADDR_BITSHIFT 28 /* TFDB Area - TFDs buffer table */ #define FH_MEM_TFDIB_DRAM_ADDR_LSB_MSK (0xFFFFFFFF) #define FH_TFDIB_LOWER_BOUND (FH_MEM_LOWER_BOUND + 0x900) #define FH_TFDIB_UPPER_BOUND (FH_MEM_LOWER_BOUND + 0x958) #define FH_TFDIB_CTRL0_REG(_chnl) (FH_TFDIB_LOWER_BOUND + 0x8 * (_chnl)) #define FH_TFDIB_CTRL1_REG(_chnl) (FH_TFDIB_LOWER_BOUND + 0x8 * (_chnl) + 0x4) /** * Transmit DMA Channel Control/Status Registers (TCSR) * * 4965 has one configuration register for each of 8 Tx DMA/FIFO channels * supported in hardware (don't confuse these with the 16 Tx queues in DRAM, * which feed the DMA/FIFO channels); config regs are separated by 0x20 bytes. * * To use a Tx DMA channel, driver must initialize its * FH_TCSR_CHNL_TX_CONFIG_REG(chnl) with: * * FH_TCSR_TX_CONFIG_REG_VAL_DMA_CHNL_ENABLE | * FH_TCSR_TX_CONFIG_REG_VAL_DMA_CREDIT_ENABLE_VAL * * All other bits should be 0. * * Bit fields: * 31-30: Tx DMA channel enable: '00' off/pause, '01' pause at end of frame, * '10' operate normally * 29- 4: Reserved, set to "0" * 3: Enable internal DMA requests (1, normal operation), disable (0) * 2- 0: Reserved, set to "0" */ #define FH_TCSR_LOWER_BOUND (FH_MEM_LOWER_BOUND + 0xD00) #define FH_TCSR_UPPER_BOUND (FH_MEM_LOWER_BOUND + 0xE60) /* Find Control/Status reg for given Tx DMA/FIFO channel */ #define FH49_TCSR_CHNL_NUM (7) #define FH50_TCSR_CHNL_NUM (8) /* TCSR: tx_config register values */ #define FH_TCSR_CHNL_TX_CONFIG_REG(_chnl) \ (FH_TCSR_LOWER_BOUND + 0x20 * (_chnl)) #define FH_TCSR_CHNL_TX_CREDIT_REG(_chnl) \ (FH_TCSR_LOWER_BOUND + 0x20 * (_chnl) + 0x4) #define FH_TCSR_CHNL_TX_BUF_STS_REG(_chnl) \ (FH_TCSR_LOWER_BOUND + 0x20 * (_chnl) + 0x8) #define FH_TCSR_TX_CONFIG_REG_VAL_MSG_MODE_TXF (0x00000000) #define FH_TCSR_TX_CONFIG_REG_VAL_MSG_MODE_DRV (0x00000001) #define FH_TCSR_TX_CONFIG_REG_VAL_DMA_CREDIT_DISABLE (0x00000000) #define FH_TCSR_TX_CONFIG_REG_VAL_DMA_CREDIT_ENABLE (0x00000008) #define FH_TCSR_TX_CONFIG_REG_VAL_CIRQ_HOST_NOINT (0x00000000) #define FH_TCSR_TX_CONFIG_REG_VAL_CIRQ_HOST_ENDTFD (0x00100000) #define FH_TCSR_TX_CONFIG_REG_VAL_CIRQ_HOST_IFTFD (0x00200000) #define FH_TCSR_TX_CONFIG_REG_VAL_CIRQ_RTC_NOINT (0x00000000) #define FH_TCSR_TX_CONFIG_REG_VAL_CIRQ_RTC_ENDTFD (0x00400000) #define FH_TCSR_TX_CONFIG_REG_VAL_CIRQ_RTC_IFTFD (0x00800000) #define FH_TCSR_TX_CONFIG_REG_VAL_DMA_CHNL_PAUSE (0x00000000) #define FH_TCSR_TX_CONFIG_REG_VAL_DMA_CHNL_PAUSE_EOF (0x40000000) #define FH_TCSR_TX_CONFIG_REG_VAL_DMA_CHNL_ENABLE (0x80000000) #define FH_TCSR_CHNL_TX_BUF_STS_REG_VAL_TFDB_EMPTY (0x00000000) #define FH_TCSR_CHNL_TX_BUF_STS_REG_VAL_TFDB_WAIT (0x00002000) #define FH_TCSR_CHNL_TX_BUF_STS_REG_VAL_TFDB_VALID (0x00000003) #define FH_TCSR_CHNL_TX_BUF_STS_REG_POS_TB_NUM (20) #define FH_TCSR_CHNL_TX_BUF_STS_REG_POS_TB_IDX (12) /** * Tx Shared Status Registers (TSSR) * * After stopping Tx DMA channel (writing 0 to * FH_TCSR_CHNL_TX_CONFIG_REG(chnl)), driver must poll * FH_TSSR_TX_STATUS_REG until selected Tx channel is idle * (channel's buffers empty | no pending requests). * * Bit fields: * 31-24: 1 = Channel buffers empty (channel 7:0) * 23-16: 1 = No pending requests (channel 7:0) */ #define FH_TSSR_LOWER_BOUND (FH_MEM_LOWER_BOUND + 0xEA0) #define FH_TSSR_UPPER_BOUND (FH_MEM_LOWER_BOUND + 0xEC0) #define FH_TSSR_TX_STATUS_REG (FH_TSSR_LOWER_BOUND + 0x010) #define FH_TSSR_TX_STATUS_REG_BIT_BUFS_EMPTY(_chnl) ((1 << (_chnl)) << 24) #define FH_TSSR_TX_STATUS_REG_BIT_NO_PEND_REQ(_chnl) ((1 << (_chnl)) << 16) #define FH_TSSR_TX_STATUS_REG_MSK_CHNL_IDLE(_chnl) \ (FH_TSSR_TX_STATUS_REG_BIT_BUFS_EMPTY(_chnl) | \ FH_TSSR_TX_STATUS_REG_BIT_NO_PEND_REQ(_chnl)) /* Tx service channels */ #define FH_SRVC_CHNL (9) #define FH_SRVC_LOWER_BOUND (FH_MEM_LOWER_BOUND + 0x9C8) #define FH_SRVC_UPPER_BOUND (FH_MEM_LOWER_BOUND + 0x9D0) #define FH_SRVC_CHNL_SRAM_ADDR_REG(_chnl) \ (FH_SRVC_LOWER_BOUND + ((_chnl) - 9) * 0x4) #define FH_TX_CHICKEN_BITS_REG (FH_MEM_LOWER_BOUND + 0xE98) /* Instruct FH to increment the retry count of a packet when * it is brought from the memory to TX-FIFO */ #define FH_TX_CHICKEN_BITS_SCD_AUTO_RETRY_EN (0x00000002) #define RX_QUEUE_SIZE 256 #define RX_QUEUE_MASK 255 #define RX_QUEUE_SIZE_LOG 8 /* * RX related structures and functions */ #define RX_FREE_BUFFERS 64 #define RX_LOW_WATERMARK 8 /* Size of one Rx buffer in host DRAM */ #define IWL_RX_BUF_SIZE_3K (3 * 1000) /* 3945 only */ #define IWL_RX_BUF_SIZE_4K (4 * 1024) #define IWL_RX_BUF_SIZE_8K (8 * 1024) /** * struct iwl_rb_status - reseve buffer status * host memory mapped FH registers * @closed_rb_num [0:11] - Indicates the index of the RB which was closed * @closed_fr_num [0:11] - Indicates the index of the RX Frame which was closed * @finished_rb_num [0:11] - Indicates the index of the current RB * in which the last frame was written to * @finished_fr_num [0:11] - Indicates the index of the RX Frame * which was transfered */ struct iwl_rb_status { __le16 closed_rb_num; __le16 closed_fr_num; __le16 finished_rb_num; __le16 finished_fr_nam; __le32 __unused; /* 3945 only */ } __attribute__ ((packed)); #define TFD_QUEUE_SIZE_MAX (256) #define TFD_QUEUE_SIZE_BC_DUP (64) #define TFD_QUEUE_BC_SIZE (TFD_QUEUE_SIZE_MAX + TFD_QUEUE_SIZE_BC_DUP) #define IWL_TX_DMA_MASK DMA_BIT_MASK(36) #define IWL_NUM_OF_TBS 20 static inline u8 iwl_get_dma_hi_addr(dma_addr_t addr) { return (sizeof(addr) > sizeof(u32) ? (addr >> 16) >> 16 : 0) & 0xF; } /** * struct iwl_tfd_tb transmit buffer descriptor within transmit frame descriptor * * This structure contains dma address and length of transmission address * * @lo: low [31:0] portion of the dma address of TX buffer * every even is unaligned on 16 bit boundary * @hi_n_len 0-3 [35:32] portion of dma * 4-15 length of the tx buffer */ struct iwl_tfd_tb { __le32 lo; __le16 hi_n_len; } __attribute__((packed)); /** * struct iwl_tfd * * Transmit Frame Descriptor (TFD) * * @ __reserved1[3] reserved * @ num_tbs 0-4 number of active tbs * 5 reserved * 6-7 padding (not used) * @ tbs[20] transmit frame buffer descriptors * @ __pad padding * * Each Tx queue uses a circular buffer of 256 TFDs stored in host DRAM. * Both driver and device share these circular buffers, each of which must be * contiguous 256 TFDs x 128 bytes-per-TFD = 32 KBytes * * Driver must indicate the physical address of the base of each * circular buffer via the FH_MEM_CBBC_QUEUE registers. * * Each TFD contains pointer/size information for up to 20 data buffers * in host DRAM. These buffers collectively contain the (one) frame described * by the TFD. Each buffer must be a single contiguous block of memory within * itself, but buffers may be scattered in host DRAM. Each buffer has max size * of (4K - 4). The concatenates all of a TFD's buffers into a single * Tx frame, up to 8 KBytes in size. * * A maximum of 255 (not 256!) TFDs may be on a queue waiting for Tx. */ struct iwl_tfd { u8 __reserved1[3]; u8 num_tbs; struct iwl_tfd_tb tbs[IWL_NUM_OF_TBS]; __le32 __pad; } __attribute__ ((packed)); /* Keep Warm Size */ #define IWL_KW_SIZE 0x1000 /* 4k */ #endif /* !__iwl_fh_h__ */
"use strict"; // Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT license. // See LICENSE in the project root for license information.s Object.defineProperty(exports, "__esModule", { value: true }); const _isStatic = Symbol('ApiStaticMixin._isStatic'); /** * Mixin function for {@link (ApiStaticMixin:interface)}. * * @param baseClass - The base class to be extended * @returns A child class that extends baseClass, adding the {@link (ApiStaticMixin:interface)} functionality. * * @public */ function ApiStaticMixin(baseClass) { class MixedClass extends baseClass { // tslint:disable-next-line:no-any constructor(...args) { super(...args); const options = args[0]; this[_isStatic] = options.isStatic; } /** @override */ static onDeserializeInto(options, context, jsonObject) { baseClass.onDeserializeInto(options, context, jsonObject); options.isStatic = jsonObject.isStatic; } get isStatic() { return this[_isStatic]; } /** @override */ serializeInto(jsonObject) { super.serializeInto(jsonObject); jsonObject.isStatic = this.isStatic; } } return MixedClass; } exports.ApiStaticMixin = ApiStaticMixin; /** * Static members for {@link (ApiStaticMixin:interface)}. * @public */ (function (ApiStaticMixin) { /** * A type guard that tests whether the specified `ApiItem` subclass extends the `ApiStaticMixin` mixin. * * @remarks * * The JavaScript `instanceof` operator cannot be used to test for mixin inheritance, because each invocation of * the mixin function produces a different subclass. (This could be mitigated by `Symbol.hasInstance`, however * the TypeScript type system cannot invoke a runtime test.) */ function isBaseClassOf(apiItem) { return apiItem.hasOwnProperty(_isStatic); } ApiStaticMixin.isBaseClassOf = isBaseClassOf; })(ApiStaticMixin = exports.ApiStaticMixin || (exports.ApiStaticMixin = {})); //# sourceMappingURL=ApiStaticMixin.js.map
#pragma once #include "Module.h" #include "Globals.h" #define MAX_MOUSE_BUTTONS 5 #define MAX_KEYS 300 enum EventWindow { WE_QUIT = 0, WE_HIDE = 1, WE_SHOW = 2, WE_COUNT }; enum KEY_STATE { KEY_IDLE = 0, KEY_DOWN, KEY_REPEAT, KEY_UP, KEY_ERROR }; class Input : public Module { public: Input(App* app, bool start_enabled = true); ~Input(); bool Init(); update_status PreUpdate(); bool CleanUp(); KEY_STATE GetKey(uint id) const { return (id < MAX_KEYS) ? keyboard[id] : KEY_ERROR; } KEY_STATE GetMouseButton(uint id) const { return (id < MAX_MOUSE_BUTTONS) ? mouse_buttons[id] : KEY_ERROR; } int GetMouseX() const { return mouse_x; } int GetMouseY() const { return mouse_y; } private: bool windowEvents[WE_COUNT]; KEY_STATE* keyboard; KEY_STATE mouse_buttons[MAX_MOUSE_BUTTONS]; int mouse_x; int mouse_y; };
""" Given an array, count triplets, that will form a geometric progression """ """ Some GP fundae: The nth term in GP is: a(n) = a * (r ** (n-1)) a(n) = r * (a(n-1)) r (common-ratio) = """ from collections import Counter, defaultdict """ # Initial approach - that results in a TLE def countTriplets(arr, r): ctr = Counter(arr) arr = sorted(set(arr)) total = 0 for i in range(len(arr)): b = r * arr[i] c = r * r * arr[i] if b in arr and c in arr: total += ctr[arr[i]] * ctr[b] * ctr[c] return total """ def count_triplets_that_form_gp(arr, r): v2 = defaultdict(int) # v3 is tracking how many end with a specific number v3 = defaultdict(int) total = 0 for k in arr: total += v3[k] # Increment the number of triplets that end with k v3[k * r] += v2[k] v2[k * r] += 1 print(f"The total is: {total}") print(f"The v2 map is: {v2}") print(f"The v3 map is: {v3}") print("***********************") return total if __name__ == "__main__": length, common_ratio = list(map(int, input().split())) arr = list(map(int, input().split())) result = count_triplets_that_form_gp(arr, common_ratio) print("The result is:", result)
import React, { Component } from "react"; import Button from "@material-ui/core/Button"; import Dialog from "@material-ui/core/Dialog"; import DialogActions from "@material-ui/core/DialogActions"; import DialogContent from "@material-ui/core/DialogContent"; import DialogContentText from "@material-ui/core/DialogContentText"; import DialogTitle from "@material-ui/core/DialogTitle"; import Grid from "@material-ui/core/Grid"; import ButtonGood from "../../UI/Button/ButtonGood/ButtonGood"; import ButtonBad from "../../UI/Button/ButtonBad/ButtonBad"; import TitleLabel from "../../UI/Label/TitleLabel"; import Fab from "@material-ui/core/Fab"; import AddIcon from "@material-ui/icons/AddPhotoAlternate"; import DeleteIcon from "@material-ui/icons/Delete"; import { FormControlLabel, Checkbox } from "@material-ui/core"; import Modal from "../../UI/Modal/Modal"; import PhotoUpload from "../../Forms/PhotoUpload/PhotoUpload"; import TextAreaInput from "../../UI/Input/TextArea/TextArea"; import TextInput from "../../UI/Input/TextInput/TextInput"; import NumberInput from "../../UI/Input/NumberInput/NumberInput"; import IMG from "../../UI/LightBox/ImageLightBox"; import Select from "react-select"; import { connect } from "react-redux"; import * as actions from "../../../redux/actions/index"; import styleClass from "./ProductPage.module.css"; import { MDBBtn } from "mdbreact"; class ProductPage extends Component { state = { dialogOpen: false, showAddFotoModal: false, product: { price: "", name: "", latinName: "", description: "", type: "SINGLE", tags: "", available: false, wikiEntry: { wikiEntryId: null } } }; componentWillMount() { this.props.onProductFetch(); this.props.onWikiEntryFetch(); let product = null; for (let i = 0; i < this.props.products.products.length; i++) { if ( this.props.products.products[i].productId == this.props.match.params.id ) { product = this.props.products.products[i]; } } if (product !== null) { this.setState({ product }); } } refreshHandler = () => { let product = null; for (let i = 0; i < this.props.products.products.length; i++) { if ( this.props.products.products[i].productId == this.props.match.params.id ) { product = this.props.products.products[i]; } } if (product !== null) { this.setState({ product }); } }; deleteButtonHandler = () => { this.setState({ dialogOpen: true }); }; addPictureButtonHandler = () => { this.setState({ showAddFotoModal: true }); }; closePhotoAddModal = () => { this.setState({ showAddFotoModal: false }); }; onModifyButtonClicked = () => { this.props.onProductUpdate(this.state.product); this.props.history.replace("/product"); }; onTextInputHandler = (event, inputIdentifier) => { const newState = { ...this.state }; if (inputIdentifier === "name") { newState.product.name = event.target.value; this.setState(newState); } else if (inputIdentifier === "latinName") { newState.product.latinName = event.target.value; this.setState(newState); } else if (inputIdentifier === "description") { newState.product.description = event.target.value; this.setState(newState); } else if (inputIdentifier === "tags") { newState.product.tags = event.target.value; this.setState(newState); } else if (inputIdentifier === "price") { newState.product.price = event.target.value; this.setState(newState); } else if (inputIdentifier === "type") { newState.product.type = event.target.value; this.setState(newState); } else if (inputIdentifier === "wikiId") { if (newState.product.wikiEntry === null) { newState.product.wikiEntry = { wikiEntryId: null }; } newState.product.wikiEntry.wikiEntryId = event.target.value; this.setState(newState); } else if (inputIdentifier === "available") { newState.product.available = !this.state.product.available; this.setState(newState); } }; onWikiSelectHandler = option => { this.setState({ ...this.state, product: { ...this.state.product, wikiEntry: { wikiEntryId: option.value } } }); }; handleDialogClose = () => { this.setState({ dialogOpen: false }); }; handleDialogConfirm = () => { this.setState({ dialogOpen: false }); this.props.onProductDelete(this.props.match.params.id); this.props.history.replace("/product"); }; render() { console.log(this.state); const buttonAddStyle = { margin: 0, top: "auto", right: 20, bottom: 20, left: "auto", position: "fixed", zIndex: 1000 }; const buttonDeleteStyle = { margin: 0, top: "auto", right: 80, bottom: 20, left: "auto", position: "fixed", zIndex: 1000 }; let product = null; let photos = null; for (let i = 0; i < this.props.products.products.length; i++) { if ( this.props.products.products[i].productId == this.props.match.params.id ) { product = this.props.products.products[i]; } } if (product !== null) { if (product.photos !== null) { photos = product.photos.map((photo, index) => { return ( <Grid item key={index} xs={12} xl={6} lg={4}> <IMG photo={photo}></IMG> </Grid> ); }); } let options = [{ label: "NONE", value: null }]; let selectedOption = options[0]; const wikiEntryOptions = this.props.wiki.wikiEntries.map( (wikiEntry, index) => { const option = { label: wikiEntry.wikiEntryId + ": " + wikiEntry.name + "-" + wikiEntry.latinName, value: wikiEntry.wikiEntryId }; options.push(option); if ( this.state.product.wikiEntry !== null && this.state.product.wikiEntry.wikiEntryId !== null && this.state.product.wikiEntry.wikiEntryId === wikiEntry.wikiEntryId ) { console.log(option); selectedOption = option; } return ( <option key={wikiEntry.wikiEntryId} value={wikiEntry.wikiEntryId}> {wikiEntry.wikiEntryId}: {wikiEntry.name}-{wikiEntry.latinName} </option> ); } ); return ( <div className={styleClass.All}> <Dialog open={this.state.dialogOpen} onClose={this.handleDialogClose} aria-labelledby="alert-dialog-title" aria-describedby="alert-dialog-description" > <DialogTitle id="alert-dialog-title"> {"Are you sure you want to delete this wiki entry?"} </DialogTitle> <DialogContent></DialogContent> <DialogActions> <Button onClick={this.handleDialogConfirm} color="primary"> Yes </Button> <Button onClick={this.handleDialogClose} color="primary" autoFocus > No </Button> </DialogActions> </Dialog> <Modal show={this.state.showAddFotoModal} modalClosed={this.closePhotoAddModal} > <PhotoUpload history={this.props.history} productId={this.props.match.params.id} isWikiEntry={false} ></PhotoUpload> </Modal> <Fab color="primary" aria-label="add" style={buttonAddStyle} onClick={this.addPictureButtonHandler} > <AddIcon></AddIcon> </Fab> <Fab color="secondary" aria-label="add" style={buttonDeleteStyle} onClick={this.deleteButtonHandler} > <DeleteIcon /> </Fab> <TitleLabel name="Product Page"></TitleLabel> <Grid container justify="center" alignItems="center" spacing={1}> <Grid container spacing={1} justify="center" alignItems="center"> <Grid item xs={12} md={9} lg={9}> <TextInput name={"Name:"} value={this.state.product.name} onChangeAction={event => this.onTextInputHandler(event, "name") } ></TextInput> </Grid> <Grid item xs={12} md={9} lg={9}> <TextInput name={"Latin name:"} value={this.state.product.latinName} onChangeAction={event => this.onTextInputHandler(event, "latinName") } ></TextInput> </Grid> <Grid item xs={12} md={9} lg={9}> <TextAreaInput name={"Description:"} value={this.state.product.description} onChangeAction={event => this.onTextInputHandler(event, "description") } rows={5} ></TextAreaInput> </Grid> <Grid item xs={12} md={6} lg={6}> <TextInput name={"Tags:"} value={this.state.product.tags} onChangeAction={event => this.onTextInputHandler(event, "tags") } rows={1} ></TextInput> </Grid> <Grid item xs={11} md={3} lg={3}> <FormControlLabel onClick={event => this.onTextInputHandler(event, "available")} control={ <Checkbox value={this.state.product.available} checked={this.state.product.available} /> } label="Is available" /> </Grid> <Grid item xs={12} md={9} lg={9}> <NumberInput name={"Price:"} value={this.state.product.price} onChangeAction={event => this.onTextInputHandler(event, "price") } rows={1} ></NumberInput> </Grid> <Grid item xs={11} md={8} lg={8}> <label>Type:</label> <select value={this.state.product.type} onChange={event => this.onTextInputHandler(event, "type")} > <option value="SINGLE">SINGLE</option> <option value="BOUQUET">BOUQUET</option> <option value="OTHER">OTHER</option> </select> </Grid> <Grid item xs={12} md={6}> <Select value={selectedOption} placeholder={"WikiEntry:"} options={options} onChange={option => this.onWikiSelectHandler(option)} ></Select> </Grid> </Grid> <Grid item xs={12} sm={6} md={6} lg={6}> <div className={styleClass.Button}> <ButtonGood name={"Modify"} onClickAction={event => this.onModifyButtonClicked()} ></ButtonGood> </div> </Grid> <Grid item xs={12} sm={6} md={6} lg={6}> <div className={styleClass.Button}> <MDBBtn onClick={this.refreshHandler}>Refresh</MDBBtn> </div> </Grid> {photos} </Grid> </div> ); } return ( <div> productPage <h2>{this.props.match.params.id}</h2> </div> ); } } const mapStateToProps = state => { return { wiki: state.wiki, products: state.products }; }; const mapDispatchToProps = dispatch => { return { onWikiEntryFetch: () => dispatch(actions.fetchWikiEntries()), onProductFetch: () => dispatch(actions.fetchProducts()), onProductDelete: productId => dispatch(actions.deleteProduct(productId)), onProductUpdate: product => dispatch(actions.updateProduct(product)) }; }; export default connect(mapStateToProps, mapDispatchToProps)(ProductPage);
/* * This file contains the handling of command * responses as well as events generated by firmware. */ #include <linux/hardirq.h> #include <linux/slab.h> #include <linux/delay.h> #include <linux/sched.h> #include <asm/unaligned.h> #include <net/cfg80211.h> #include "cfg.h" #include "cmd.h" /** * lbs_mac_event_disconnected - handles disconnect event. It * reports disconnect to upper layer, clean tx/rx packets, * reset link state etc. * * @priv: A pointer to struct lbs_private structure * * returns: n/a */ void lbs_mac_event_disconnected(struct lbs_private *priv) { if (priv->connect_status != LBS_CONNECTED) return; lbs_deb_enter(LBS_DEB_ASSOC); /* * Cisco AP sends EAP failure and de-auth in less than 0.5 ms. * It causes problem in the Supplicant */ msleep_interruptible(1000); if (priv->wdev->iftype == NL80211_IFTYPE_STATION) lbs_send_disconnect_notification(priv); /* report disconnect to upper layer */ netif_stop_queue(priv->dev); netif_carrier_off(priv->dev); /* Free Tx and Rx packets */ kfree_skb(priv->currenttxskb); priv->currenttxskb = NULL; priv->tx_pending_len = 0; priv->connect_status = LBS_DISCONNECTED; if (priv->psstate != PS_STATE_FULL_POWER) { /* make firmware to exit PS mode */ lbs_deb_cmd("disconnected, so exit PS mode\n"); lbs_set_ps_mode(priv, PS_MODE_ACTION_EXIT_PS, false); } lbs_deb_leave(LBS_DEB_ASSOC); } int lbs_process_command_response(struct lbs_private *priv, u8 *data, u32 len) { uint16_t respcmd, curcmd; struct cmd_header *resp; int ret = 0; unsigned long flags; uint16_t result; lbs_deb_enter(LBS_DEB_HOST); mutex_lock(&priv->lock); spin_lock_irqsave(&priv->driver_lock, flags); if (!priv->cur_cmd) { lbs_deb_host("CMD_RESP: cur_cmd is NULL\n"); ret = -1; spin_unlock_irqrestore(&priv->driver_lock, flags); goto done; } resp = (void *)data; curcmd = le16_to_cpu(priv->cur_cmd->cmdbuf->command); respcmd = le16_to_cpu(resp->command); result = le16_to_cpu(resp->result); lbs_deb_cmd("CMD_RESP: response 0x%04x, seq %d, size %d\n", respcmd, le16_to_cpu(resp->seqnum), len); lbs_deb_hex(LBS_DEB_CMD, "CMD_RESP", (void *) resp, len); if (resp->seqnum != priv->cur_cmd->cmdbuf->seqnum) { netdev_info(priv->dev, "Received CMD_RESP with invalid sequence %d (expected %d)\n", le16_to_cpu(resp->seqnum), le16_to_cpu(priv->cur_cmd->cmdbuf->seqnum)); spin_unlock_irqrestore(&priv->driver_lock, flags); ret = -1; goto done; } if (respcmd != CMD_RET(curcmd) && respcmd != CMD_RET_802_11_ASSOCIATE && curcmd != CMD_802_11_ASSOCIATE) { netdev_info(priv->dev, "Invalid CMD_RESP %x to command %x!\n", respcmd, curcmd); spin_unlock_irqrestore(&priv->driver_lock, flags); ret = -1; goto done; } if (resp->result == cpu_to_le16(0x0004)) { /* 0x0004 means -EAGAIN. Drop the response, let it time out and be resubmitted */ netdev_info(priv->dev, "Firmware returns DEFER to command %x. Will let it time out...\n", le16_to_cpu(resp->command)); spin_unlock_irqrestore(&priv->driver_lock, flags); ret = -1; goto done; } /* Now we got response from FW, cancel the command timer */ del_timer(&priv->command_timer); priv->cmd_timed_out = 0; if (respcmd == CMD_RET(CMD_802_11_PS_MODE)) { struct cmd_ds_802_11_ps_mode *psmode = (void *) &resp[1]; u16 action = le16_to_cpu(psmode->action); lbs_deb_host( "CMD_RESP: PS_MODE cmd reply result 0x%x, action 0x%x\n", result, action); if (result) { lbs_deb_host("CMD_RESP: PS command failed with 0x%x\n", result); /* * We should not re-try enter-ps command in * ad-hoc mode. It takes place in * lbs_execute_next_command(). */ if (priv->wdev->iftype == NL80211_IFTYPE_MONITOR && action == PS_MODE_ACTION_ENTER_PS) priv->psmode = LBS802_11POWERMODECAM; } else if (action == PS_MODE_ACTION_ENTER_PS) { priv->needtowakeup = 0; priv->psstate = PS_STATE_AWAKE; lbs_deb_host("CMD_RESP: ENTER_PS command response\n"); if (priv->connect_status != LBS_CONNECTED) { /* * When Deauth Event received before Enter_PS command * response, We need to wake up the firmware. */ lbs_deb_host( "disconnected, invoking lbs_ps_wakeup\n"); spin_unlock_irqrestore(&priv->driver_lock, flags); mutex_unlock(&priv->lock); lbs_set_ps_mode(priv, PS_MODE_ACTION_EXIT_PS, false); mutex_lock(&priv->lock); spin_lock_irqsave(&priv->driver_lock, flags); } } else if (action == PS_MODE_ACTION_EXIT_PS) { priv->needtowakeup = 0; priv->psstate = PS_STATE_FULL_POWER; lbs_deb_host("CMD_RESP: EXIT_PS command response\n"); } else { lbs_deb_host("CMD_RESP: PS action 0x%X\n", action); } __lbs_complete_command(priv, priv->cur_cmd, result); spin_unlock_irqrestore(&priv->driver_lock, flags); ret = 0; goto done; } /* If the command is not successful, cleanup and return failure */ if ((result != 0 || !(respcmd & 0x8000))) { lbs_deb_host("CMD_RESP: error 0x%04x in command reply 0x%04x\n", result, respcmd); /* * Handling errors here */ switch (respcmd) { case CMD_RET(CMD_GET_HW_SPEC): case CMD_RET(CMD_802_11_RESET): lbs_deb_host("CMD_RESP: reset failed\n"); break; } __lbs_complete_command(priv, priv->cur_cmd, result); spin_unlock_irqrestore(&priv->driver_lock, flags); ret = -1; goto done; } spin_unlock_irqrestore(&priv->driver_lock, flags); if (priv->cur_cmd && priv->cur_cmd->callback) { ret = priv->cur_cmd->callback(priv, priv->cur_cmd->callback_arg, resp); } spin_lock_irqsave(&priv->driver_lock, flags); if (priv->cur_cmd) { /* Clean up and Put current command back to cmdfreeq */ __lbs_complete_command(priv, priv->cur_cmd, result); } spin_unlock_irqrestore(&priv->driver_lock, flags); done: mutex_unlock(&priv->lock); lbs_deb_leave_args(LBS_DEB_HOST, "ret %d", ret); return ret; } int lbs_process_event(struct lbs_private *priv, u32 event) { int ret = 0; struct cmd_header cmd; lbs_deb_enter(LBS_DEB_CMD); switch (event) { case MACREG_INT_CODE_LINK_SENSED: lbs_deb_cmd("EVENT: link sensed\n"); break; case MACREG_INT_CODE_DEAUTHENTICATED: lbs_deb_cmd("EVENT: deauthenticated\n"); lbs_mac_event_disconnected(priv); break; case MACREG_INT_CODE_DISASSOCIATED: lbs_deb_cmd("EVENT: disassociated\n"); lbs_mac_event_disconnected(priv); break; case MACREG_INT_CODE_LINK_LOST_NO_SCAN: lbs_deb_cmd("EVENT: link lost\n"); lbs_mac_event_disconnected(priv); break; case MACREG_INT_CODE_PS_SLEEP: lbs_deb_cmd("EVENT: ps sleep\n"); /* handle unexpected PS SLEEP event */ if (priv->psstate == PS_STATE_FULL_POWER) { lbs_deb_cmd( "EVENT: in FULL POWER mode, ignoring PS_SLEEP\n"); break; } priv->psstate = PS_STATE_PRE_SLEEP; lbs_ps_confirm_sleep(priv); break; case MACREG_INT_CODE_HOST_AWAKE: lbs_deb_cmd("EVENT: host awake\n"); if (priv->reset_deep_sleep_wakeup) priv->reset_deep_sleep_wakeup(priv); priv->is_deep_sleep = 0; lbs_cmd_async(priv, CMD_802_11_WAKEUP_CONFIRM, &cmd, sizeof(cmd)); priv->is_host_sleep_activated = 0; wake_up_interruptible(&priv->host_sleep_q); break; case MACREG_INT_CODE_DEEP_SLEEP_AWAKE: if (priv->reset_deep_sleep_wakeup) priv->reset_deep_sleep_wakeup(priv); lbs_deb_cmd("EVENT: ds awake\n"); priv->is_deep_sleep = 0; priv->wakeup_dev_required = 0; wake_up_interruptible(&priv->ds_awake_q); break; case MACREG_INT_CODE_PS_AWAKE: lbs_deb_cmd("EVENT: ps awake\n"); /* handle unexpected PS AWAKE event */ if (priv->psstate == PS_STATE_FULL_POWER) { lbs_deb_cmd( "EVENT: In FULL POWER mode - ignore PS AWAKE\n"); break; } priv->psstate = PS_STATE_AWAKE; if (priv->needtowakeup) { /* * wait for the command processing to finish * before resuming sending * priv->needtowakeup will be set to FALSE * in lbs_ps_wakeup() */ lbs_deb_cmd("waking up ...\n"); lbs_set_ps_mode(priv, PS_MODE_ACTION_EXIT_PS, false); } break; case MACREG_INT_CODE_MIC_ERR_UNICAST: lbs_deb_cmd("EVENT: UNICAST MIC ERROR\n"); lbs_send_mic_failureevent(priv, event); break; case MACREG_INT_CODE_MIC_ERR_MULTICAST: lbs_deb_cmd("EVENT: MULTICAST MIC ERROR\n"); lbs_send_mic_failureevent(priv, event); break; case MACREG_INT_CODE_MIB_CHANGED: lbs_deb_cmd("EVENT: MIB CHANGED\n"); break; case MACREG_INT_CODE_INIT_DONE: lbs_deb_cmd("EVENT: INIT DONE\n"); break; case MACREG_INT_CODE_ADHOC_BCN_LOST: lbs_deb_cmd("EVENT: ADHOC beacon lost\n"); break; case MACREG_INT_CODE_RSSI_LOW: netdev_alert(priv->dev, "EVENT: rssi low\n"); break; case MACREG_INT_CODE_SNR_LOW: netdev_alert(priv->dev, "EVENT: snr low\n"); break; case MACREG_INT_CODE_MAX_FAIL: netdev_alert(priv->dev, "EVENT: max fail\n"); break; case MACREG_INT_CODE_RSSI_HIGH: netdev_alert(priv->dev, "EVENT: rssi high\n"); break; case MACREG_INT_CODE_SNR_HIGH: netdev_alert(priv->dev, "EVENT: snr high\n"); break; case MACREG_INT_CODE_MESH_AUTO_STARTED: /* Ignore spurious autostart events */ netdev_info(priv->dev, "EVENT: MESH_AUTO_STARTED (ignoring)\n"); break; default: netdev_alert(priv->dev, "EVENT: unknown event id %d\n", event); break; } lbs_deb_leave_args(LBS_DEB_CMD, "ret %d", ret); return ret; }
var __create = Object.create; var __defProp = Object.defineProperty; var __getOwnPropDesc = Object.getOwnPropertyDescriptor; var __getOwnPropNames = Object.getOwnPropertyNames; var __getProtoOf = Object.getPrototypeOf; var __hasOwnProp = Object.prototype.hasOwnProperty; var __markAsModule = (target) => __defProp(target, "__esModule", { value: true }); var __export = (target, all) => { for (var name in all) __defProp(target, name, { get: all[name], enumerable: true }); }; var __reExport = (target, module3, copyDefault, desc) => { if (module3 && typeof module3 === "object" || typeof module3 === "function") { for (let key of __getOwnPropNames(module3)) if (!__hasOwnProp.call(target, key) && (copyDefault || key !== "default")) __defProp(target, key, { get: () => module3[key], enumerable: !(desc = __getOwnPropDesc(module3, key)) || desc.enumerable }); } return target; }; var __toESM = (module3, isNodeMode) => { return __reExport(__markAsModule(__defProp(module3 != null ? __create(__getProtoOf(module3)) : {}, "default", !isNodeMode && module3 && module3.__esModule ? { get: () => module3.default, enumerable: true } : { value: module3, enumerable: true })), module3); }; var __toCommonJS = /* @__PURE__ */ ((cache) => { return (module3, temp) => { return cache && cache.get(module3) || (temp = __reExport(__markAsModule({}), module3, 1), cache && cache.set(module3, temp), temp); }; })(typeof WeakMap !== "undefined" ? /* @__PURE__ */ new WeakMap() : 0); var stdin_exports = {}; __export(stdin_exports, { css: () => css, entry: () => entry, js: () => js, module: () => module2 }); var module2 = __toESM(require("../entries/pages/admin/__layout.reset.svelte.js")); const entry = "pages/admin/__layout.reset.svelte-592f345b.js"; const js = ["pages/admin/__layout.reset.svelte-592f345b.js", "chunks/vendor-c6b1e087.js"]; const css = []; module.exports = __toCommonJS(stdin_exports);
/* * Backpack - Skyscanner's Design System * * Copyright 2018 Skyscanner Ltd * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import PropTypes from 'prop-types'; import React from 'react'; import SideNavLayout from './../SideNavLayout'; import links from './../links'; const DocsLayout = ({ children, ...rest }) => ( <SideNavLayout activeSection="COMPONENTS" links={links} {...rest}> {children} </SideNavLayout> ); DocsLayout.propTypes = { children: PropTypes.oneOfType([ PropTypes.arrayOf(PropTypes.node), PropTypes.node, ]).isRequired, }; export default DocsLayout;
from naya.json import parse, parse_string, stream_array __all__ = ["parse", "parse_string", "stream_array"]
import PropTypes from 'prop-types' import React from 'react' class PlayToken extends React.PureComponent { static propTypes = { recording_id: PropTypes.number, text: PropTypes.string } static defaultProps = { text: 't(Play recording)' } _handlePlay = this._handlePlay.bind(this) render() { const { text } = this.props return ( <div className="voice-campaign-play-token"> <div className="voice-campaign-play-token-inner" onClick={ this._handlePlay }> <i className="fa fa-play-circle" /> <span className="link"> { text } </span> </div> </div> ) } _handlePlay(e) { e.stopPropagation() const { recording_id } = this.props const audio = new Audio(`/phone/voice/phone/recordings/${recording_id}`) audio.play() } } export default PlayToken
import React, { Component } from 'react'; class Mern extends Component { render () { } }
/* * module.c * * Created on: Jan 1, 2017 * Author: Dad */ #ifdef NEW_MODULE #include <stdbool.h> #include <stdint.h> #include <stdio.h> #include "../arena/strings.h" #include "../codegen/tokenizer.h" #include "../datastructure/map.h" #include "../datastructure/queue.h" #include "../error.h" #include "../memory/memory.h" #include "../shared.h" #include "instruction.h" #include "module.h" #include "tape.h" #define DEFAULT_PROGRAM_SIZE 256 struct Module_ { FILE *file; const char *fn; FileInfo *fi; Tape *tape; }; Module *module_create(FileInfo *fi) { Module *m = ALLOC2(Module); m->file = NULL; m->fi = fi; m->fn = NULL; m->tape = NULL; return m; } Module *module_create_tape(FileInfo *fi, Tape *tape) { Module *m = module_create(fi); m->tape = tape; return m; } void module_set_filename(Module *m, const char fn[]) { ASSERT(NOT_NULL(m), NOT_NULL(fn)); m->fn = strings_intern(fn); if (NULL != m->fi) { file_info_set_name(m->fi, fn); } } const char *module_filename(const Module const *m) { ASSERT_NOT_NULL(m); if (NULL == m->fn && NULL != m->fi) { return file_info_name(m->fi); } return m->fn; } FileInfo *module_fileinfo(const Module const *m) { return m->fi; } DEB_FN(const char *, module_name, const Module const *m) { ASSERT(NOT_NULL(m)); if (NULL == m->tape) { return "?"; } return tape_modulename(m->tape); } Ins module_ins(const Module *m, uint32_t index) { ASSERT(NOT_NULL(m), tape_len(m->tape) > index); return module_insc(m, index)->ins; } const InsContainer *module_insc(const Module *m, uint32_t index) { ASSERT(NOT_NULL(m), tape_len(m->tape) > index); return tape_get(m->tape, (int)index); } int32_t module_ref(const Module *m, const char ref_name[]) { ASSERT(NOT_NULL(m), NOT_NULL(ref_name)); void *ptr = map_lookup(module_refs(m), ref_name); if (NULL == ptr) { return -1; } return (int32_t)(uint32_t)ptr; } const Map *module_refs(const Module *m) { ASSERT(NOT_NULL(m)); return tape_refs(m->tape); } const Map *module_fn_args(const Module *m) { ASSERT(NOT_NULL(m)); return &m->tape->fn_args; } void module_iterate_classes(const Module *m, ClassAction action) { ASSERT(NOT_NULL(m)); Set processed; set_init_default(&processed); // For each class void process_class(Pair * kv) { const char *class_name = (char *)kv->key; const Map *methods = (Map *)kv->value; // Check if already processed. if (set_lookup(&processed, methods)) { return; } // Check if the parents have been processed processed. void maybe_process_parent(void *ptr) { const char *parent_class_name = *((char **)ptr); Map *parent_methods = map_lookup(module_classes(m), parent_class_name); // If parent not processed, process it. if (NULL == parent_methods || set_lookup(&processed, parent_methods)) { return; } Pair kv2; kv2.key = parent_class_name; kv2.value = parent_methods; process_class(&kv2); } Expando *class_parents = map_lookup(module_class_parents(m), class_name); if (NULL != class_parents) { expando_iterate(class_parents, maybe_process_parent); } // Process class action((char *)kv->key, (const Map *)kv->value); set_insert(&processed, kv->value); } map_iterate(module_classes(m), process_class); set_finalize(&processed); } const Map *module_classes(const Module *m) { ASSERT(NOT_NULL(m)); return tape_classes(m->tape); } const Map *module_class_parents(const Module *m) { ASSERT(NOT_NULL(m)); return tape_class_parents(m->tape); } uint32_t module_size(const Module *m) { ASSERT(NOT_NULL(m)); return tape_len(m->tape); } const Tape *module_tape(const Module *m) { return m->tape; } void module_set_tape(Module *m, Tape *tape) { m->tape = tape; } void module_delete(Module *m) { ASSERT_NOT_NULL(m); // Delete file and assert no more tokens if (NULL != m->fi) { file_info_delete(m->fi); } if (NULL != m->tape) { tape_delete(m->tape); } DEALLOC(m); } #endif
# Copyright (c) 2020 Foundries.io # SPDX-License-Identifier: Apache-2.0 import logging import os from tempfile import NamedTemporaryFile from expandvars import expandvars from apps.compose_apps import ComposeApps from apps.docker_registry_client import DockerRegistryClient from helpers import cmd as cmd_exe logger = logging.getLogger(__name__) class AppsPublisher: def __init__(self, factory, publish_tool: str, archs: str, registry_host=DockerRegistryClient.DefaultRegistryHost): self._factory = factory self._publish_tool = publish_tool self._archs = archs self._registry_host = registry_host self._image_base_url = '{}/{}'.format(registry_host, self._factory) self._allowed_tags = ['${TAG}', 'latest'] if factory == 'lmp': # the lmp containers repo pulls in fiotest which sets # its tag to "postmerge" which is okay based on how # we do tagging for that repo. self._allowed_tags.append('postmerge') def publish(self, apps: ComposeApps, version: str): self.tag(apps, version) logger.info('Publishing Apps...') published_apps = {} [published_apps.update({app.name: {'uri': self.__publish(app, version)}}) for app in apps] return published_apps def tag(self, apps: ComposeApps, version: str): # TODO: Consider implementation of the "publish tool" in DockerRegistryClient # in this case we won't need the tagging step/changing image URIs in docker-compose.yml of each app logger.info('Tagging Apps...') [self.__tag(app, version) for app in apps] def __tag(self, app: ComposeApps.App, tag: str): changed = False for service_name, service_cfg in app.services(): image_url_template = service_cfg.get('image') if not image_url_template: raise Exception('Mandatory element `image:` is missing in the app service config; app: {}, service: {}' .format(app.name, service_name)) image_url = expandvars(image_url_template) logger.info('Service image url: %s', image_url) if not image_url.startswith(self._registry_host) or \ (self._factory != 'lmp' and image_url.startswith(self._registry_host + "/lmp/")): # image url points to non-Foundries docker registry or to Foundries public Factory (aka lmp) continue if not image_url.startswith(self._image_base_url): raise Exception('Image url refers to an image that does not belong to the given Factory;' ' url: {}, factory: {}'.format(image_url, self._factory)) parts = image_url.split(':') if len(parts) == 1: logger.info('Image {} pinned to `latest`, updating to {}'.format(image_url, tag)) service_cfg['image'] = image_url + ':' + tag changed = True elif len(parts) == 2: if not (parts[1] in self._allowed_tags or parts[1] == tag): raise Exception('Image {} pinned to {}, can be {}'.format(image_url, parts[1], self._allowed_tags)) logger.info('Image {} pinned to {}, updating to {}'.format(image_url, parts[1], tag)) service_cfg['image'] = parts[0] + ':' + tag changed = True else: raise Exception('Unexpected image value: ' + image_url) if changed: app.save() def __publish(self, app: ComposeApps.App, tag: str): app_base_url = self._image_base_url + '/' + app.name self._app_tagged_url = app_base_url + ':app-' + tag # TODO: Consider implementation of the "publish tool" in DockerRegistryClient with NamedTemporaryFile(mode="w+") as f: cmd_exe(self._publish_tool, '-d', f.name, self._app_tagged_url, self._archs, cwd=app.dir) return app_base_url + '@' + f.read().strip()
specific action log: gotoDay # #Stop script if user is process of picking a specific action group. If [ $$pick = 1 ] Show Custom Dialog [ Message: "Pick a specific-action tag or click the cancel button in the Tag window. After you do this you can go to the Day window."; Buttons: “OK” ] Exit Script [ ] End If # Select Window [ Name: "Day"; Current file ] December 6, ଘ౮27 22:00:06 ActionLog.fp7 - gotoDay -1-
#pragma once #include "c_types.h" void c_log_level(c_log_level_t level); void c_log(c_log_level_t level, const char *message); void c_logn(c_log_level_t level, const char *message);
(window.webpackJsonp=window.webpackJsonp||[]).push([[11],{263:function(t,r,e){"use strict";e(158)("fixed",function(t){return function(){return t(this,"tt","","")}})},320:function(t,r,e){"use strict";e(263),e(9),e(6),e(2),e(21);var n=e(1),i=e.n(n),o=e(19),a=e.n(o),c=e(84),s=e.n(c),u=e(0),l=e.n(u),h=(e(11),e(83)),f=e(235),p=e(242),d=l.a.forwardRef(function(t,r){var e=t.classes,n=t.className,o=t.component,c=void 0===o?"div":o,s=t.fixed,u=void 0!==s&&s,f=t.maxWidth,d=void 0===f?"lg":f,m=a()(t,["classes","className","component","fixed","maxWidth"]);return l.a.createElement(c,i()({className:Object(h.a)(e.root,n,u&&e.fixed,!1!==d&&e["maxWidth".concat(Object(p.a)(String(d)))]),ref:r},m))});r.a=Object(f.a)(function(t){var r;return{root:(r={width:"100%",marginLeft:"auto",boxSizing:"border-box",marginRight:"auto",paddingLeft:t.spacing(2),paddingRight:t.spacing(2)},s()(r,t.breakpoints.up("sm"),{paddingLeft:t.spacing(3),paddingRight:t.spacing(3)}),s()(r,t.breakpoints.up("md"),{paddingLeft:t.spacing(4),paddingRight:t.spacing(4)}),r),fixed:Object.keys(t.breakpoints.values).reduce(function(r,e){var n=t.breakpoints.values[e];return 0!==n&&(r[t.breakpoints.up(e)]={maxWidth:n}),r},{}),maxWidthXs:s()({},t.breakpoints.up("xs"),{maxWidth:Math.max(t.breakpoints.values.xs,444)}),maxWidthSm:s()({},t.breakpoints.up("sm"),{maxWidth:t.breakpoints.values.sm}),maxWidthMd:s()({},t.breakpoints.up("md"),{maxWidth:t.breakpoints.values.md}),maxWidthLg:s()({},t.breakpoints.up("lg"),{maxWidth:t.breakpoints.values.lg}),maxWidthXl:s()({},t.breakpoints.up("xl"),{maxWidth:t.breakpoints.values.xl})}},{name:"MuiContainer"})(d)},321:function(t,r,e){e(9),e(6),e(26),e(52),e(2),e(159),e(16),e(35),e(25);var n=function(t){"use strict";var r,e=Object.prototype,n=e.hasOwnProperty,i="function"==typeof Symbol?Symbol:{},o=i.iterator||"@@iterator",a=i.asyncIterator||"@@asyncIterator",c=i.toStringTag||"@@toStringTag";function s(t,r,e,n){var i=r&&r.prototype instanceof m?r:m,o=Object.create(i.prototype),a=new N(n||[]);return o._invoke=function(t,r,e){var n=l;return function(i,o){if(n===f)throw new Error("Generator is already running");if(n===p){if("throw"===i)throw o;return W()}for(e.method=i,e.arg=o;;){var a=e.delegate;if(a){var c=E(a,e);if(c){if(c===d)continue;return c}}if("next"===e.method)e.sent=e._sent=e.arg;else if("throw"===e.method){if(n===l)throw n=p,e.arg;e.dispatchException(e.arg)}else"return"===e.method&&e.abrupt("return",e.arg);n=f;var s=u(t,r,e);if("normal"===s.type){if(n=e.done?p:h,s.arg===d)continue;return{value:s.arg,done:e.done}}"throw"===s.type&&(n=p,e.method="throw",e.arg=s.arg)}}}(t,e,a),o}function u(t,r,e){try{return{type:"normal",arg:t.call(r,e)}}catch(n){return{type:"throw",arg:n}}}t.wrap=s;var l="suspendedStart",h="suspendedYield",f="executing",p="completed",d={};function m(){}function v(){}function g(){}var y={};y[o]=function(){return this};var x=Object.getPrototypeOf,w=x&&x(x(S([])));w&&w!==e&&n.call(w,o)&&(y=w);var b=g.prototype=m.prototype=Object.create(y);function k(t){["next","throw","return"].forEach(function(r){t[r]=function(t){return this._invoke(r,t)}})}function L(t){var r;this._invoke=function(e,i){function o(){return new Promise(function(r,o){!function r(e,i,o,a){var c=u(t[e],t,i);if("throw"!==c.type){var s=c.arg,l=s.value;return l&&"object"==typeof l&&n.call(l,"__await")?Promise.resolve(l.__await).then(function(t){r("next",t,o,a)},function(t){r("throw",t,o,a)}):Promise.resolve(l).then(function(t){s.value=t,o(s)},function(t){return r("throw",t,o,a)})}a(c.arg)}(e,i,r,o)})}return r=r?r.then(o,o):o()}}function E(t,e){var n=t.iterator[e.method];if(n===r){if(e.delegate=null,"throw"===e.method){if(t.iterator.return&&(e.method="return",e.arg=r,E(t,e),"throw"===e.method))return d;e.method="throw",e.arg=new TypeError("The iterator does not provide a 'throw' method")}return d}var i=u(n,t.iterator,e.arg);if("throw"===i.type)return e.method="throw",e.arg=i.arg,e.delegate=null,d;var o=i.arg;return o?o.done?(e[t.resultName]=o.value,e.next=t.nextLoc,"return"!==e.method&&(e.method="next",e.arg=r),e.delegate=null,d):o:(e.method="throw",e.arg=new TypeError("iterator result is not an object"),e.delegate=null,d)}function O(t){var r={tryLoc:t[0]};1 in t&&(r.catchLoc=t[1]),2 in t&&(r.finallyLoc=t[2],r.afterLoc=t[3]),this.tryEntries.push(r)}function j(t){var r=t.completion||{};r.type="normal",delete r.arg,t.completion=r}function N(t){this.tryEntries=[{tryLoc:"root"}],t.forEach(O,this),this.reset(!0)}function S(t){if(t){var e=t[o];if(e)return e.call(t);if("function"==typeof t.next)return t;if(!isNaN(t.length)){var i=-1,a=function e(){for(;++i<t.length;)if(n.call(t,i))return e.value=t[i],e.done=!1,e;return e.value=r,e.done=!0,e};return a.next=a}}return{next:W}}function W(){return{value:r,done:!0}}return v.prototype=b.constructor=g,g.constructor=v,g[c]=v.displayName="GeneratorFunction",t.isGeneratorFunction=function(t){var r="function"==typeof t&&t.constructor;return!!r&&(r===v||"GeneratorFunction"===(r.displayName||r.name))},t.mark=function(t){return Object.setPrototypeOf?Object.setPrototypeOf(t,g):(t.__proto__=g,c in t||(t[c]="GeneratorFunction")),t.prototype=Object.create(b),t},t.awrap=function(t){return{__await:t}},k(L.prototype),L.prototype[a]=function(){return this},t.AsyncIterator=L,t.async=function(r,e,n,i){var o=new L(s(r,e,n,i));return t.isGeneratorFunction(e)?o:o.next().then(function(t){return t.done?t.value:o.next()})},k(b),b[c]="Generator",b[o]=function(){return this},b.toString=function(){return"[object Generator]"},t.keys=function(t){var r=[];for(var e in t)r.push(e);return r.reverse(),function e(){for(;r.length;){var n=r.pop();if(n in t)return e.value=n,e.done=!1,e}return e.done=!0,e}},t.values=S,N.prototype={constructor:N,reset:function(t){if(this.prev=0,this.next=0,this.sent=this._sent=r,this.done=!1,this.delegate=null,this.method="next",this.arg=r,this.tryEntries.forEach(j),!t)for(var e in this)"t"===e.charAt(0)&&n.call(this,e)&&!isNaN(+e.slice(1))&&(this[e]=r)},stop:function(){this.done=!0;var t=this.tryEntries[0].completion;if("throw"===t.type)throw t.arg;return this.rval},dispatchException:function(t){if(this.done)throw t;var e=this;function i(n,i){return c.type="throw",c.arg=t,e.next=n,i&&(e.method="next",e.arg=r),!!i}for(var o=this.tryEntries.length-1;o>=0;--o){var a=this.tryEntries[o],c=a.completion;if("root"===a.tryLoc)return i("end");if(a.tryLoc<=this.prev){var s=n.call(a,"catchLoc"),u=n.call(a,"finallyLoc");if(s&&u){if(this.prev<a.catchLoc)return i(a.catchLoc,!0);if(this.prev<a.finallyLoc)return i(a.finallyLoc)}else if(s){if(this.prev<a.catchLoc)return i(a.catchLoc,!0)}else{if(!u)throw new Error("try statement without catch or finally");if(this.prev<a.finallyLoc)return i(a.finallyLoc)}}}},abrupt:function(t,r){for(var e=this.tryEntries.length-1;e>=0;--e){var i=this.tryEntries[e];if(i.tryLoc<=this.prev&&n.call(i,"finallyLoc")&&this.prev<i.finallyLoc){var o=i;break}}o&&("break"===t||"continue"===t)&&o.tryLoc<=r&&r<=o.finallyLoc&&(o=null);var a=o?o.completion:{};return a.type=t,a.arg=r,o?(this.method="next",this.next=o.finallyLoc,d):this.complete(a)},complete:function(t,r){if("throw"===t.type)throw t.arg;return"break"===t.type||"continue"===t.type?this.next=t.arg:"return"===t.type?(this.rval=this.arg=t.arg,this.method="return",this.next="end"):"normal"===t.type&&r&&(this.next=r),d},finish:function(t){for(var r=this.tryEntries.length-1;r>=0;--r){var e=this.tryEntries[r];if(e.finallyLoc===t)return this.complete(e.completion,e.afterLoc),j(e),d}},catch:function(t){for(var r=this.tryEntries.length-1;r>=0;--r){var e=this.tryEntries[r];if(e.tryLoc===t){var n=e.completion;if("throw"===n.type){var i=n.arg;j(e)}return i}}throw new Error("illegal catch attempt")},delegateYield:function(t,e,n){return this.delegate={iterator:S(t),resultName:e,nextLoc:n},"next"===this.method&&(this.arg=r),d}},t}(t.exports);try{regeneratorRuntime=n}catch(i){Function("r","regeneratorRuntime = r")(n)}},449:function(t,r,e){t.exports=e(321)},464:function(t,r,e){"use strict";var n=e(1),i=e.n(n),o=e(19),a=e.n(o),c=e(0),s=e.n(c),u=(e(11),e(83)),l=e(235),h=e(242);function f(t){var r,e,n;return r=t,e=0,n=1,t=(Math.min(Math.max(e,r),n)-e)/(n-e),t=(t-=1)*t*t+1}var p=s.a.forwardRef(function(t,r){var e,n=t.classes,o=t.className,c=t.color,l=void 0===c?"primary":c,p=t.disableShrink,d=void 0!==p&&p,m=t.size,v=void 0===m?40:m,g=t.style,y=t.thickness,x=void 0===y?3.6:y,w=t.value,b=void 0===w?0:w,k=t.variant,L=void 0===k?"indeterminate":k,E=a()(t,["classes","className","color","disableShrink","size","style","thickness","value","variant"]),O={},j={},N={};if("determinate"===L||"static"===L){var S=2*Math.PI*((44-x)/2);O.strokeDasharray=S.toFixed(3),N["aria-valuenow"]=Math.round(b),"static"===L?(O.strokeDashoffset="".concat(((100-b)/100*S).toFixed(3),"px"),j.transform="rotate(-90deg)"):(O.strokeDashoffset="".concat((e=(100-b)/100,e*e*S).toFixed(3),"px"),j.transform="rotate(".concat((270*f(b/70)).toFixed(3),"deg)"))}return s.a.createElement("div",i()({className:Object(u.a)(n.root,o,"inherit"!==l&&n["color".concat(Object(h.a)(l))],"indeterminate"===L&&n.indeterminate,"static"===L&&n.static),style:i()({width:v,height:v},j,g),ref:r,role:"progressbar"},N,E),s.a.createElement("svg",{className:n.svg,viewBox:"".concat(22," ").concat(22," ").concat(44," ").concat(44)},s.a.createElement("circle",{className:Object(u.a)(n.circle,"indeterminate"===L&&n.circleIndeterminate,"static"===L&&n.circleStatic,d&&n.circleDisableShrink),style:O,cx:44,cy:44,r:(44-x)/2,fill:"none",strokeWidth:x})))});r.a=Object(l.a)(function(t){return{root:{display:"inline-block",lineHeight:1},static:{transition:t.transitions.create("transform")},indeterminate:{animation:"mui-progress-circular-rotate 1.4s linear infinite",animationName:"$mui-progress-circular-rotate"},colorPrimary:{color:t.palette.primary.main},colorSecondary:{color:t.palette.secondary.main},svg:{},circle:{stroke:"currentColor"},circleStatic:{transition:t.transitions.create("stroke-dashoffset")},circleIndeterminate:{animation:"mui-progress-circular-dash 1.4s ease-in-out infinite",animationName:"$mui-progress-circular-dash",strokeDasharray:"80px, 200px",strokeDashoffset:"0px"},"@keyframes mui-progress-circular-rotate":{"100%":{transform:"rotate(360deg)"}},"@keyframes mui-progress-circular-dash":{"0%":{strokeDasharray:"1px, 200px",strokeDashoffset:"0px"},"50%":{strokeDasharray:"100px, 200px",strokeDashoffset:"-15px"},"100%":{strokeDasharray:"100px, 200px",strokeDashoffset:"-125px"}},circleDisableShrink:{animation:"none"}}},{name:"MuiCircularProgress",flip:!1})(p)}}]); //# sourceMappingURL=11-f8b7dd725dcf01249701.js.map
#!/usr/bin/python # -*- coding: utf-8 -*- # Copyright: (c) 2020, Nikolay Dachev <nikolay@dachev.info> # GNU General Public License v3.0+ https://www.gnu.org/licenses/gpl-3.0.txt from __future__ import (absolute_import, division, print_function) __metaclass__ = type DOCUMENTATION = ''' --- module: api author: "Nikolay Dachev (@NikolayDachev)" short_description: Ansible module for RouterOS API description: - Ansible module for RouterOS API with python librouteros. - This module can add, remove, update, query and execute arbitrary command in routeros via API. notes: - I(add), I(remove), I(update), I(cmd) and I(query) are mutually exclusive. - I(check_mode) is not supported. requirements: - librouteros - Python >= 3.6 (for librouteros) options: hostname: description: - RouterOS hostname API. required: true type: str username: description: - RouterOS login user. required: true type: str password: description: - RouterOS user password. required: true type: str ssl: description: - If is set TLS will be used for RouterOS API connection. required: false type: bool default: false port: description: - RouterOS api port. If ssl is set, port will apply to ssl connection. - Defaults are C(8728) for the HTTP API, and C(8729) for the HTTPS API. type: int path: description: - Main path for all other arguments. - If other arguments are not set, api will return all items in selected path. - Example C(ip address). Equivalent of RouterOS CLI C(/ip address print). required: true type: str add: description: - Will add selected arguments in selected path to RouterOS config. - Example C(address=1.1.1.1/32 interface=ether1). - Equivalent in RouterOS CLI C(/ip address add address=1.1.1.1/32 interface=ether1). type: str remove: description: - Remove config/value from RouterOS by '.id'. - Example C(*03) will remove config/value with C(id=*03) in selected path. - Equivalent in RouterOS CLI C(/ip address remove numbers=1). - Note C(number) in RouterOS CLI is different from C(.id). type: str update: description: - Update config/value in RouterOS by '.id' in selected path. - Example C(.id=*03 address=1.1.1.3/32) and path C(ip address) will replace existing ip address with C(.id=*03). - Equivalent in RouterOS CLI C(/ip address set address=1.1.1.3/32 numbers=1). - Note C(number) in RouterOS CLI is different from C(.id). type: str query: description: - Query given path for selected query attributes from RouterOS aip and return '.id'. - WHERE is key word which extend query. WHERE format is key operator value - with spaces. - WHERE valid operators are C(==), C(!=), C(>), C(<). - Example path C(ip address) and query C(.id address) will return only C(.id) and C(address) for all items in C(ip address) path. - Example path C(ip address) and query C(.id address WHERE address == 1.1.1.3/32). will return only C(.id) and C(address) for items in C(ip address) path, where address is eq to 1.1.1.3/32. - Example path C(interface) and query C(mtu name WHERE mut > 1400) will return only interfaces C(mtu,name) where mtu is bigger than 1400. - Equivalent in RouterOS CLI C(/interface print where mtu > 1400). type: str cmd: description: - Execute any/arbitrary command in selected path, after the command we can add C(.id). - Example path C(system script) and cmd C(run .id=*03) is equivalent in RouterOS CLI C(/system script run number=0). - Example path C(ip address) and cmd C(print) is equivalent in RouterOS CLI C(/ip address print). type: str ''' EXAMPLES = ''' --- - name: Use RouterOS API hosts: localhost gather_facts: no vars: hostname: "ros_api_hostname/ip" username: "admin" password: "secret_password" path: "ip address" nic: "ether2" ip1: "1.1.1.1/32" ip2: "2.2.2.2/32" ip3: "3.3.3.3/32" tasks: - name: Get "{{ path }} print" community.routeros.api: hostname: "{{ hostname }}" password: "{{ password }}" username: "{{ username }}" path: "{{ path }}" register: print_path - name: Dump "{{ path }} print" output ansible.builtin.debug: msg: '{{ print_path }}' - name: Add ip address "{{ ip1 }}" and "{{ ip2 }}" community.routeros.api: hostname: "{{ hostname }}" password: "{{ password }}" username: "{{ username }}" path: "{{ path }}" add: "{{ item }}" loop: - "address={{ ip1 }} interface={{ nic }}" - "address={{ ip2 }} interface={{ nic }}" register: addout - name: Dump "Add ip address" output - ".id" for new added items ansible.builtin.debug: msg: '{{ addout }}' - name: Query for ".id" in "{{ path }} WHERE address == {{ ip2 }}" community.routeros.api: hostname: "{{ hostname }}" password: "{{ password }}" username: "{{ username }}" path: "{{ path }}" query: ".id address WHERE address == {{ ip2 }}" register: queryout - name: Dump "Query for" output and set fact with ".id" for "{{ ip2 }}" ansible.builtin.debug: msg: '{{ queryout }}' - name: Store query_id for later usage ansible.builtin.set_fact: query_id: "{{ queryout['msg'][0]['.id'] }}" - name: Update ".id = {{ query_id }}" taken with custom fact "fquery_id" community.routeros.api: hostname: "{{ hostname }}" password: "{{ password }}" username: "{{ username }}" path: "{{ path }}" update: ".id={{ query_id }} address={{ ip3 }}" register: updateout - name: Dump "Update" output ansible.builtin.debug: msg: '{{ updateout }}' - name: Remove ips - stage 1 - query ".id" for "{{ ip2 }}" and "{{ ip3 }}" community.routeros.api: hostname: "{{ hostname }}" password: "{{ password }}" username: "{{ username }}" path: "{{ path }}" query: ".id address WHERE address == {{ item }}" register: id_to_remove loop: - "{{ ip2 }}" - "{{ ip3 }}" - name: Set fact for ".id" from "Remove ips - stage 1 - query" ansible.builtin.set_fact: to_be_remove: "{{ to_be_remove |default([]) + [item['msg'][0]['.id']] }}" loop: "{{ id_to_remove.results }}" - name: Dump "Remove ips - stage 1 - query" output ansible.builtin.debug: msg: '{{ to_be_remove }}' # Remove "{{ rmips }}" with ".id" by "to_be_remove" from query - name: Remove ips - stage 2 - remove "{{ ip2 }}" and "{{ ip3 }}" by '.id' community.routeros.api: hostname: "{{ hostname }}" password: "{{ password }}" username: "{{ username }}" path: "{{ path }}" remove: "{{ item }}" register: remove loop: "{{ to_be_remove }}" - name: Dump "Remove ips - stage 2 - remove" output ansible.builtin.debug: msg: '{{ remove }}' - name: Arbitrary command example "/system identity print" community.routeros.api: hostname: "{{ hostname }}" password: "{{ password }}" username: "{{ username }}" path: "system identity" cmd: "print" register: cmdout - name: Dump "Arbitrary command example" output ansible.builtin.debug: msg: "{{ cmdout }}" ''' RETURN = ''' --- message: description: All outputs are in list with dictionary elements returned from RouterOS api. sample: C([{...},{...}]) type: list returned: always ''' from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.basic import missing_required_lib from ansible.module_utils._text import to_native import ssl import traceback LIB_IMP_ERR = None try: from librouteros import connect from librouteros.query import Key HAS_LIB = True except Exception as e: HAS_LIB = False LIB_IMP_ERR = traceback.format_exc() class ROS_api_module: def __init__(self): module_args = (dict( username=dict(type='str', required=True), password=dict(type='str', required=True, no_log=True), hostname=dict(type='str', required=True), port=dict(type='int'), ssl=dict(type='bool', default=False), path=dict(type='str', required=True), add=dict(type='str'), remove=dict(type='str'), update=dict(type='str'), cmd=dict(type='str'), query=dict(type='str'))) self.module = AnsibleModule(argument_spec=module_args, supports_check_mode=False, mutually_exclusive=(('add', 'remove', 'update', 'cmd', 'query'),),) if not HAS_LIB: self.module.fail_json(msg=missing_required_lib("librouteros"), exception=LIB_IMP_ERR) self.api = self.ros_api_connect(self.module.params['username'], self.module.params['password'], self.module.params['hostname'], self.module.params['port'], self.module.params['ssl']) self.path = self.list_remove_empty(self.module.params['path'].split(' ')) self.add = self.module.params['add'] self.remove = self.module.params['remove'] self.update = self.module.params['update'] self.arbitrary = self.module.params['cmd'] self.where = None self.query = self.module.params['query'] if self.query: if 'WHERE' in self.query: split = self.query.split('WHERE') self.query = self.list_remove_empty(split[0].split(' ')) self.where = self.list_remove_empty(split[1].split(' ')) else: self.query = self.list_remove_empty(self.module.params['query'].split(' ')) self.result = dict( message=[]) # create api base path self.api_path = self.api_add_path(self.api, self.path) # api call's if self.add: self.api_add() elif self.remove: self.api_remove() elif self.update: self.api_update() elif self.query: self.api_query() elif self.arbitrary: self.api_arbitrary() else: self.api_get_all() def list_remove_empty(self, check_list): while("" in check_list): check_list.remove("") return check_list def list_to_dic(self, ldict): dict = {} for p in ldict: if '=' not in p: self.errors("missing '=' after '%s'" % p) p = p.split('=') if p[1]: dict[p[0]] = p[1] return dict def api_add_path(self, api, path): api_path = api.path() for p in path: api_path = api_path.join(p) return api_path def api_get_all(self): try: for i in self.api_path: self.result['message'].append(i) self.return_result(False, True) except Exception as e: self.errors(e) def api_add(self): param = self.list_to_dic(self.add.split(' ')) try: self.result['message'].append("added: .id= %s" % self.api_path.add(**param)) self.return_result(True) except Exception as e: self.errors(e) def api_remove(self): try: self.api_path.remove(self.remove) self.result['message'].append("removed: .id= %s" % self.remove) self.return_result(True) except Exception as e: self.errors(e) def api_update(self): param = self.list_to_dic(self.update.split(' ')) if '.id' not in param.keys(): self.errors("missing '.id' for %s" % param) try: self.api_path.update(**param) self.result['message'].append("updated: %s" % param) self.return_result(True) except Exception as e: self.errors(e) def api_query(self): keys = {} for k in self.query: if 'id' in k and k != ".id": self.errors("'%s' must be '.id'" % k) keys[k] = Key(k) try: if self.where: if len(self.where) < 3: self.errors("invalid syntax for 'WHERE %s'" % ' '.join(self.where)) where = [] if self.where[1] == '==': select = self.api_path.select(*keys).where(keys[self.where[0]] == self.where[2]) elif self.where[1] == '!=': select = self.api_path.select(*keys).where(keys[self.where[0]] != self.where[2]) elif self.where[1] == '>': select = self.api_path.select(*keys).where(keys[self.where[0]] > self.where[2]) elif self.where[1] == '<': select = self.api_path.select(*keys).where(keys[self.where[0]] < self.where[2]) else: self.errors("'%s' is not operator for 'where'" % self.where[1]) for row in select: self.result['message'].append(row) else: for row in self.api_path.select(*keys): self.result['message'].append(row) if len(self.result['message']) < 1: msg = "no results for '%s 'query' %s" % (' '.join(self.path), ' '.join(self.query)) if self.where: msg = msg + ' WHERE %s' % ' '.join(self.where) self.result['message'].append(msg) self.return_result(False) except Exception as e: self.errors(e) def api_arbitrary(self): param = {} self.arbitrary = self.arbitrary.split(' ') arb_cmd = self.arbitrary[0] if len(self.arbitrary) > 1: param = self.list_to_dic(self.arbitrary[1:]) try: arbitrary_result = self.api_path(arb_cmd, **param) for i in arbitrary_result: self.result['message'].append(i) self.return_result(False) except Exception as e: self.errors(e) def return_result(self, ch_status=False, status=True): if status == "False": self.module.fail_json(msg=to_native(self.result['message'])) else: self.module.exit_json(changed=ch_status, msg=self.result['message']) def errors(self, e): if e.__class__.__name__ == 'TrapError': self.result['message'].append("%s" % e) self.return_result(False, True) self.result['message'].append("%s" % e) self.return_result(False, False) def ros_api_connect(self, username, password, host, port, use_ssl): # connect to routeros api conn_status = {"connection": {"username": username, "hostname": host, "port": port, "ssl": use_ssl, "status": "Connected"}} try: if use_ssl is True: if not port: port = 8729 conn_status["connection"]["port"] = port ctx = ssl.create_default_context() ctx.check_hostname = False ctx.set_ciphers('ADH:@SECLEVEL=0') api = connect(username=username, password=password, host=host, ssl_wrapper=ctx.wrap_socket, port=port) else: if not port: port = 8728 conn_status["connection"]["port"] = port api = connect(username=username, password=password, host=host, port=port) except Exception as e: conn_status["connection"]["status"] = "error: %s" % e self.module.fail_json(msg=to_native([conn_status])) return api def main(): ROS_api_module() if __name__ == '__main__': main()