Posts

Showing posts from April, 2011

Outputting an image larger than the window from a line scan camera opencv c++ -

i trying use line scan camera generate rather long image not fit within bounds of window. trying output long image using mat.copyto , keep getting cv assertion error code: cv_assert(channels() == cv_mat_cn(dtype)); can tell me means or how fix it?

selenium - Slow Specification Progress -

$ gauge -v gauge version: 0.8.4 plugins ------- html-report (4.0.2) java (0.6.4) chrome: latest chromedriver: 2.31 selenium-java: 3.4.0 tl;dr running gauge specifications on machine intranet access runs slow compared machine has full access internet. known issue? details i'm converting gauge/sahi project migrated twist pure gauge/selenium project. have project running locally , runs super fast. the issue happens when run specifications on environment, @ point specifications progress in browser time page load happens. time page load happens, page loads quickly, browser activity spinner keeps spinning quite few seconds before seems timeout , proceeds tests, repeating hang further page loads. i've tried differences between 2 machines trying find fix. 2 machines have same gauge plugins , gauge version on them. local machine running win 7 while machine issue running win server '08 r1. tests on win serv box run , finish correctly if given enough time, don&

bash - Linux shell script regex match -

Image
i have text file. want lines starting specific format. want lines have x/x/x format. x number. regex not working. giving no match : while read line regex="\d+\/\d+\/\d+" if [[ ${line} =~ ${regex} ]]; echo ${line} else echo "no match : ${line}" fi done <${textfilename} file : don't use bash if can use better tool: grep -e '^[[:digit:]]+/[[:digit:]]+/[[:digit:]]+' "${textfilename}" but if have use bash: while ifs= read -r line if [[ "$line}" =~ ^[[:digit:]]+/[[:digit:]]+/[[:digit:]]+ ]]; echo -- "$line" else echo "no match: $line" fi done < "$textfilename" \d not valid regex(3) .

node.js - Heroku Single User Node App, do I need Redis -

i'm building simple node app broadcast messaging using socket.io. have 3 users @ time user 1: moderator (gets stream of social media comments various apis, picks messages send user 2 , user 3) user 2: graphics (displays messages pushed user 1 graphics in openbroadcastsoftware) user 3: host (displays messages pushed user 1 on ipad (to field viewer questions) this realtime use, nothing needs saved or logged. i know basics of sending , receiving socket.io messages. my question is, portability, want host app on heroku if single free/hobby dyno app, need sort of backend redis? or work if hosting app on local server since there once instance? this app never going have more 3 users described above, i'm not looking implement scaling what-so-ever thanks!

Using group by function in python/pandas dataframe -

i have data frame in python . data looks below. id time test count 1 01:25.5 1105 1 2 02:25.9 1105 0 3 03:25.5 1105 1 4 04:25.5 1105 1 5 05:25.9 1105 1 6 06:25.5 1105 0 7 07:25.9 1105 1 8 08:25.6 1105 1 9 09:25.9 1106 0 10 10:25.6 1105 1 11 11:26.0 1105 1 12 12:25.6 1105 1 13 14:22.0 1105 0 14 14:25.6 1106 1 15 15:26.0 1105 1 16 16:25.6 1105 0 17 17:22.0 1105 1 18 18:25.7 1105 1 19 19:26.0 1105 1 20 20:25.7 1105 0 21 21:25.1 1105 1 22 22:25.7 1106 1 23 22:33.7 1107 0 24 24:25.7 1105 0 25 25:26.1 1105 0 26 27:25.7 1105 1 27 22:35.7 1106 0 now want group records on conditions. 1) if in 3 minute window there 4 or more 4 records particular t

oauth 2.0 - Use Apps Script URLFetchApp to access Google Datastore Data -

i want experiment google datastore via apps script because have current solution based on google sheets runs timeout issues inherent in transacting drive files. i've created test project in google cloud service account , enabled library mzx5dznpsyjvyzar67xxjqai_d-phda33 (cgoa) handle oauth2 work. followed guide start here , got pertinent confirmation works token (and removing token throws 'authentication failed prompt'). now want start basic query display 1 entity put in. can use api explorer here , run query body: { "query": {} } and result: { "batch": { "entityresulttype": "full", "entityresults": [ { "entity": { "key": { "partitionid": { "projectid": "project-id-5200707333336492774" }, "path": [ { "kind": "transaction", "id": "562

aptana3 - Fresh Install of Aptana Studio 3 -

i have installed aptana studion 3 on windows 10 , linux mint 18.2. on both of them following error message on start page when open it, "server unavailable please try again later. server trying connect , how connect (or worry it)? have found nothing addresses issue.

amazon web services - Automate scraping daily and writing to database using AWS -

