Posts

Showing posts from January, 2014

java - writing a program to obtain various data values from user and displaying it in different formats. -

this question has answer here: scanner skipping nextline() after using next(), nextint() or other nextfoo()? 14 answers i newbie in java , have written program display flight details import java.io.*; import java.util.scanner; class main { public static void main(string args[]) { int ticket; string name,destination; float fare; char tclass; scanner in = new scanner(system.in); system.out.println("enter flight name : "); name=in.nextline(); system.out.println("enter ticket no : "); ticket=in.nextint(); system.out.println("enter flight fare : "); fare=in.nextfloat(); system.out.println("enter travelling class : "); tclass=in.next().charat(0); system.out.println("enter source : "); string source=in.nextline(); system.out.println("enter destination

python - How to discretize large dataframe by columns with variable bins in Pandas/Dask -

i able discretize pandas dataframe columns code: import numpy np import pandas pd def discretize(x, n_scale=1): c in x.columns: loc = x[c].median() # median absolute deviation of column scale = mad(x[c]) bins = [-np.inf, loc - (scale * n_scale), loc + (scale * n_scale), np.inf] x[c] = pd.cut(x[c], bins, labels=[-1, 0, 1]) return x i want discretize each column using parameters: loc (the median of column) , scale (the median absolute deviation of column). with small dataframes time required acceptable (since single thread solution). however, larger dataframes want exploit more threads (or processes) speed computation. i no expert of dask , should provide solution problem. however, in case discretization should feasible code: import dask.dataframe dd import numpy np import pandas pd def discretize(x, n_scale=1): # i'm using 2 partitions example x_dask = dd.from_pandas(x, npartitions=2)

c# - Difference between initiating sql object inside "using" statement and decorating with using statement -

this question has answer here: is sqlcommand.dispose() required if associated sqlconnection disposed? 5 answers i've doubt significant difference applying "using" statement in same code block different way , know practice best way me sameple 1 code block using (sqlconnection sqlconnection = new sqlconnection(dbconnectionstring)) { sqlconnection.open(); using (var command = new sqlcommand(store_procname, sqlconnection)) { command.parameters.add(constants.param_value, sqldbtype.varchar).value = id; command.commandtype = commandtype.storedprocedure; using (var adp = new sqldataadapter(command)) { adp.fill(dtvalid); }

ios - NSURLSessionUploadTask how to read server response -

i using nsurlsessionuploadtask upload file. here parts of code not complete let session:nsurlsession = nsurlsession(configuration: config, delegate: self, delegatequeue: nsoperationqueue .mainqueue()) let sessiontask:nsurlsessionuploadtask = session.uploadtaskwithstreamedrequest(request but problem unable json response server sends back. the following delegate not firing other delegates firing func urlsession(session: nsurlsession, datatask: nsurlsessiondatatask, didreceivedata data: nsdata) code using: func sendfiletoserver1(filename:string,filedata:nsdata,serverurl:string){ let body = nsmutabledata() let mimetype = "application/octet-stream" // let mimetype = "video/quicktime" let boundary = "boundary-\(nsuuid().uuidstring)" let url = nsurl(string: serverurl) let request = nsmutableurlrequest(url: url!) request.httpmethod = "post" request.setvalue("multipart/form-data; boundary=----\(boundary)", forhttph

php - Rest request url -

i have this url post https://domainname/api/v1/loans/{loanid}/transactions?command=repayment which used post data php software exposes functionality via rest. in docs,this information given post loans/5/transactions?command=repayment content-type: application/json request body: { "dateformat": "dd mmmm yyyy", "locale": "en", "transactiondate": "14 may 2013", "transactionamount": "500.00", "paymenttypeid": "12", "note": "check payment", "accountnumber": "acc123", "checknumber": "che123", "routingcode": "rou123", "receiptnumber": "rec123", "banknumber": "ban123" } this example loans/5/transactions?command=repayment loanid entered 5 how can include other parameters given in request body url?. if request server https post fun

between java.time.LocalTime (next day) -

please suggest if there api support determine if time between 2 localtime instances, or suggest different approach. i have entity: class place { localtime startday; localtime endday; } which stores working day start , end time, i.e. '9:00' till '17:00', or nightclub '22:00' till "5:00". i need implement place.isopen() method determines if place open @ given time. a simple isbefore / isafter not work here, because need determine if end time on next day. of course, can compare start , end times , make decision, want without additional logic, simple between() call. if localtime not sufficient purpose, please suggest other. if understand correctly, need make 2 cases depending on whether closing time on same day opening time (9-17) or on next day (22-5). it be: public static boolean isopen(localtime start, localtime end, localtime time) { if (start.isafter(end)) { return !time.isbefore(start) || !time.isafter(

regex - File splitting using Perl -

i'm trying split large text files several text files. found thread few years ago similar premise couldn't find exact situation. https://unix.stackexchange.com/a/64691/183674 how split following data if first line didn't start 00:00:00:00? 00:00:00:00 00:00:05:00 01sc_001.jpg 00:00:14:29 00:00:19:29 01sc_002.jpg 00:01:07:20 00:01:12:20 01sc_003.jpg 00:00:00:00 00:00:03:25 02mi_001.jpg 00:00:03:25 00:00:08:25 02mi_002.jpg 00:00:35:27 00:00:40:27 02mi_003.jpg 00:00:00:00 00:00:05:00 03bi_001.jpg 00:00:05:19 00:00:10:19 03bi_002.jpg 00:01:11:17 00:01:16:17 03bi_003.jpg 00:00:00:00 00:00:05:00 04cg_001.jpg 00:00:11:03 00:00:16:03 04cg_002.jpg 00:01:12:25 00:01:17:25 04cg_003.jpg here's code reference: #!/usr/bin/env perl use strict; use warnings; open(my $infh, '<', 'abc_tabdelim.txt') or die $!; $outfh; $filecount = 0; while ( $line = <$infh> ) { if ( $line =~ /^00:00:00:00/ ) { close($outfh) if $outfh; open($out

github - Merge two copies of the same git repository -

i made git repo foo , started working. twenty commits later, copied on files repo new directory bar , created new git repo. have twenty commits on bar repo, too. how merge 2 repos have 1 clean history? want rid of first commit in bar repo , append rest foo repo. you add second repository remote first repo , rebase commits onto branch of foo repository. inside foo repository add bar repository $ git remote add bar <path-to-bar> $ git fetch bar now find commit want rebase (in case second one) , do $ git rebase master <hash-of-second-commit> depending on how 2 repositories differ apply cleanly, or might have resolve merge conflicts.

css - Make a darker box in a canvas with pattern -

Image
i have defined rule has-pattern in css: .has-pattern { background-image: url('../images/patterns/pattern-1.png'); background-repeat: repeat; background-position: left top; } as result, section has-pattern applied ( <section class="team section has-pattern"> ) has following background: now, want insert smaller box inside section, darker background color. question how not make darker box break existing pattern. i tried add follows in css: .team .box-inner { padding: 60px; background-color: #3fa07a; background-image: url('../images/patterns/pattern-1.png'); background-repeat: repeat; } the problem pattern of 2 levels not match: does has solution? you can acheive not using pattern inner box using rgba colour value instead, allowing pattern show through transparency. eg. background: rgba(0,0,0,0.2); demo @ https://jsfiddle.net/xudg5d93/ for futher control on how transparency affects things, might want

java - Does JavaFX support regular expressions (or wild cards) in CSS? -

i've tried using wild cards in css selectors javafx ui (tableview), doesn't seem work, although javafx css reference notes it's based on css version 2.1: javafx cascading style sheets (css) based on w3c css version 2.1 additions current work on version 3. for example: tablecolumnheader[id|="column"] > .label { -fx-graphic: url("ico.png"); } the above css attempt show icon "ico.png" on column headers of tableview tablecolumnheader type selector table's column header node .label style class label node rendered within column header [id|="column"] similar example mentioned here: https://www.w3.org/tr/css21/selector.html#matching-attrs the id of column header inherited tablecolumn . id set on tablecolumn object follows: tablecolumn.setid("column-"+ columnname) columnname string variable the above css doesn't work. variation includes [id=...] , or other attribute other id doesn&#

windows - Batch: Return filename with highest integer -

if have directory full of text files such 01.text.sql 02text.sql 3text.sql how return file name highest integer e.g. 3.text.sql? can see numbers might not prefixed 0 , might missing . after integer. know have loop through directory this choose highest numbered file - batch file however, not take account different file name formats. there way batch script can loop through directory , automatically pull file highest integer or have store file names , compare them each other in separate loop? currently have returns 3text instead of 3 setlocal enabledelayedexpansion set max=0 %%x in (*.sql) ( set "fn=%%~nx" set "fn=!fn:*-=!" if !fn! gtr !max! set max=!fn! ) echo highest script number %max% updated loop: setlocal enabledelayedexpansion set scriptmax=0 %%x in (*.sql) ( set "fn=%%~nx" set a=1000!fn! set /a fn=a %% 1000 if !fn! gtr !max! set max=!fn! ) set /a a=b interpret in b first non numeric character number, so s

ios - App crashes while app is going into background and when iPad gets auto-locked -

i facing weird issue in application when app goes background mode , when ipad gets locked. till working fine while unlocking device , opening app background, crashing. this crash log, getting device exception type: 00000020 exception codes: 0x000000008badf00d exception note: simulated (this not crash) highlighted thread: 8 application specific information: <bknewprocess: 0x12cd18cb0; com.apps-factory; pid: 540; hostpid: -1> has active assertions beyond permitted time: {( <bkprocessassertion: 0x12cd1e3b0> id: 540-72c6af6c-f674-40e8-ba89-efe4bf52f8d6 name: called uikit, <redacted> process: <bknewprocess: 0x12cd18cb0; com.apps-factory; pid: 540; hostpid: -1> permittedbackgroundduration: 180.000000 reason: finishtask owner pid:540 preventsuspend preventidlesleep preventsuspendonsleep )} elapsed total cpu time (seconds): 82.430 (user 82.430, system 0.000), 23% cpu elapsed application cpu time (seconds): 77.475, 21% cpu filtered syslog: none fou

Is there any way to allow pycharm autocomplete the function arguments? -

the pycharm ctrl+p can show argument tip. there way can let pycharm automatically inject arguments (with default argument name) code pydev? i using pycharm community edition 2016.2.1 on linux , best find (after searching while on topic) use same in eclipse: ctrl + space. creates drop down menu containing function arguments allows select ones need. unfortunately, drop down menu contains non functions arguments entries typically arguments show @ top. note arguments not in right order. not great solution is i'm using now.

angularjs - Developing and deploying Angular 2 application with Java REST back-end to production -

i have application java rest (jetty/jersey) back-end. want develop ui in angular 2. how best structure , build project(s) development , deployment? considerations: i using node , npm start run test server. fine start both java service , npm start testing. we use eclipse java app. minimal editing in eclipse typescript angelozerr's plugin works great. we use jenkins build. i'm attempting figure out: folder structure. go inside same eclipse project rest service? build. npm install in jenkins build , populate dist folder? this tutorial may helpful: https://blog.udemy.com/node-js-tutorial/ it covers angularjs, nodejs, express , mongodb. (mean stack)

ruby on rails - capybara and RSpec: ajax response not working -

i'm working on writing test cases using ( rspec , capybara ). capybara (2.7.1) , rspec (3.4.0) rspec-core (3.4.4) rspec-expectations (3.4.0) rspec-mocks (3.4.1) rspec-rails (3.4.2) rspec-support (3.4.1) there many answers available no luck!!!. these result found: 1 , 2 , , 3 capybara.rb capybara.asset_host = 'http://localhost:3000' capybara.default_max_wait_time = 5 session_helpers.rb module features module sessionhelpers def sign_up_with(email, password, confirmation) visit new_user_registration_path fill_in 'email', with: email fill_in 'password', with: password fill_in 'password confirmation', :with => confirmation click_button 'sign up' end def signin(email, password) visit root_url find(:xpath, "//a[@class='login_box_btn']").click fill_in 'login_user_email', with: email fill_in 'login_user_password', with: passwo

redux - Normalizr create result for single enity -

i using normalizr have same response shape different api endpoints. const post = new schema('posts'); const posts = arrayof('post'); const listresponse = [ {id: 1, text: 'post one'}, {id: 2, text: 'post two'}, ]; normalize(listresponse, posts); /* { entities: { posts: { 1: {id: 1, text: 'post one'}, 2: {id: 2, text: 'post two'} } }, result: [1, 2] } */ const singleresponse = {id: 1, text: 'post one'}; normalize(singleresponse, post); /* { entities: { posts: { 1: {id: 1, text: 'post one'} } }, result: 1 } */ then treat normalized response no matter how came. but thing single item getting result: 1 instead of array result: [1] , cause issues in later code. now have normalize result array manually, maybe there better way that? in application, used 2 different actions case, fetch_post , fetch_posts acc

angularjs - Angular autocomplete with search filter -

how can have autocomplete feature in angular combined search filter? this code using search filter problem want add autocomplete feature. js code angular.module('sortapp', []) .controller('maincontroller', function($scope) { $scope.sorttype = 'country'; // set default sort type $scope.sortreverse = false; // set default sort order $scope.searchcountry = ''; // set default search/filter term $scope.countries = [ { country: 'austria', smallmediumbusiness: '+43-720-880296', enterprise: '0800006482', countryclass:'at'}, { country: 'belgium', smallmediumbusiness: '+32-78480136', enterprise: '080049411', countryclass:'be'}, { country: 'bulgaria', smallmediumbusiness: '+359-24917167', enterprise: '00800-115-1013', countryclass:'bg'}, { country: 'croatia', smallmediumbusiness: '', enterprise

sockets - C: UDP packets source Ip faking - can't receive packet -

after hours on google still cant figure out. what trying is: want send udp packets fake source-ip c programm (see code below). what not working: when send packet server-1 server-2 , trying receive it, appear in 'iftop', when sourceip of packet not faked. when put fake ip in udp header still sais me packet sent (i see on 'iftop' on server-1), won't receive on server-2. example when send correct sender ip, i'll receive packet , see on 'iftop', when take example '1.2.3.4' source ip cant receive (but 'iftop' on server-1 still says has been send). i read lot of stuff , says no problem fake source ip of udp packet, i'm wondering doing wrong. tried in python , didn't receive too. /* raw udp sockets */ #include<stdio.h> //for printf #include<string.h> //memset #include<sys/socket.h> //for socket ofcourse #include<stdlib.h> //for exit(0); #include<errno.h> //for errno - error number #include

In Protractor, how can I skip failed test cases and continue remaining test cases -

for example, in set of 10 test cases, 1 test in particular expects condition failing. in case how can stop executing test case further, or should continue execute remaining test cases? jasmine supports pending() function. if call pending function in specs, spec marked pending.in case 1 of expectation failing put pending function before that! describe('test', function() { it('skip spec', function() { if (someskipcheck()) { pending(); } expect(1).tobe(2); // expect failing }); for more details can refer jasmine pending function - http://jasmine.github.io/2.0/introduction.html#section-pending_specs

mysql - Show current user as "Me" in select tag -

i have used below-written code select users def user_for_select user.pluck(:name, :id).unshift(['all', 'all']) end but want display current user's name "me" in select tag. you can like: def user_for_select user .pluck("case when id = #{current_user.id} 'me' else name end name, id") .unshift(['all', 'all']) end tested in own rails console (rails 4.2.6): admin.pluck("case when id = #{u.id} 'me' else full_name end name, id").unshift(['all', 'all']) # (0.6ms) select case when id = 7 'me' else full_name end name, id "admins" # => [["all", "all"], ["arup rakshit", 1], ["me", 7], ["pinaki das", 2], ["mina das", 3], ["proloy das", 4], ["mouli roy", 5], ["pisi das", 6]] edit: if method class method below. class user < ar class << self

javascript - Components gets the wrong props when clicking links in React-router -

i'm working on simple user page each user has own profile. profile page works on initial load. however, if viewing profile of user1 click link take me user2 , profile page still load user1 because this.props.params haven't updated yet. if click link twice, profile of user2 show up. need getting work correctly here, code speaks more words: var { router, route, redirect, indexroute, indexlink, link, hashhistory, browserhistory } = reactrouter; var browserhistory = reactrouter.browserhistory; var profile = react.createclass({ getinitialstate: function() { return { username: '', userid: '', displayname: '' }; }, setprofile: function() { $.post('/api/v1/rest/getuser', {username: this.props.params.name}, function (result) { if(!result.error) { this.setstate({ username: result.seo_name, userid: resul

Rails way to query on array inside JSON data type -

i have column in table json data type storing array. migration class addeditsummarytoposts < activerecord::migration def change add_column :posts, :edit_summary, :json end end post class post < activerecord::base serialize :edit_summary, json end this how data stored: :id => 2, :edit_summary => [ { "user_id" => 56, "date" => "2016-08-09t07:46:04.555-04:00" }, { "user_id" => 57, "date" => "2016-08-08t06:35:44.345-04:00" }, ] i referred this post , wrote query working fine select * posts, json_array_elements(edit_summary) elem elem->>'date' between '2016-08-07 00:00:00' , '2016-08-10 23:59:59'; now question there way same rails way? you can execute same query in rails providing raw sql conditions. however, feel edit summaries belong relation instead. a post has_many editsummary , benefits: you'l

python - random module's randrange not working in pygame -

Image
i trying make game in pygame , want add apples @ random places random module not working. tried looking online guy there able use without problem my code , output down below impoort pygame imporrt random pygame.init() display_width = 1000 display_height = 500 gamedisplay = pygame.display.set_mode((display_width,display_height)) pygame.display.set_caption("slikisnake") clock = pygame.time.clock() fps = 15 block_size = 10 def gameloop(): lead_x = display_width/2 lead_y = display_height/2 lead_x_change =0 lead_y_change =0 randapplex = random.randint(0, display_width - block_size) randappley = random.randint(0 ,display_height - block_size) pygame.display.update() gameexit = false gameover = false while not gameexit: while gameover == true: gamedisplay.fill(white) message_on_screen("game over,press r start again or q quit", black) pygame.display.update()

Get list of extended classes in TypeScript -

i have: classa classb extends classa classc extends classb i created object on classc: var myclassc= new classc(); classa has method: public classname(): string { var funcnameregex = /function (.{1,})\(/; var results = (funcnameregex).exec(this["constructor"].tostring()); return (results && results.length > 1) ? results[1] : ""; } which returns "classc" string if call myclassc.getclassname(); what need list of classes base class: classc, classb, classa. there way this? yeah, indeed possible: function getclassname(obj: any): string { var funcnameregex = /function (.{1,})\(/; var results = (funcnameregex).exec(obj.constructor.tostring()); return (results && results.length > 1) ? results[1] : ""; } class classa { public classname(): string[] { let classnames = []; let obj = object.getprototypeof(this); let classname: string; while ((clas

sql server - A tricky query to update the table with values of another table -

Image
this question extension of previous 1 available @ unable know exception in query . this time i've table named breaks. and looks below. i'm able column sum using below query. select dateadd(second, sum(datediff(second, '19000101', totalbreaktime)), '19000101') userid = 0138039 , convert(date, starttime) = convert(date, getdate())) t breakstable; my second table looks below. this time, want update breaks column sum of totalbreaktime breaks table(the first screenshot) , condition has date current day. i'm unable understand how this. you need merge : merge secondtable target using ( select userid, sum(datediff(second, '19000101', totalbreaktime)) columnwithbreakscount breakstable convert(date, starttime) = convert(date, getdate())) group userid) source on target.userid = source.userid when matched update set breaks = source.columnwithbreakscount but work if have 1 column each userid

html - cant get custom data attributes value in jquery -

<input type="submit" value="+" data-commentid="{{ $comment->id }}" data-postid="{{ $post->id }}" data-likes="{{ $comment->likes }}" class="likebtn increment"> jquery like $('.likebtn').on('click', function(e) { e.preventdefault(); // commentidとpostidもhtmlから取ってくる commentid = parseint($('this').attr('data-commentid')); console.log(commentid); postid = parseint($('this').attr('data-postid')); console.log(postid); likes = parseint($('this').attr('data-likes')); console.log(data-likes); like_function(commentid, postid, likes, $('this')); }); in console see these variables returns nan. wrong? do not use quotations around this. $(this) notice no quotations.

java - ProxyFactoryBean class has no defination for CommonsPool2TargetSource? -

i'm facing trouble while creating pool pojo class. here code snippet: @bean public commonspool2targetsource pooltargetsource() { commonspool2targetsource commonspool2targetsource = new commonspool2targetsource(); commonspool2targetsource.setminidle(5); commonspool2targetsource.setmaxsize(50); commonspool2targetsource.settargetclass(jiotuurl.class); return commonspool2targetsource; } @bean public proxyfactorybean proxyfactorybean() { proxyfactorybean proxyfactorybean = new proxyfactorybean(); proxyfactorybean.settargetsource(pooltargetsource());//the type org.apache.commons.pool2.pooledobjectfactory cannot resolved. indirectly referenced required .class files return proxyfactorybean; } @bean public methodinvokingfactorybean poolconfigadvisor() { methodinvokingfactorybean poolconfigadvisor = new methodinvokingfactorybean(); poolconfigadvisor.settargetobject(commonsp

php - Adwords API ReportDefinitionService: ReportDefinition not found -

if : $user->getservice('managedcustomerservice'); $customer = new \managedcustomer(); this works, if do: $user->loadservice('reportdefinitionservice'); $report = new \reportdefinition(); i receive error: class 'reportdefinition' not found. (i write on yii2, use api v201607) what did wrong? =========== fix ================= i temporary made working adding: require_once dirname(dirname(dirname(__file__))) . '/vendor/googleads/googleads-php-lib/examples/adwords/v201607/init.php'; require_once adwords_util_version_path . '/reportutils.php'; you can't create reports reportdefinitionservice since api version v201109 . use ad-hoc reports instead.

Unable update UILable using dispatch_async in swift iOS -

i setting json string value uilabel using dispatch_async method. unable show updated value , when printing label text, showing updated value. here code- dispatch_async(dispatch_get_main_queue(), { self.extract_json(data!) }) func extract_json(jsondata:nsdata) { let json: anyobject? { json = try nsjsonserialization.jsonobjectwithdata(jsondata, options: []) print("full data \(json!)") } catch { json = nil return } let user_object = json!["opportunity_master"] as! nsarray let data_block = user_object[0] as? nsdictionary self.opp_title = (data_block!["opportunity_title"] as? string)! print(self.opp_title) <-- **here updating uilabel**--> self.event_title.text = self.opp_title self.event_title.setneedsdisplay() print("event title label \(self.event_title.text)") } i unable update values, please su

asp.net mvc - How to render .cshtml as Email Body using SendGrid+MVC4? -

i trying send email, normal email able send. have send template(.cshtml) in email. please tell me how can this. here code: controller: public actionresult sendemaildeviceinfodisplay(list<string> devicedataildata) { string body = ""; var emailcontoller = new emailcontroller(); string email = devicedataildata[9]; body = "<html>event name: " + devicedataildata[0] +"</html>"; var sendemail = emailcontoller.senddeviceandeventinfomail(email, body); viewbag.info = devicedataildata[8]; return partialview("sendemailconformationdisplay"); } sendgrid method: public string senddeviceandeventinfomail(string email, string body){ var mymessage = new sendgridmessage(); mymessage.from = new mailaddress("anita.mehta@test.com"); list<string> recipients = new list&l

webdriver warning the server did not provide any stacktrace information -

i have written driver.findelement(by.id("kfidocumentlink")).click(); code clicking on button 'kfi document'. please find html code. <a class="button" id="kfidocumentlink" href="/quote/kfidocument/the%20co-operative%20bank%20-%20download%20mortgage%20illustration%20(pdf)%20160808104103" target="_blank">download mortgage illustration (pdf)</a> when run code, able click on button , unable click button. could assist on please? actually time when goes find element, not present on dom @ time due slow internet or other reason, that's why sometime able click , sometime not. to overcome issue should try using webdriverwait expectedconditions.elementtobeclickable wait before click on element until element visible on dom , clickable below :- webdriverwait wait = new webdriverwait(driver, 10); el = wait.until(expectedconditions.elementtobeclickable(by.id("kfidocumentlink"))); el.click

android - How to set max-height of ImageView at runtime -

how set max height of imageview @ runtime? for example, have image url , has width greater screen width. want set imageview height screen's width , make imageview square. i can't find perfect solution this. appreciated deeply. it doesn't matter size of image, code below size perfect ratio, make max width without making resolution suck.if dont want max width modify dimensions code. ll need picasso. private dimensions getscreendimensions() { displaymetrics metrics = new displaymetrics(); windowmanager wm = (windowmanager) context.getsystemservice(context.window_service); display display = wm.getdefaultdisplay(); display.getmetrics(metrics); final int widthscreen = metrics.widthpixels; int heightscreen = metrics.heightpixels; dimensions screendimen = new dimensions(metrics.widthpixels,metrics.heightpixels); // custom class return screendimen; } private bitmap makecalc(dimensions screendimen, dimensions imagedimen,b

ios - FBX parse for openGL Display -

i want parse fbx file , display via opengl on iphone. try parse *.fbx format using fbx sdk autodesk . found link useful, still have misunderstanding - guess indices receive incorrect. create simple cube in blender , export file in *.fbx . if open file via fbx review app - displayed perfect, when try draw cube - looks data parse incorrect/or partial. to indices use next code int numindices = pmesh->getpolygonvertexcount(); int *indices = new int [numindices]; indices = pmesh->getpolygonvertices(); int polygoncount = pmesh->getpolygoncount(); int totalobjsize = 0; (int = 0; < polygoncount; ++i) { totalobjsize += pmesh->getpolygonsize(i); } result: ----indices----24---: 0 1 2 3 4 7 6 5 0 4 5 1 1 5 6 2 2 6 7 3 4 0 3 7 ----coordinates(vertises)----72 1 1 -1 1 -1 -1 -1 -1 -1 -1 1 -1 1 0.999999 1 -1 1 1 -1 -1 1 0.999999 -1 1 1 1 -1 1 0.999999 1 0.999999 -1 1 1 -1 -1 1 -1 -1 0.999999 -1 1 -1 -1 1 -1 -1 -1 -1 -1 -1 -1 -1 1 -1 1 1 -1 1

Android card view error on touching Card view -

Image
i want toast message on touching each card card name: xml code on android <relativelayout android:layout_width="match_parent" android:layout_height="match_parent"> <imageview android:id="@+id/thumbnail" android:layout_width="match_parent" android:layout_height="@dimen/album_cover_height" android:background="?attr/selectableitembackgroundborderless" android:clickable="true" android:onclick="clikimage" android:scaletype="fitxy" /> java code public void clikimage(view view){ toast.maketext(mainactivity.this, "cliked", toast.length_short).show(); } in code same toast coming each card.. the texts came code . . /** * adding few albums testing */ private void preparealbums() {

c# - How to see which string threw a FormatException? -

i have method parses currency strings (such "€4.00" or "$14.50"), there parsing error, , throws formatexception . what want do, send string couldn't parsed (threw exception) database. try { string euronumber = "€4.00"; // throw formatexception double parsednumber = double.parse(euronumber, numberstyles.currency); } catch (formatexception ex) { string stringthatthrewtheexception; // should "€4.00" in case // [omitted] sending server logic } is somehow possible? or should use kind of hack? thank in advance. as bugfinder said, can use tryparse: double parsednumber; var result = double.tryparse(euronumber, numberstyles.currency, cultureinfo.currentculture, out parsednumber); if (!result) { // send error } another alternative move string outside of scope of try block: string euronumber = "€4.00"; try { // throw formatexception double parsednumber = double.p

octave - How to calculate the Hamming weight for a vector? -

i trying calculate hamming weight of vector in matlab. function hamming_weight (vet_dec) ham_weight = sum(dec2bin(vet_dec) == '1') endfunction the vector is: hamming_weight ([208 15 217 252 128 35 50 252 209 120 97 140 235 220 32 251]) however, gives following result, not want: ham_weight = 10 10 9 9 9 5 5 7 i grateful if me please. you summing on wrong dimension! sum(dec2bin(vet_dec) == '1',2).' ans = 3 4 5 6 1 3 3 6 4 4 3 3 6 5 1 7 dec2bin(vet_dec) creates matrix this: 11010000 00001111 11011001 11111100 10000000 00100011 00110010 11111100 11010001 01111000 01100001 10001100 11101011 11011100 00100000 11111011 as can see, you're interested in sum of each row, not each column. use second input argument sum(x, 2) , specifies dimension want sum along. note approach horribly slow, can see this question . edit for valid, , meaningf

c - What counts as character type in C11? -

what belongs "character type" in c11 — besides char of course? to more precise, special exceptions character type (for example any object can accessed lvalue expression of character type — see §6.5/7 in c11 standard), concrete types apply? seem apply uint8_t , int8_t stdint.h , guaranteed? on other hand gcc doesn't regard char16_t uchar.h "character type". only char , signed char , unsigned char 1 . the types uint8_t , int8_t , char16_t , or type in form intn_t or charn_t , may or may not synonyms character type. 1 (quoted from: iso/iec 9899:201x 6.2.5 types 15) 3 types char, signed char, , unsigned char collectively called character types.

python - Why does scipy.optimize.curve_fit not fit correctly to the data? -

Image
i've been trying fit function data while using scipy.optimize.curve_fit have real difficulty. can't see reason why wouldn't work. # encoding: utf-8 __future__ import (print_function, division, unicode_literals, absolute_import, with_statement) import numpy np scipy.optimize import curve_fit import matplotlib.pyplot mpl x, y, e_y = np.loadtxt('data.txt', unpack=true) def f(x, a, k): return (1/(np.sqrt(1 + a*((k-x)**2)))) popt, pcov = curve_fit(f, x, y, maxfev = 100000000) mpl.plot(x, f(x, *popt), 'r-', label='fit') mpl.plot(x, y, 'rx', label='original') mpl.legend(loc='best') mpl.savefig('curve.pdf') print(popt) # correct values should calculated # a=0.003097 # k=35.4 here plot-image produced upper code: data.txt: #x y e_y 4.4 0.79 0.13 19.7 4.9 0.8 23.5 7.3 1.2 29.7 17

Wordpress install plugin redirect me to dashboard -

when finding plugin , clicking on install now, being redirected dashboard , can't install pluging. happen when try upload plugin zip too. download plugin , put extract wordpress plugins directory , go wp-admin plugin , activate .

python - Getting variable from other class -

as totally beginner need ask help. defined class config take config.ini file information , put them variable. define class : connection, base of result class config. trying many ways, give up. take ? class config: def __init__(self,system): self.config = configparser.configparser() self.config.read("config.ini") self.connection_source=self.config.get(system,'source') self.system=system def getsystemsources(self): return self.connection_source def getconnection(self,source): self.source=source self.connection_string=self.config.get('connection',self.system+'_'+source+'_'+'connectstring') ## connection self.connection_user=self.config.get('connection',self.system+'_'+source+'_'+'user') ## connection user self.connection_password=self.config.get('connection',self.system+'_'+source+'_'+&

c# - Licensing Asp.Net application with Portable.Licensing -

i need protect asp.net web api 2.2 application using portable.licensing . have organized application creating multiple asp.net areas . ex: core accounting human resource inventory i need licence each , every areas. if customer has purchased accounting module, should able access accounting functionality. otherwise have display error message. and generate unlike machine key protect software piracy. so how can use portable licensing asp.net areas? where/at point license needs validated? could 1 please me achieve requirement providing instructions? providing sample code highly appreciated!. for wandering same thing: well, basically, how implement licensing in application - depends! no silver bullet, always. i spent half of day studying portable.licensing , that's comes mind: in portable.licensing have "withproductfeatures" method in fluent api adding custom data license, , areas - product features. insert check - depends on number of factors:

html5 - How to debug "No database selected" error using MySQL and PHP? -

Image
i face error error: insert biodata('fname', 'lname', 'email', 'phone', 'message') values('syed', 'masroor', 'masroor_toori@yahoo.com', '0215586484', 'dhflhdfvh',) no database selected sql query: i have made database here: connect db connection properly $link = mysql_connect('localhost', 'mysql_user', 'mysql_password'); $db_selected = mysql_select_db('db_name', $link);

How to check mapped network drive if exist by hostname C# -

i have problem in code c#. can not check mapped network drive if exist host name. can check ip address ping function. actual problem not ip address. need check hostname. ping ping = new ping(); var reply = ping.send("ads-201"); if (reply.status == ipstatus.success) { networkdrive onetdrive = new networkdrive(); onetdrive.localdrive = "z:"; onetdrive.sharename = "\\\\ads-201\\fileserver\\public"; onetdrive.mapdrive(); } this answer: friend figure out, sharing needs it. var searcher = new managementobjectsearcher( "root\cimv2", "select * win32_mappedlogicaldisk"); list gunler = new list(); try { while (true) { thread.sleep(60 * 1 * 100); gunler.clear(); foreach (managementobject queryobj in searcher.get()) { gunler.add(quer