Posts

Showing posts from June, 2015

Problems while writing decimal doubles onto a .csv file C++ -

Image
i have program reads test .csv file row row , gives standard deviation & mean of every row. goes on write new .csv file including sd, average, , original values of every row. #include <iostream> #include <string> #include <fstream> #include <sstream> #include <stdlib.h> #include <math.h> #define rows 100 #define columns 11 using namespace std; void read(int data[rows][columns]) { string str; ifstream ifile; string filename="testdatain.csv"; ifile.open(filename); if (ifile) { int = 0; while (getline (ifile,str)){ stringstream ss(str); string temp; for(int j=0;j<columns;j++){ getline(ss,temp,','); data[i][j]=atoi(temp.c_str()); } i++; } cout << "finished reading data." << endl; }else { cout << "error reading." <<endl; ...

javascript - Drop down menu Validation on button press w/ Alert -

the user should select 1 of options in drop down menu before proceeding form. "next button" should send alert if no option selected. both yes , no should allow next button work. need javascript this. here html: <fieldset> <h2 class="fs-title">past history </h2> <h3 class="fs-subtitle">please select 1 of following</h3> <div> <select name="past" id="past"> <option value=""disabled selected>select one</option> <option value="a">yes</option> <option value="b">no</option> </select> </div> <br> <input type="button" name="previous" class="previous action-button" value="previous" /> <input type="button" name="next" class="next action-button" id="nextpast" value="nex...

PHP Shopping Cart duplicate Items when adding to cart using Sessions and Arrays -

help me don't have more solutions. simple want need items separated correctly without duplicating here code here pic: click on shopping cart pic order button: <?php session_start(); if(isset($_get['btnbuy'])) { $_session['cartdesc'][$_session['ctr']] = $_session['desc'][$_session['indexnum']]; $_session['cartprice'][$_session['ctr']] = $_session['price'][$_session['indexnum']]; $_session['cartquant'][$_session['ctr']] = $_get['txtquant']; $_session['ctr'] = $_session['ctr']+1; //here when duplicate happpens! header("location: index.php"); } ?> here add cart button <?php if(isset($_get['cmdadd0'])) $_session['indexnum'] = 0; elseif(isset($_get['cmdadd1'])) $_session['indexnum'] = 1; elseif(isset($_get['cmdadd2'])) $_s...

windows - In the Microsoft error message, "the specified module could not be found", what exactly is meant by "module" and "specified"? -

is "module" dll file? or inside dll file? "specified" name shown in error message? or how find out microsoft means "specified"? what happen if microsoft changed error message "can't find xyz.dll"? make harder or easier understand error message? i'm trying understand microsoft's logic in decisions use words "module" , "specified", because noticed huge number of questions error message, year after year, , nobody ever seems clear on means.

Python source code compiling on linux -

i got linux os , i'm trying compile python source code new linux os. if helps, os tails can https://tails.boum.org/ if need have @ it. first off, welcome linux world. okay, 1 thing note, unix based operating systems come standard python built-in. because python major language tools in linux. open terminal ctrl+alt+t , type python , hit enter. put in python interactive terminal. you need install ide python. spyder 1 python based. use sublimetext .

ios - ordering array with another array -

Image
i have following categorynames array. and now, have categorytempelements , has cname property. need know how order categorytempelements order of categorynames . update : have added sortorder property category object , tried following order not change. for (category* in categorytempelements) { int index = (int)[categorynames indexofobject:a.cname]; a.sortorder = index; } nssortdescriptor *sortdescriptor = [[nssortdescriptor alloc] initwithkey:@"sortorder" ascending:yes]; nsarray *sortdescriptors = [nsarray arraywithobject:sortdescriptor]; nsarray *sortedarray = [categorytempelements sortedarrayusingdescriptors:sortdescriptors]; you need first convert categorynames array dictionary nsstring key , nsnumber int value, value order in array //this example code, first array (reference value array) nsarray * array = @[@"prueba",@"prueba2",@"prueba3"]; //first need convert array in nsdictionary nsmutabledi...

Wrong json format for htmlBody swift -