i need high level advice on how build database. following: (1) write r script pulls data daily website (2) have script automatically run daily, @ same time in morning, without requiring laptop open @ time (so run in cloud?). (3) in r, script's final output dataframe variable, , dataframe variable written (appended) table in database. for variety of reasons, (a) familiar fact scripts can run daily using amazon ec2 instance, (b) know amazon has sort of cloud database service, , (c) want become more familiar aws, set project aws. know how write scraping scripts in r, need advice on how (2) , (3). can has done similar please give advice (so can avoid many of beginner mistakes), , know of sources @ guidance on project? any here appreciated!

openid connect - Why is the IdentityTokenLifetime default to 300 sec? -

maybe should ask intended use of identity token is. thought used identify user , can passed other services (e.g. backend services) , services use id_token validate valid user? don't see current available endpoint validate id_token. if not, should passed 1 service service validate user? the end point takes id_token parameter end session endpoint passed id_token_hint. in case, why identitytokenlifetime default 300 sec only? don't expect user end session in 300 sec. the identity token one-time token. it contains identity of user , authentication metadata. once token validated, (in theory) deleted. pick out claims interested in. the situation want keep identity token around special features during sign-out. the identity token never passed around. that's access token for.

libreoffice - Refer to arguments in SUMIFS conditional -

i want create sumifs condition can refer both arguments. want able "if month , year of first argument equal month , year of second argument." however, examples of sumifs i've seen have condition such "=food", can't perform function on other argument. how can accomplished? sumproduct more powerful sumifs, although harder understand. =sumproduct( month(b1:b20)=month(d1), year(b1:b20)=year(d1), c1:c20 ) this checks rows 1 20 see if month of date in column b equal month of d1, , likewise year. if both equal, sums value column c of row. details on how sumproduct works : if either month or year not equal, result of first or second array row zero. gets multiplied whatever in column c, resulting in zero. value gets summed row zero; in other words, ignored.

Functions as objects in Python: what exactly is stored in memory? -

i've been using python while solve practical problems, still don't have proper theoretical understanding of what's going on behind hood. example, i'm struggling understand how python manages treat functions objects. know functions objects of class 'function', 'call' method, , aware can make custom-made classes behave functions writing 'call method' them. can't figure out precisely gets stored in memory when new functions created, , how access information gets stored. to experiment, wrote little script creates lots of function objects , stores them in list. noticed program used lot of memory. funct_list = [] in range(10000000): def funct(n): return n + funct_list.append(funct) my questions are: what precisely gets stored in ram when define new function object? storing details of how function implemented? if so, function object have attributes or methods allow me "inspect" (or possibly "alter retrosp

javascript - SVG vector changing fill not working -

i'm trying change fill color on svg file. no 1 methods working. trying lot of, can't object want to. <object type="image/svg+xml" data="map.svg" height="500" id="world_map"> browser not support svg. <script src="draw.js"></script> </object> this svg declaration , script src. and script var x = $('#world_map#path1622'); console.log(x); but not working. isn't return element. i've tried code it's not working too. i think have tip. svg file -object -#document -svg and have to code like var content = $("").contents(); i have make access document,object or svg?

jquery - add <a> tag into a class with javascript -

Image
i want add link label tag code this: <div class="swatchinput"> <label selectid="pa_color" class="attribute_pa_color_black wcvaswatchlabel wcvasquare"</label> <div> how can add <a href="test.com"> close after </label> make link. use code jquery dosnt work fine $(".swatchinput").before( "<a href='https://yenial.ir'>" ); $( "</a>" ).appendto( ".attribute_pa_color_black" ); looks don't understand how html, dom, jquery works. need know is: you cannot have improper nesting (like <a></label></a> , asking believe). there no selector $("</a>") . tag starting / ending tag. you cannot wrap <label> <a> . you haven't closed <label> 's starting tag correctly. you haven't closed href attribute correctly. you cannot have <a> inside <label

python - OpenCV: Without modifications, input video file smaller than output file -

i using opencv in python read video .mp4 file ~300kb in size, 1min , 20sec long. have noticed if read each frame file, , write said frame new file using opencv's functionalities, new video copy ~50mb... can explain how possible , how fix it? the codec both files same: h.264 below code: import numpy np import cv2 cap = cv2.videocapture('/users/video.mp4') # define codec , create videowriter object fourcc = cv2.videowriter_fourcc(*'avc1') out = cv2.videowriter('output.mp4',fourcc, 50.0, (160, 210)) while(cap.isopened()): ret, frame = cap.read() if ret==true: out.write(frame) if cv2.waitkey(1) & 0xff == ord('q'): break else: break # release if job finished cap.release() out.release() cv2.destroyallwindows()

javascript - How to parse file data in hapi.js? -

i trying parse excel file data in server using hapi.js . getting file data in binary stream. this code using , need parse file data json binary stream. so, xlsx file coming server side api binary stream. need read binary stream , create file , save locally @ server api server.route({ method: 'post', path: `${path..'/xlsx/')}get`, config: { handler: function (request, reply) { const payload = request.payload console.log(payload); reply ('done'); }, payload: { output: 'stream', parse: true, allow: 'multipart/form-data' }, if (data.file) { var name = data.file.filename; var path = dirname + "/uploads/" + name; var file = fs.createwritestream(path); console.log(path); file.on('error', function (err) { console.e

javascript - Is there an R.notEquals equivalent in Ramda? -

in ramda can follows (this hypothetical code, designed illustrate kind of solution i'm search for) const highest = function(attribute) { switch(attribute){ case 'score': return 'john' } } const hashighestscore = r.compose( r.equals, r.tolower, highest )('score') hashighestscore('john') // true is there equivalent r.equals returns opposite value yet works same r.equals? such hypothetical code work: const hasnothighestscore = r.compose( r.notequals, r.tolower, highest )('score') obviously inverse previous result const doesnothavehighestscore = x => !hashighestscore(x) but i'd know if there r.notequals or perhaps can create myself? thanks. consider following (i wrote before reading comments, honest. don't know why person didn't answer): const nothashighestscore = r.compose( r.complement, r.equals, r.tolower, highest )('score')

ios - PHPhotoLibrary error: content editing in performChanges results in error "The operation couldn’t be completed. (Cocoa error -1.)" -

this code run on viewdidappear of brand new swift app. info.plist setup correctly privacy - photo library usage description key. the error the operation couldn’t completed. (cocoa error -1.) i can create new assets, delete assets, favorite assets, , revert assets... attempting edit content results in error. i've been attempting scour internet clue how go solving (stack overflow, wwdc videos, second page of google, bing , yahoo ). phphotolibrary.requestauthorization { (status:phauthorizationstatus) in if status != phauthorizationstatus.authorized { return } let results = phasset.fetchassets(with: nil) guard let asset = results.firstobject else { return } if asset.canperform(.content) { let inputoptions = phcontenteditinginputrequestoptions() inputoptions.isnetworkaccessallowed = true inputoptions.canhandleadjustmentdata = { (asjustmentdata) -> bool in return false } asset.requestcontenteditingin

android - Change application's starting activity -

i have created meat , guts of application want add different activity starting point (sort of log-in screen). couple questions: 1 have decent handle on how switch between activities (based on article: http://www.linux-mag.com/id/7498 ) i'm not sure how go creating new 1 (with eclipse) . 2 once have new activity created, how can set default activity of application? presume change name of classes...but there more elegant way handle (maybe within androidmanifest.xml )? yes, use androidmanifest.xml file. can have more 1 launcher activity specified in application manifest. make activity seen on launcher add these attributes activity in manifest: <intent-filter> <action android:name="android.intent.action.main" /> <category android:name="android.intent.category.launcher" /> </intent-filter>

jquery - Close the hamburger menu when you click outside of container -

i want have simple hamburger menu. i'm using jquery toggle open , close when hamburger clicked. user able close when click anywhere outside of div or menu. the jsfiddle have written out. don't mind styling. i use like $(window).on('click', function(){ $('.responsive-menu').removeclass('expand'); }) but added, cannot open menu. please help. thank you! the trick check if element clicked has parent .responsive-menu or .menu-btn . if has'n of 2 , menu expanded, toggle! updated fiddle $(document).on("click", function(e){ if( $(e.target).closest(".responsive-menu").length == 0 && $(".responsive-menu").hasclass("expand") && $(e.target).closest(".menu-btn").length == 0 ){ $('.responsive-menu').toggleclass('expand'); } });

camera - Genicam transport Layer -

Image
i new genicam standard, having issue on understanding transport layer gige camera. couldnt find detail information or guideline on writing gige camera transport layer provided camera vendor directly. appreciate if can share information this. dalsa did provide gige-v framework @ website . source code provided, there several function compile .so file still manageable reverse engineer function in driver. working until camera register part. reference understand gige vision driver , genicam. below result get: gige vision library genicam c example program (aug 29 2017) copyright (c) 2015, dalsa. rights reserved. [0][22]: 192.168.34.22 , d0:67:e5:2b:b2:3d [1][26]: 192.168.34.26 , 0c:c4:7a:4c:96:c1 [2][30]: 192.168.34.30 , 00:01:29:65:93:a5 [0][14]: 192.168.128.14 , 3a:f4:e2:f9:af:f7 4 camera(s) on network please enter selected camera index:3 socket handle success! available port 8080 available port 8081 available port 8082 gev_createconnection [testgev_createconnectio

templates - complex constexpr alternatives -

consider typedef std::complex<double> complex; complex complexexpresion(int a) {return complex(0,-a);} since 1 cannot write template<typename d> struct { static constexpr complex value = complexexpresion(d::value); }; as alternative 1 writes template<typename d> struct b { static const complex value; }; template<typename d> const complex b<d>::value = complexexpresion(d::value); consider template<typename d, int n> struct c; template<typename d> struct c<d,1> { static const complex value; }; template<typename d> const complex c<d,1>::value = b<d>::value; for reasone struct data { static auto constexpr value =2; }; int main() { using c = c<data,1>; std::cout << c::value; } prints correct value(which (0,-2) ) here same code prints (0,0) when complied msvc++ i have 2 questions 1) why on msvc++ , there known workaround? 2) there better alter

identityserver4 - IdentityServer3 PublicOrigin and IssuerUri Difference and Usage in IdentityServerOptions -

i got issue when deploying iis. apparently client uses reverse proxy , of openid configuration disco showing ip address instead of domain name. publicorigin solves problem. however, still don't understand different between, publicorigin and issueruri example in: var options = new identityserveroptions { publicorigin = "https://myids/project1/", issueruri = "https://myids/project1/", ... } i can see disco showing changes if both value updated respectively, i.e.; { "issuer": "https://myids/project1/", "jwks_uri": "https://myids/project1/.well-known/jwks", "authorization_endpoint": "https://myids/project1/connect/authorize", "token_endpoint": "https://myids/project1/connect/token", "userinfo_endpoint": "https://myids/project1/connect/userinfo", "end_session_endpoint": "https://myids/project1/connect/endsession

html - Why am I forced to start typing halfway down the input box? Want to start at top and when it reaches end of box wrap to next line -

Image
#main { margin-top: 2rem; margin-bottom: 2rem; } #main #main-col { float: left; width: 68%; margin-right: 2%; } #main #sidebar { float: right; width: 30%; } #main #sidebar #sidebar-message { height: 90px; width: 90%; } <aside id="sidebar"> <h3>advice? leave message!</h3> <p>lorem ipsum dolor sit amet, consectetur adipiscing elit. nam tellus ex, pharetra et orci sollicitudin, luctus consequat massa. donec dapibus neque id lobortis efficitur. morbi ultrices neque ut ipsum rhoncus mollis.</p> <form> full name:<br> <input type="text" name="fullname"><br> message:<br> <input type="text" name="message" id="sidebar-message"><br> </form> </aside> want have user start typing @ top(like twitter) , when reaches end of box

python - Using two different models in tensorflow -

im trying use 2 different mobilenet models. following code of how initialize model. def initialsetup(): os.environ['tf_cpp_min_log_level'] = '2' start_time = timeit.default_timer() # takes 2-5 seconds run # unpersists graph file tf.gfile.fastgfile('age/output_graph.pb', 'rb') f: age_graph_def = tf.graphdef() age_graph_def.parsefromstring(f.read()) tf.import_graph_def(age_graph_def, name='') tf.gfile.fastgfile('output_graph.pb', 'rb') f: gender_graph_def = tf.graphdef() gender_graph_def.parsefromstring(f.read()) tf.import_graph_def(gender_graph_def, name='') print ('took {} seconds unpersist graph'.format(timeit.default_timer() - start_time)) since both 2 different models, how use predictions? update initialsetup() age_session = tf.session(graph=age_graph_def) gender_session = tf.session(graph=gender_graph_def) tf.session()

pypy - Is there any way to install pandas on pypy2-v5.8.0-win32? -

windows 7 64bit.i had install numpy 1.10.0 via. pypy -m pip install git+https://bitbucket.org/pypy/numpy.git then,i tried 3 method(pip+git,pip,easy_install) install pandas,however, all failed,why ? method : pip install git+https://github.com/pandas-dev/pandas.git failed reason: traceback (most recent call last): file "d:\pypy2-v5.8.0-win32\lib-python\2.7\logging\__init__.py", line 895, in emit stream.write(fs % msg) file "d:\pypy2-v5.8.0-win32\site-packages\pip\_vendor\colorama\ansitowin32.py" , line 141, in write self.write_and_convert(text) file "d:\pypy2-v5.8.0-win32\site-packages\pip\_vendor\colorama\ansitowin32.py" , line 169, in write_and_convert self.write_plain_text(text, cursor, len(text)) file "d:\pypy2-v5.8.0-win32\site-packages\pip\_vendor\colorama\ansitowin32.py" , line 174, in write_plain_text self.wrapped.write(text[start:end]) ioerror: [errno 12] not enough space: '<stdout>' logged fi

javascript - onclick reset and showhide -

i have got 1 button reset , 1 link hiding image. onclick used doing this. need use 'hide' link both 'hide' , 'reset' on 'onclick'. code given below: <script> function myframe6() { var ifr = document.getelementsbyname('frame6')[0]; ifr.src = ifr.src; } </script> <p> <input type="button" value="reset" onclick="myframe2()" class="btn btn-primary"> <a href="#" id="p6-hide" class="hidelink" onclick="showhide('p6');return false;">hide image</a> </p> you can either add reset function call (i'm guessing that's myframe2()) link's onclick separated semicolon so: onclick="showhide(); myframe2()" or call myframe2(); , showhide() same function.

XSL - Modify XML Export to Excel to resize columns -

i'm using xsl file modify xml file generate excel spreadsheet - working increase width of columns. can't use the: <xsl:attribute name="ss:autofitwidth">1</xsl:attribute> option columns being generated text contain mix of text, numbers , dates, , docs xml spreadsheet reference mentions use of means 'column should autosized numeric , date values only. not autofit textual values.' that's not option. does know way have columns resized or specify value width of column can @ least increase width more closely reflect content in each column? here's current xml: <?xml version="1.0" encoding="utf-8"?> <fmpxmlresult xmlns="http://www.filemaker.com/fmpxmlresult"> <errorcode>0</errorcode> <product build="06-06-2017" name="filemaker" version="proadvanced 16.0.2"/> <metadata> <field emptyok="yes" maxrepeat="1

Not able to debug VB.Net Service -

i know there many reference problem not able find correct solution it. have created vb windows service , have installed successfully. running in service manager. still when try run project saying cannot start service command line or debugger. i not able debug service. can please guide things missing?

python - Pandas - Filtering text and data -

Image
we have learnt how filter through pandas in python thought try out on public data set. ( http://data.wa.aemo.com.au/#stem-bids-and-offers ) i used august's data this. the challenge set myself filter on $/mwh > 0 , had on bids. have learnt how use np.logical_and filter problem found can filter on either numerical or logical. not both. i have approach works , gets me data , visualisation i'm after i'm there more efficient way of filtering text , numeric fields. problem approach works if character size different. i.e. if said bid or fib. pick both. only want pick bid. please point me in right direction? here code: #task: want filter out positive $/mwh bids #this requires 2 filters - 1 filter out $mwh > 0 , 1 filter bids # try converting numpy array , using filtering mechanisms there import numpy np df = pd.read_csv('stem-bids-and-offers-2017-08.csv') df.head(5) #i don't know how filter 'text' yet have use way using len function #this r

Objective C & Swift -- do they handle both Client and Server Side? -

this general question. in more "traditional" web or browser based development, have server side languages such java, c#, etc. then, on client side, there html, css & javascript. what i'm wondering native mobile app development (note: not mobile web development) this... is there such clear delineation between server side , client side? there separate tools , languages each? if separate, tools used ui development? or, ios, objective c and/or swift handle both? server never returns view in mobile development. api can called when data server needed. rest of things (local storage , screens mainly) lay on device. xcode apple (to develop apple based apps) gives interfacebuilder in form of .storyboard files can used both languages, objective-c , swift.

CSS & JavaScript Popup Not Working -

why isn't javascript function triggering popup? i've tried .classlist style.visibility , neither triggers #filter div display. <div class='lpicon' onclick="designfunction"> <img class='lpactionicon' src='file:///users/homefolder/desktop/hyperspace%20website/images/launchpad/lp%20action%20icon-%20design.png'/> </div> <div id='filter'> </div> css: .lpicon { height: 100px; width: 50px; margin-left: 14%; margin-top: 8%; float: left; } #filter { visibility: hidden; height: 100%; width: 100%; background-color: grey; position: absolute; opacity: .7; top: 0px; } javascript: function designfunction() { document.getelementbyid("filter").classlist.remove("block"); } i think need use designfunction() , need change css of filter div using block if not have provide more code because block present no where. can set slecting , using .cs

angular - How to Store and Retrieve Data in Multidimensional Array in Angular4 / Ionic 3 -

i trying store values in angular 4 (ionic 3) , fetch row array based on key. key passed function , function retrieves values compute values. class property below. pretty sure formatted right. let chemicals = [{ "trichlor" : [{ "ozmul": 6854.95, "volume": "x" }], "dichlor": [{ "ozmul": 4149.03, "volume": 0.9351 }], "cal-hypo-48": [{ "ozmul": 3565.44, "volume": 0.9352 }], "cal-hypo-53": [{ "ozmul": 3936.84, "volume": 0.9352 }], "cal-hypo-65": [{ "ozmul": 4828.12, "volume": 0.9352 }], "cal-hypo-73": [{ "ozmul": 5422.41, "volume": 0.9352 }], "lithium-hypo": [{ "ozmul": 2637.5, "volume": 0.978 }],

python 3.x - image segmentation using watershed algorithm -

Image
i have image me, grey scale image obtained colour image has near grey background . want apply watershed algorithm image count no objects in image. what best way apply thresholding grey image such objects best separated background. edit: thinking of changing background using grabcut algo , apply thresholding.someone me this. in case think simple global auto thresh holding (otsu's algorithm) working fine since region of interest quite together. may use cv2.threshold(img,127,255,cv2.thresh_binary) in opencv or can implement otsu's algorithm yourself. see link

java - Login Post Method Capture Invisible Cookies and Form-Data - Jsoup -

Image
i trying login imbd using following code string loginlink = "https://www.imdb.com/ap/signin?clientcontext=131-8315704-5985438&openid.pape.max_auth_age=0&openid.return_to=https%3a%2f%2fwww.imdb.com%2fap-signin-handler&openid.identity=http%3a%2f%2fspecs.openid.net%2fauth%2f2.0%2fidentifier_select&openid.assoc_handle=imdb_us&openid.mode=checkid_setup&sitestate=eyjvcgvuawquyxnzb2nfagfuzgxlijoiaw1kyl91cyisinjlzglyzwn0vg8ioijodhrwczovl3d3dy5pbwrilmnvbs9yzwdpc3ryyxrpb24vc2lnbmlup3jlzl89bg9naw4ifq&openid.claimed_id=http%3a%2f%2fspecs.openid.net%2fauth%2f2.0%2fidentifier_select&openid.ns=http%3a%2f%2fspecs.openid.net%2fauth%2f2.0&&tag=imdbtag_reg-20"; connection.response loginform = jsoup.connect(loginlink) .useragent("mozilla/5.0 (windows nt 6.1; wow64) applewebkit/535.1 (khtml, gecko) chrome/13.0.782.112 safari/535.1") .method(connection.method.get) .execute(); document doc = lo

c# - klocwork Error: No permission set for resource 'streamWriter' before accessing it -

with article, https://support.roguewave.com/documentation/klocwork/en/10-x/cs.nps/ i still getting klocwork error, after explicitly setting security. solution resolve it. it's giving error below line of code, streamwriter.writeline("hello"); here full code, using (var stream = new filestream(@"c:\\sample.txt", filemode.create)) { var security = new system.security.accesscontrol.filesecurity(); security.addaccessrule(new filesystemaccessrule(@"domain\user", filesystemrights.modify, accesscontroltype.allow)); stream.setaccesscontrol(security); using (var streamwriter = new streamwriter(stream)) { streamwriter.writeline("hello"); } }

shell - extract rar files to same folder name -

i have many .rar folders within particular directory. want extract contents of each rar folder in same directory , extracted files of rar folder should placed in new folder same name of rar folder name. for example, if there 2 rar files: one.rar , two.rar , script should create 2 folders of same name: one , two . folder named one should contain files extracted one.rar , folder named two should contain files extracted two.rar . the command: unrar e $filename extracts contents of rar file not create destination folder. if use unrar e $filename $destination_path , since there can many rar files, manually creating folder name in destination path take lot of time. how can achieve shell script? so far have written these lines: loc="/home/desktop/code"` # directory path contains rar files extracted <br/> file in "$loc"/* unrar e $file done i don't know how create same folder name of rar name , extract files of rar

loopbackjs - How to implement attribute level mask depending on the Roles in loopback.js? -

i have few roles created in loopback application. there way in can hide property of model depending on roles of user? yes. can create function , in function based on role of user, can delete specific fields. function should called after each remote method want apply rule (you can use * apply function after remote methods). here sample code hope helps you: const filterbasedonrole= function (ctx, remotemethodoutput, next) { const rolemapping = samplemodel.app.loopback.rolemapping; if (ctx.req.accesstoken && ctx.req.accesstoken.userid) { rolemapping.findone({ where: { principalid: ctx.req.accesstoken.userid }, include: 'role', }, (err, rolemapping) => { if (err) { return next(err); } if (!rolemapping) { //user doesn't have role } else { const role = rolemapping.role().name; if (role === 'admin') { // remove fields remotemethodoutput

regex - How to replace single quote to two single quotes, but do nothing if two single quotes are next to each other in perl -

i need change single quote found in string 2 single quotes, if more 1 single quotes found successively, should remain is. e.g. str = abc'def''sdf'''asdf output should : str = abc''def''sdf'''asdf i think cleanest way search following pattern: (?<!')'(?!') and replace 2 single quotes. pattern searches single quote, has negative lookbehind , lookahead assertions check preceeding , proceeding character not single quote. my $var = "abc'def''sdf'"; print "$var\n"; $var =~ s/(?<!')'(?!')/''/g; print "$var\n"; note have written straight pattern match, e.g. (^|[^'])'($|[^']) but replacement becomes tricky because have consumed characters surrounding single quote. don't work if don't have to. output: abc'def''sdf' abc''def''sdf'' demo here: rextester

php - get Latest Registered Id? -

code : want have latest registered employeeid in drop down list database ? public function getemployeeid() { if (!isset($_session["email"]) || !isset($_session["passwrd"])) { header("location:index.php"); // cannot access page without login. } if (empty($_post)) { $query = mysqli_query($this->connection, "select employeeid employees") or die("query execution failed: " . mysqli_error()); while ($row = $query->fetch_array()) { $id = $row["employeeid"]; $_session["id"] = $id; } } } here html code snippet : <td> <select name="employeeid" required autofocus class='form-control'> <option value=""> ----select----</option> <?php if (iss

Generate random boxed co-ordinates in c# -

i need find random co-ordinates, bound square. defined values 70, 55, 175, 175 furthest points want go to: north = utility.generaterandomnumber(utility.directions.north, 70); south = utility.generaterandomnumber(utility.directions.south, 55); east = utility.generaterandomnumber(utility.directions.east, 175); west = utility.generaterandomnumber(utility.directions.west, 175); my generator below, have declare global static param: public static random random = new random(); directions enumerator. public static int generaterandomnumber(directions direction, int to) { if ((direction == directions.south) || (direction == directions.west)) return random.next(to * -1, 0); else return random.next(0, to); } the function works fine , retrieve co-ordinates below: north: 52 south: -13 east: 82 west: -105 north: 27 south: -45 east: 172 west: -117 north: 0 south: -37 east: 161 west: -160 north: 43 south: -39 east: 26 west: -174 north: 29 south: -7 east: 75 we

node.js - How to generate token using passport.js while signing in locally and not with any other social media channel? -

i trying generate token while logging in locally. let's normal user , want sign in. token generated while signing in? , how? need guidance. as using mongodb require users schema model in routes code.here routes code user.js var express = require('express'); var router = express.router(); var passport = require('passport'); var user = require('../models/schema'); var verify = require('./verify'); /* users listing. */ router.get('/', function(req, res, next) { res.send('respond resource'); }); router.post('/register', function(req, res) { user.register(new user({ username : req.body.username,email: req.body.email, phone:req.body.phone }),req.body.password, function(err, user) { if (err) { return res.status(500).json({err: err}); } passport.authenticate('local')(req, res, function () { return res.status(200).json({status: 'registration suc

angular - Sending string one component to other component in angular2 -

i want send username login component home component ...how can please tell me simple example showing sending string 1 component use angular2 cli , vs code editor use @input import { component, input } '@angular/core'; @component({ selector:'counter', inputs: ['number'] }) export class countercomponent { @input() count: number = 0; } @component({ selector: 'counter-sibling', template: '' }) export class countersibling{ @output() count: number = 0; } usage in counter-sibling:

xmltextwriter - ERROR-- Token StartDocument in state End Document would result in an invalid XML document -

i want create xml file below code ..can focus me olution.i searched on error message not find relavent. code:- stringbuilder builder = new stringbuilder(); using (stringwriter stringwriter = new stringwriter(builder)) { using (xmltextwriter writer = new xmltextwriter(stringwriter)) { xmlwritersettings settings = new xmlwritersettings(); settings.indent = true; settings.omitxmldeclaration = false; writer.writestartdocument(); writer.writestartelement("xsl:output",""); writer.writeattributestring("method", "xml"); writer.writeattributestring("indent", "yes"); writer.writeendelement(); writer.writestartelement(fihrdocument, ""); writer.writestartelement("xsl:value-of",""); wri

linq - IQueriable() to ListAsync() conversion issue due to filter on list inside a list -

i have issue filtering list inside list on async method. private async task<list<userlist>> getasynclist(string query) { var result = getuserlist.where(x => x.firstname.toupper().contains(query.toupper()) || x.lastname.toupper().contains(query.toupper()) || x.emailid.toupper().contains(query.toupper()) **|| x.userrole.any(a => a.toupper().contains(query.toupper()))**); return await result.tolistasync(); } getting below exception expression of type 'system.collections.generic.iasyncenumerable 1[system.string]' cannot used parameter of type 'system.collections.generic.ienumerable 1[system.string]' of method 'system.collections.generic.list 1[system.string] tolist[string](system.collections.generic.ienume

How to generate certificate with pkcs11 in JAVA -

i generated rsa keypair pkcs11 , don't know how generate csr , certificate. working code, keypair generated. // set sun pkcs 11 provider string configname = "hsmconfig.cfg"; provider p = new sunpkcs11(configname); if (-1 == security.addprovider(p)) { throw new runtimeexception("could not add security provider"); } // load key store char[] pin = "ocsocsp3".tochararray(); keystore ks = keystore.getinstance("pkcs11", p); ks.load(null, pin); // generate key securerandom sr = new securerandom(); keypairgenerator keygen = keypairgenerator.getinstance("rsa", p); keygen.initialize(1024, sr); keypair keypair = keygen.generatekeypair(); privatekey pk = keypair.getprivate(); publickey pub = keypair.getpublic();

How to add custom method to spring integration ftp gateway interface? -

following spring integration ftp doc , have managed send files ftp server through java config way: @messaginggateway public interface mygateway { @gateway(requestchannel = "toftpchannel") void sendtoftp(file file); } ss public static void main(string[] args) { configurableapplicationcontext context = new springapplicationbuilder(ftpjavaapplication.class) .web(false) .run(args); mygateway gateway = context.getbean(mygateway.class); // sending file ftp server gateway.sendtoftp(new file("/foo/bar.txt")); } it seems me code above using custom method 'sendtoftp()' send file target ftp server. question how add other methods mygateway interface implement operations? ls (list files) (retrieve file) mget (retrieve file(s)) rm (remove file(s)) mv (move/rename file) put (send file) mput (send multiple files) each ftp gateway can handle 1 method. you need

javascript - Function don't return value from array -

this question has answer here: javascript closure inside loops – simple practical example 31 answers i have snippet of code for(var i=0; < this.arr2.length; i++) { arr.push({ id: i.tostring(), label: this.arr2[i], display: () => this.arr2[i] }) } why display undefined if doing let val = this.arr2[i]; display: () => val is working fine you should use let keyword in order declare block scope local variable for(let = 0; < this.arr2.length; i++) { arr.push({ id: i.tostring(), label: this.arr2[i], display: () => this.arr2[i] }) } for example use map method. the map() method creates new array results of calling provided function on every element in calling array. arr=arr2.map(function(item,i){ return {id:i,label:item,display:()=>item}; }); short exam

c++ - Calling a macro only once in the project -

i trying set easylogging++ in project, , run following issue: macro initialize_easyloggingpp should called once in project. now, if call macro main.cpp , include easylogging++.h in main.cpp - works fine. however, when try include easylogging++.h in more .cpp files, linker issues undefined references (as if macro hasn't been called). if place call macro in file alphabetically before main.cpp , linker resolves normally. in linking phase objects sorted alphabetically. is there nice way solve issue? or have try force different order of files @ linking time? i not experienced sort of issues, tried googling it, couldn't find solution. if there similar question, sorry, couldn't find it. thanks help! maybe wrap call in function invoke using std::call_once() , example: void setup_logging() { static std::once_flag once; std::call_once(once, [] () { initialize_easyloggingpp(); }); } that way can call setup_logging() multiple times, macro invoked on

javascript - Parse Server querying subobject with containedIn -

does parse server support constraint containedin subobject? i have try this: const chatquery = new parse.query('chat') .containedin('target.group', [1,2,3]) but show error: { "code": 141, "error": { "code": 1, "message": { "name": "error", "length": 112, "severity": "error", "code": "42703", "position": "71", "file": "parse_relation.c", "line": "3183", "routine": "errormissingcolumn" } } } and code below doesn't throw error although not purpose: const chatquery = new parse.query('chat') .equalto('target.group', 1) i don't know if didn't support or code wrong. have open gh issue (see https://github.com/parse-community/parse-server/issues/4099 ) still no respond. i

c# - How to make an oval frame in RDLC ( Report Viewer ) -

is possible round corners of rectangle in rdlc report? i'm trying make oval frame in parameter text. i don't think changed in area since, here found when looking similar feature: rounded corners on report body , header borders . think background image option , can create dynamically too. also, here suggestion: from so , haven't tried approach, don't know if works.

session - AsyncStorage : React Native -

save 'unique id' session variable in react native you can add unique id using asyncstorage : asyncstorage.setitem('key name', uniqueid) and after can other component : asyncstorage.getitem('key name').then((value) => console.log(value)) for details can read documentation . hope answer can you.

threshold - Chips - How do I show dropdown list on clicking view (ChipsInput) -

i'm using materialchipsinput library implementing chips. has threshold 1, when type character shows list. how show drop down list clicking on widget. as in autocompletetextview setthreshold 0, , inside setonclicklistener view.showdropdown() . how implement same library. i didn't find threshold or show drop down list kind methods.

javascript - Code behaving different on phones and tablets -

i've built page writes , reads info , firebase database. now, works , on pc, , when simulating different phones , laptops in inspector. thing on actual android or ios references seems off. still saves database in wrong places. missing? here's line sets values in database: database.ref("birds/birdlist/" + [newid] + "/seene").set(checkvalue); and on iphone, example, line sets in: birds/birdlist "seene: true" or "seene: false" dependning on user's input. i'm thinking might have var newid , on touchscreens clicking doesn't id passed on should, don't know how track on actual phone (in inspector can log activity, said works simulated phone on computer anyway). function getid() { var _id = document.activeelement.id; newid = _id.substring(8); } i use click event trigger functions. input appreciated! could share snippet of code codepen or else can see? did try touchstart/touchend event mobile devices