when try create json dictionary wrong format semicolon instead of commas json let jsondata = try? jsonserialization.data(withjsonobject: params) params dictionary. tried using options: .prettyprinted same result { "key": "value"; "key": "value" } instead of { "key": "value", "key": "value" } i tried read file same result semicolon :( update full code: let params: dictionary<string, string> = ["country":"a" ,"language":"a" ,"query":"some query" ,"context": "null"] let baseurl = "someurl" let url = url(string: baseurl)! var request = urlrequest(url: url) request.httpmethod = "post" { request.httpbody = try jsonserialization.data(withjsonobject: params, options: .prettyprinted) print(try? jsonserialization.jsonobject(with: request.httpbody!)) } catch let e...

RestAPi calling using Java code, need to write connections in separate code -

i wanted hide http connections using class http connections , wanted reduce code. can me doing this? public class exportgroups { public static void main(string[] args) { try { string username = "username"; string password = "pass@word123"; string userpassword = username + ":" + password; string encoding = new sun.misc.base64encoder().encode(userpassword.getbytes()); url url = new url("https://agilepointserver/extension/exportgroups"); httpurlconnection conn = (httpurlconnection) url.openconnection(); conn.setdooutput(true); conn.setrequestproperty("authorization", "basic " + encoding); conn.setrequestmethod("post"); conn.setrequestproperty("content-type", "application/json"); string input = "{\"groupnames\": [\"accounts payable\...

javascript - Jquery append() on inner div while expanding the outer div so that the inner div elements fits inside -

i have div structure similar this. i'm using jquery append elements inside div id append. however, outer div doesn't expand automatically fit appended elements. <div class="well" id='expand'> <div class="container"> <!-- other divs --> </div> <div id= "append"> </div> </div i solved issue increasing height of outer div i.e. var div_height = $('#expand').height(); $('#expand').css({"height":div_height + append_height}) is there better way this? you pure css using min-height , height:auto causes expand div adjust height according content: #expand{ height:auto; min-height:50px; height:auto !important; /* ie not support min-height */ } also add height:auto !important; child element mobile support.

actionscript 3 - How to navigateToURL from Flex application contained within an Adobe AIR wrapper? -

i have flex application loaded air htmlloader. flex application displays link when clicked, calls navigatetourl(...) , displays new browser window. functionality works flex application, nothing when wrapped in air. are loading flex app disk? might in local-with-file sandbox . have @ this: http://help.adobe.com/en_us/as3/dev/ws5b3ccc516d4fbf351e63e3d118666ade46-7cba.html here's excerpt documentation link above. home / actionscript 3.0 developer’s guide / networking , communication / http communications opening url in application flash player 9 , later, adobe air 1.0 , later can use navigatetourl() function open url in web browser or other application. content running in air, navigatetourl() function opens page in default system web browser. urlrequest object pass request parameter of function, url property used. first parameter of navigatetourl() function, navigate parameter, urlrequest object (see using urlrequest class). second optional window parameter, in ...

Notice: Undefined index: txtQuant - PHP Textbox is undefined using SESSIONS -

notice: undefined index: txtquant in e:\wamp\www\shoppingcartv4\cartv4.php on line 8 notice: undefined index: txtquant in e:\wamp\www\shoppingcartv4\cartv4.php on line 56 my update code: if(isset($_get["update"])) { $i = $_get["update"]; $_session["qnty"] = $_get["txtquant"]; $_session["amounts"][$i] = $_session["qnty"][$i]; } my html code <?php if(!empty($_session["products"])){ ($i=0; $i< count($_session["products"]); $i++) { ?> <tr> <td><?php echo($_session["products"][$i]); ?></td> <td width="10px">&nbsp;</td> <td><input type="text" name="txtquant[]"></td> <td width="10px">&nbsp;</td> <td><?php echo($_session["amounts...

java - targetsdk 3 show my elements of my game larger -

i have game "battle earth" here: https://www.codester.com/items/287/battle-for-earth-android-game-source-code in game target sdk 3 , when targetsdk 3 screen full screen , every button ads shows in large size. when set target sdk above , elements size normall game screen make small in corner of screen. want set targetsdk 22, why behavior happen?and reason ?

Change the style of an array of String inside a TextView - swift - EDIT -

my first question how change font of word example "test" in textview, , answered correctly @bkrl , @torongo. func changealloccurence(of string: string, font: uifont) -> nsattributedstring { let attributedstring = nsmutableattributedstring(string: self) var range = nsmakerange(0, attributedstring.mutablestring.length) while(range.location != nsnotfound) { range = attributedstring.mutablestring.range(of: string, options: .caseinsensitive, range: range) if(range.location != nsnotfound) { attributedstring.addattribute(nsfontattributename, value: font, range: range) range = nsmakerange(range.location + range.length, self.characters.count - (range.location + range.length)); } } return attributedstring } as still not familiar above code, tried add few lines in order generalize code can works array of strings ...

How to check spellings and Autocorrect the wrong spelling by json (wordlist is in json format) in html -

how check spellings of paragraph , autocorrect wrong spelling json (wordlist in json format) , print in new table after correcting in html mydataj.json { "description": "common english words.", "commonwords": [ "a", "able", "about", "absolute", "accept", "account", "achieve", "across", "act", "active", "actual", "add", "address", "admit", ] } you can use these libraries after parsing json file spellcheck. http://www.languagetool.org/usage/ jazzy ( http://jazzy.sourceforge.net/ ) or can write own spellchecking library , use work. http://norvig.com/spell-correct.html

tensorflow - Saving tf.trainable_variables() using convert_variables_to_constants -

i have keras model convert tensorflow protobuf (e.g. saved_model.pb ). this model comes transfer learning on vgg-19 network in , head cut-off , trained fully-connected+softmax layers while rest of vgg-19 network frozen i can load model in keras, , use keras.backend.get_session() run model in tensorflow, generating correct predictions: frame = preprocess(cv2.imread("path/to/img.jpg") keras_model = keras.models.load_model("path/to/keras/model.h5") keras_prediction = keras_model.predict(frame) print(keras_prediction) keras.backend.get_session() sess: tvars = tf.trainable_variables() output = sess.graph.get_tensor_by_name('softmax:0') input_tensor = sess.graph.get_tensor_by_name('input_1:0') tf_prediction = sess.run(output, {input_tensor: frame}) print(tf_prediction) # matches keras_prediction if don't include line tvars = tf.trainable_variables() , tf_prediction variable wrong , doesn't match output keras_...

android: device not supported by app- why? -

Image
i developing camera app. 1 of users complaining device not supported. it's acer a200 : i don't see reason why android market / google play marks app not supported device. know might reason? here manifest: <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="net.ttttrash.myapp" android:versioncode="32" android:versionname="3.2" > <application android:icon="@drawable/icon" android:label="@string/app_name" android:hardwareaccelerated="true"> <activity android:name=".cameraactivity" android:configchanges="keyboard|orientation|keyboardhidden" android:label="@string/app_name" android:windowsoftinputmode="adjustpan" > <intent-filter> ...

heroku - Public Directory Not Being Served With Sinatra -

Image
as title says, cannot heroku use public assets. locally, when running app shotgun works. rackup (what heroku uses), css , assets 404. i've tried bunch of answers on here ( one , two , three ) none have worked. here's directory structure: my config.ru: require 'bundler' bundler.require require file.expand_path('../config/environment', __file__) run bikeshareapp and controller: class bikeshareapp < sinatra::base '/' erb :'home/index' end '/stations' @stations = station.all erb :'stations/index' end end edit: how i'm referencing assets way <link href="/css/bootstrap.min.css" rel="stylesheet"> <link href="/css/overwrite.css" rel="stylesheet"> found it. following this guide , putting in config.ru worked: run lambda { |env| [ 200, { 'content-type' => 'text/html', 'cache-...

codeigniter url routing with query string -

i have 2 url in project http://example.com/one.html http://example.com/one.html?param1=value&param2=value in route file have rules below $route['search/one?(:any)'] = 'advance_search/books'; $route['search/one'] = 'advance_search/index'; when call 2nd url query string still call index method. 1 fix wrong. try route like http://example.com/index.php/controller_name?param1=value&param2=value controller has php file make sure first letter upper case on class , file name. controllers/one.php <?php class 1 extends ci_controller { public function index() { echo $this->input->get('param1'); } } if need remove index.php try of these htaccess https://github.com/wolfgang1983/htaccess_for_codeigniter

python - Are global variables thread safe in flask? -

in app state of common object changed making requests, , response depends on state. class someobj(): def __init__(self, param): self.param = param def query(self): self.param += 1 return self.param global_obj = someobj(0) @app.route('/') def home(): flash(global_obj.query()) render_template('index.html') if run on development server, expect 1, 2, 3 , on. if requests made 100 different clients simultaneously, can go wrong? expected result 100 different clients each see unique number 1 100. or happen: client 1 queries. self.param incremented 1. before return statement can executed, thread switches on client 2. self.param incremented again. the thread switches client 1, , client returned number 2, say. now thread moves client 2 , returns him/her number 3. since there 2 clients, expected results 1 , 2, not 2 , 3. number skipped. will happen scale application? alternatives global variable should at? yo...

java - Hibernate QuerySyntaxException when using annotations for mapping -

i have database table named user , model class named user annotated @entity using javax.persistence . when try query user following exception: severe: servlet.service() servlet [jersey web application] in context path [/myapp] threw exception [java.lang.illegalargumentexception: org.hibernate.hql.internal.ast.querysyntaxexception: user not mapped [from user u u.username = :username]] root cause org.hibernate.hql.internal.ast.querysyntaxexception: user not mapped @ org.hibernate.hql.internal.ast.util.sessionfactoryhelper.requireclasspersister(sessionfactoryhelper.java:171) @ org.hibernate.hql.internal.ast.tree.fromelementfactory.addfromelement(fromelementfactory.java:91) @ org.hibernate.hql.internal.ast.tree.fromclause.addfromelement(fromclause.java:79) @ org.hibernate.hql.internal.ast.hqlsqlwalker.createfromelement(hqlsqlwalker.java:324) @ org.hibernate.hql.internal.antlr.hqlsqlbasewalker.fromelement(hqlsqlbasewalker.java:3696) @ org.hibernate.hql.inter...

How do I know Scrapy custom settings are applied? Log shows general settings -

i use scrapy 1.3 according documentation can declare settings each specific spider simple enough. here code class bhspider(scrapy.spider): name = "code" custom_settings = {'concurrent_requests' : '20', 'feed_export_fields' :['price', 'stock','partnumber','sku', 'name' ,'manufacture','attribute','distributor','upc','descr', 'p_url','main_image','images']} allowed_domains = *** but according logs project settings used. how know project settings overcomed specific spider settings? here log 2017-08-20 13:47:51 [scrapy.utils.log] info: scrapy 1.3.2 started (bot: pc) 2017-08-20 13:47:51 [scrapy.utils.log] info: overridden settings: {'newspider_module': 'pc.spiders' , 'feed_uri': 'test_output1.csv', 'concurrent_requests': 200, 'spider_modules': ['pc.spiders'], ...

css - navbar dropdown menus display issue on mobile and small devices with media query -

not big expert in css , responsiveness design, try collapse navbar using media query. issue dropdown menus, responsive design not applied correctl : dropdown menus displayed on large desktop device. what want : result expected but result obtain : current result my code following : <nav class="navbar navbar-default"> <div class="container-fluid"> <!-- brand , toggle grouped better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1"> <span class="sr-only">toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class=...

java.lang.IllegalStateException: Failed to load ApplicationContext error java spring-boot -

Image
okay went through lot of answers problem still unsolved. trying test controller - @controller @produces(mediatype.application_json) @requestmapping(value = "/verify/email") public class emailcontroller { @autowired private byemail strategy; @autowired private applicationconfig config; @responsebody @requestmapping(method = requestmethod.post, produces = mediatype.application_json) public request newrequest(@requestbody vrequest request) throws ioexception { log.info(request.tostring()); system.out.println(request.tostring()); request.settype(vtype.email); optional<request> response = strategy.processrequest(request); return response.orelsethrow(badrequestexception::new); } and test - @runwith(springrunner.class) @autoconfiguremockmvc @webappconfiguration @springboottest public class testemailcontroller { @mock private byemail strategy; @injectmocks @autowired private emailcontroller controller; @autowired private mockmvc mockmvc; ...

Ruby on Rails - Joins models for getting notifications -

in application have models user , post , notification , postshare & socialpage . this how i've models associations: class user < activerecord::base has_many :social_pages has_many :posts class post < activerecord::base has_many :post_shares has_many :notifications belongs_to :user class notification < activerecord::base belongs_to :post class postshare < activerecord::base belongs_to :post belongs_to :social_page class socialpage < activerecord::base belongs_to :user has_many :post_shares when notifications added, i'm adding post_id table. what want achieve is, based on post_id notifications , want find post_shares post_id & find social_pages_id & based social_page_id find user has own/created page , show them notifications. i've tried joins notification.joins(:post).group(:post_id).select(:post_id) , don't correct. any appreciated! rails nested includes or nested joins on activere...

c# - Select deeply nested node in html agility pack? -

i'm parsing html files contain many nodes same node, under 1 of nodes , several layers of nodes there's node want access. has unique attribute value i'd use try , 'find' node. if not possible can go through nodes regardless of nesting? doc.documentnode.descendants() goes immediate child. any ideas how this?

angular - Embed pdf in Angular2 component -

in angular 4.3 want open modal popup , show embedded pdf file, shown here: https://pdfobject.com/static.html i used modal popup component answer pops nicely. test html modal looks this: <a class="btn btn-default" (click)="setcontent();modal.show()">show</a> <app-modal #modal> <div class="app-modal-header"> testing pdf embedding </div> <div class="app-modal-body"> <div class="embed-responsive" *ngif="contenturl"> <object [attr.data]="contenturl" type="application/pdf" class="embed-responsive-item"> <embed [attr.src]="contenturl" type="application/pdf" /> </object> </div> <p><a [href]="contenturl">pdf download</a></p> </div> <div class="app-modal-footer"> <...

java - PushBackInputStream and DataInputStream, how to push back a double? -

if want read ahead byte,and push if not '<',i can this: pushbackinputstream pbin=new pushbackinputstream(new fileinputstream("1.dat")); int b = pbin.read(); if(b!='<') pbin.unread(b); but if want push double read datainputstream,what shall do? example: pushbackinputstream pbin1=null; datainputstream din=new datainputstream( pbin1=new pushbackinputstream( new fileinputstream("1.dat") ) ); double d = din.readdouble(); pbin1.unread(d); the last line pbin1.unread(d); can not compiled,because pushbackinputstream can not push double,how can convent double byte array?or other way? you can't push double way. method datainputstream.readdouble() reads 8 bytes create double, can't pass double pushbackinputstream.unread() , expect him know how deal with. to achieve want solution simple: pushbackinputstream pbin1=new pushbackinputstream(new fileinputstrea...

javascript - Self reference in $.fn jquery -

is there anyway can refer "mousewheelevent" property "beforeslide" method? $(document).ready( function() { $(".main").hide(); var des = false; var scorll = false; var slider = $.fn.fsvs({ speed : 1000, bodyid : 'fsvs-body', selector : '> .slide', mouseswipedisance : 40, afterslide : function(){}, beforeslide : () => { if($("#slide-3").hasclass("active-slide") && !des){ $('#fsvs-body').bind('mousewheel', function(e){ if(e.originalevent.wheeldelta /120 > 0) { console.log("up"); } else{ $(".main").fadein(200, function(){ $("html").addclass("des"); $("#fsvs-body").addclass("des"); des = true; scorll = ...

java - How to re-apply or re-render my JTable after editing the JTable's JSpinner cell -

Image
i have problem on applying defaulttablerenderer jtable set contain jspinner , jcombobox through use of defaultcelleditors i have created simple defaulttablerenderer checks if there's duplicate time or invalid time value shown below. public class scheduletablecellrenderer extends defaulttablecellrenderer { @override public component gettablecellrenderercomponent( jtable table, object value, boolean isselected, boolean hasfocus, int row, int col) { component cellcomponent = super.gettablecellrenderercomponent(table, value, isselected, hasfocus, row, col); object starttimevalue = table.getmodel().getvalueat(row, 1); object endtimevalue = table.getmodel().getvalueat(row,2); if(starttimevalue!= null && endtimevalue != null && starttimevalue.tostring().equals(endtimevalue.tostring()) ){ system.out.print("start time: "+starttimevalue+", ...

python - Speeding up email attachment checking -

my script checks email attachments , downloads them if contain strings ever slow right now.. there way speed up? right it's downloading entire email believe... my script: def connect(server, user, password): m = imaplib.imap4_ssl(server, 993) print("connect imap") m.login(user, password) print("logged in") m.select() return m def downloaattachmentsinemail(m, emailid, outputdir): resp, data = m.fetch(emailid, "(body.peek[])") email_body = data[0][1] mail = email.message_from_string(email_body.decode('utf8','ignore')) if mail.get_content_maintype() != 'multipart': return part in mail.walk(): if part.get_content_maintype() != 'multipart' , part.get('content-disposition') not none: if (str(part.get_filename()) == "something") or ("something2" in str(p...

java - Android firebase onStart and onStop explanation -

Image
i've started firebase in android , can't understand things in onstart , in onstop. why necessary have code on stop method? why need remove listener ? @override protected void onstop() { super.onstop(); log.d(tag, "onstop: "); if(mauthstatelistener != null) mauth.removeauthstatelistener(mauthstatelistener); } and 1 more question advantage of setting mauth listener in onstart method instead of oncreate ? @override protected void onstart() { super.onstart(); log.d(tag, "onstart: "); mauth.addauthstatelistener(mauthstatelistener); } this how shoved in firebase -> authentication demo. there need remove listeners because mauth keep of keeping track of listeners added, in order notify when happens. when activity stops remove listener list because well, activity has stopped anyway, there no need listen auth events when activity stopped, there? why add listener @ onstart then? because according activi...

css - Animation Not Running -

i trying make loading screen using css animations. screen 4 different bars shrinking , growing. want arrange them in formation form square. use absolute positioning position them, know if there better way. managed 3 bars display , float did not manage last one. now, animations not running @ all. can me? code: https://codepen.io/ngmh/pen/gxewjk html: <div id="top"></div> <div id="right"></div> <div id="bottom"></div> <div id="left"></div> css: #top{ background-color: red; width: 100px; height: 25px; border-radius: 12.5px; position: absolute; left: 37.5px; animation-name: loading-1; animation-duration: 4s; animation-iteration-count: infinite; } #bottom{ background-color: yellow; width: 100px; height: 25px; border-radius: 12.5px; position: absolute; top: 112.5px; animation-name: loading-1; animation-duration: 4s; animation-iteration-count: infinite; }...

c# - Execute code before uninstall of a WPF application -

i have created wpf click-once application running perfectly. now, want execute code before application gets uninstalled. want inform server application particular machine uninstalled. but didn't find feasible way achieve this. could please provide thought on this? how achieve this? i not sure whether possible or not. if not there alternate way creating setup project .

Python Opencv project: "terminate called after throwing an instance of 'std::out_of_range' -

i got following error message python + opencv project: "terminate called after throwing instance of 'std::out_of_range' what(): basic_string::substr: __pos (which 140) > this->size() (which 0) aborted" projects failing @ command cv2.imread. projects running previously. have tried reinstall opencv , cmake, still have issue. (i using kubuntu 16.04) idea causes problem?

c# - better way to create game server with web interface -

i decided write card game c# has winform application main server manage game web interface. chose signalr self-host main server. because want sell app others , dont want modify code or html of web interface. question is: handling 10000 client request? there way write app better performance? thing want write main server , login cashout profile , ... written customers poker mavens , create api json functions. plzzzz guide me way better write app! with server code self hosted , javascript client calling server methods, becoming browser based client, design should work. looking @ this. https://docs.microsoft.com/en-us/aspnet/signalr/overview/deployment/tutorial-signalr-self-host but think you'll need figure out scale out scenarios , server failure scenarios self host. in case there patch update on server , has restart, you'll need able backup. consider case when need upgrade server. you'll need able host in multiple servers , you'll need provide signalr back...