Saturday 15 March 2014

Boolean Valued Response in C++ -



Boolean Valued Response in C++ -

this question has reply here:

c++ cin boolean(0,1) 3 answers

please, there way boolean valued response straight users in c++??. instance user reply yes or no not want store response in character or string variable straight boolean variable. thanks.

declare variable bool , take input 0 or 1 treated false or true respectively.

bool b; cin >> b;

c++

javascript - How do I call a method when an image has been fully loaded and rendered? -



javascript - How do I call a method when an image has been fully loaded and rendered? -

i need phone call method after image has been loaded , rendered in browser.

quick illustration big image:

http://jsfiddle.net/2clm4epv/

<img width="500px" src="http://www.digivill.net/~binary/wall-covering/(huge!)14850x8000%2520earth.jpg">

my method should called when image visible.

as discussed in comments utilize .load() function along phone call accomplish task,

html

<img id="bigimage" width="500px" src="http://www.digivill.net/~binary/wall-covering/(huge!)14850x8000%2520earth.jpg"/>

js

$('#bigimage').load(function(){ alert('loaded , redered'); }); demo

javascript jquery html css

big o - Algorithmic Upper Bound for my solution -



big o - Algorithmic Upper Bound for my solution -

i'm working on homework , want create sure analysis of upper bound solution correct.

here's do.

i read n characters input string. // o(n) construct min heap of size k(where k big constant). // o(n) retreive k entries min heap. // o(k *log n).

the complexity of solution hence o(n+ k·logn). wondering whether can safely approximate o(n), if take consideration k constant.

yes, if k constant, Θ(n + k log n) = Θ(n) + Θ(k log n) = Θ(n) + Θ(log n) = Θ(n).

big-o time-complexity

python - django template access to models -



python - django template access to models -

i having issue templating scheme in django, doing film list app larn more django , have declared models following:

class pelicula (models.model): nombre = models.charfield(max_length = 30) genero = models.charfield(max_length = 20) año = models.integerfield() def __str__(self): homecoming self.nombre

then have declared view following

def index(request): pelicula = pelicula.objects.all() homecoming render_to_response("index.html", dict(pelicula = pelicula, usuario = request.user))

so far know, not having problem here

then problem starts on template

<!doctype html> <html> <head> <title>mis peliculas favoritas</title> </head> <body> <h1>mis peliculas favoritas</h1> <ol> {% pelicula in pelicula.object_list %} <li><a href ="#">{{ pelicula.nombre }}</a></li> {% endfor %} </ol> <a href="agregar.html">agregar pelicula nueva</a> </body> </html>

so see, using loop objects in db, have 3, when run server, title shows , other link bellow named "agregar" shows except movies, wondering if problem between "pelicula" name instead of using pelicula used on declaring model, anyway have changed pelicula.object_list , didn't worked anyway

i believe having problem understanding how utilize info have through django template tags

thanks in advance , please forgive grammar not native english language speaker

in view code have pelicula = pelicula.objects.all() creates list of abjects database. send template same name, means have in template iterate on them. seek changing template this:

<h1>mis peliculas favoritas</h1> {% if pelicula %} <ol> {% item in pelicula %} <li><a href ="#">{{ item.nombre }}</a></li> {% endfor %} </ol> {% else %} didn't find any... {% endif %}

part of confusion seems come fact template code , view code separate. template doesn't know view code. context dictionary sets names can used in template , in template names have available utilize ones passed via dictionary. names in view , template here same in case because set them same. aren't same variables though, have same name. in template pelicula list of objects don't need utilize in template loop.

python django templates

Class not found Kryo exception in hive 0.13 - Hadoop -



Class not found Kryo exception in hive 0.13 - Hadoop -

i have genericudf (see code below) running fine on hadoop-1 , hive-0.12. when testing same genericudf using hive-0.13 + hadoop-2, getting below error.

vertex failed, vertexname=map 12, vertexid=vertex_1409698731658_42202_1_00, diagnostics=[vertex input: ccv initializer failed., org.apache.hive.com.esotericsoftware.kry o.kryoexception: unable find class: com.xxx.xxx.id1

here code udf.

package com.xxx.xxx; import org.apache.hadoop.hive.*; public class id1 extends genericudf { private mapredcontext context; private long sequencenum = 0; private static final int padlength = 10; stringbuilder sb = null; public objectinspector initialize(objectinspector[] arguments) throws udfargumentexception { sequencenum = 0; sb = new stringbuilder(); homecoming primitiveobjectinspectorfactory.javastringobjectinspector; } public object evaluate(deferredobject[] arguments) throws hiveexception { int sblength = sb.tostring().length(); if (sblength > 0) sb.replace(0, sblength, ""); string taskid = null; if (context.getjobconf() != null) taskid = context.getjobconf().get("mapred.taskid"); sequencenum++; if (taskid != null) { sb.append(taskid.replace("attempt_", "")); } int = 0; string seqstr = string.valueof(sequencenum); sb.append(seqstr); homecoming sb.tostring(); } public string getdisplaystring(string[] children) { homecoming "id1()"; } @override public void configure(mapredcontext context) { this.context = context; } }

i has hive-0.13, not able see post related error.

hadoop hive kryo

javascript - jQuery never calls .done() or .always() for ajax call -



javascript - jQuery never calls .done() or .always() for ajax call -

i'm having simple request:

$.get('ri/i18n/locale') .done(function() { console.log(this); }) .fail(function() { console.log(this); }) .always(function(){ console.log(this); });

unfortunately none of handlers ever called.

i cann confirm calling ri/i18n/locale in browser returns valid json string. i'm using jquery 1.11.1 .

any ideas what's wrong?

your issue might version of jquery using. before jquery 1.5, jqxhr object not returned $.get(), allows utilize promise behavior. the relevant jquery documentation.

javascript jquery ajax

How can I customize my infowindow android app borders? -



How can I customize my infowindow android app borders? -

hi guys have set customize image on everymarker infowindow on googlemap, on android application. can not fit image left, right , bottom border because, think, default infowindow properties have default padding or margin on content.

is possible fit image infowindow? here screenshot , code:

screen

xml :

<linearlayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="wrap_content" android:layout_height="wrap_content" android:gravity="center_horizontal|left" android:orientation="horizontal"> <imageview android:id="@+id/image_nuvoletta" android:layout_width="90dp" android:layout_height="60dp" android:layout_marginright="5dp" android:paddingleft="0px" android:adjustviewbounds="true" android:src="@drawable/ic_launcher"/> [...]

java snippet of getinfocontents

public view getinfocontents(marker marker) { /* distanza piedi e macchina sulla nuvoletta */ /***********************************************/ gpstracker gpstracker = new gpstracker(mainactivity.this); if (gpstracker.cangetlocation()) { string stringlatitude = string.valueof(gpstracker.latitude); string stringlongitude = string.valueof(gpstracker.longitude); double currentlat = double.parsedouble(stringlatitude); double currentlng = double.parsedouble(stringlongitude); double destlat = marker.getposition().latitude; double destlng = marker.getposition().longitude; final float[] results = new float[3]; location.distancebetween(currentlat, currentlng, destlat, destlng, results); float metri = results[0]; float km = math.round((double)metri/1000); int minuti_persona = (int)math.round(metri/125); //125 metri al minuto -> velocità media di 2,5 m/s int minuti_auto = (int)math.round(km/0.7); //700 metri al minuto -> velocità media di 42 km/h /***********************************************/ view v = getlayoutinflater().inflate(r.layout.custom_info_window, null); textview tvtitle = (textview) v.findviewbyid(r.id.title); textview tvsnippet = (textview) v.findviewbyid(r.id.snippet); tvsnippet.settypeface(tvsnippet.gettypeface(), typeface.italic); //indirizzo in corsivo textview tvpedonal_distance = (textview) v.findviewbyid(r.id.pedonal_time); textview tvcar_distance = (textview) v.findviewbyid(r.id.car_time); tvtitle.settext(marker.gettitle()); tvsnippet.settext(marker.getsnippet()); if(minuti_persona <=0) // stampa tempo per coprire la distanza { tvcar_distance.settext("a piedi: meno di united nations minuto"); }else { tvpedonal_distance.settext("a piedi: "+minuti_persona+ " minuti"); } if(minuti_auto <= 0) { tvcar_distance.settext("in auto: meno di united nations minuto"); }else { tvcar_distance.settext("in auto: " +minuti_auto+ " minuti"); } //prova immagine custom /***********************************/ imageview image; string currenturl="http://upload.wikimedia.org/wikipedia/commons/5/50/casa_natale_benito_mussolini_(1).jpg"; image = (imageview) v.findviewbyid(r.id.image_nuvoletta); picasso.with(v.getcontext()) .load(currenturl) .error(r.drawable.ic_launcher) //in caso di errore fa vedere questa immagine (un triangolo penserei) .resize(150, 110) .into(image); /***********************************/ homecoming v; }else { view v = getlayoutinflater().inflate(r.layout.custom_info_window, null); textview tvtitle = (textview) v.findviewbyid(r.id.title); textview tvsnippet = (textview) v.findviewbyid(r.id.snippet); tvtitle.settext(marker.gettitle()); tvsnippet.settext(marker.getsnippet()); homecoming v; } }

thank much

android android-layout infowindow

ruby on rails - capify-ec2 cap deploy:migrate db no servers matching -



ruby on rails - capify-ec2 cap deploy:migrate db no servers matching -

i'm unable perform cap deploy:migrate. , error message is:

2014-10-14 10:01:15 executing `deploy:migrate' executing "ls -x /home/pj-production/projectname/releases" `deploy:migrate' run servers matching {:roles=>:db, :only=>{:primary=>true}}, no servers matched

setup:

rails (3.2.13)

capistrano (2.14.2)

capify-ec2 (1.1.6)

cap ec2:status

project: projectname. num name id type dns zone roles 00: worker01 i-1 t1.micro ec2-x1.eu-west-1.compute.amazonaws.com eu-west-1b worker 01: db01 i-d m1.medium ec2-x2.eu-west-1.compute.amazonaws.com eu-west-1b 02: web01 i-f m1.medium ec2-x3.eu-west-1.compute.amazonaws.com eu-west-1b web,app,db

in deploy.rb:

ec2_roles name: :web, options: { default: true } ec2_roles name: :app, options: { default: true } ec2_roles name: :db, options: { default: true } ec2_roles name: :worker, options: { default: true }

there parts in deploy.rb

task :start, roles: :app run "cd #{current_path} && bundle exec unicorn -c config/unicorn/production.conf.rb -e production -d" end

works, illustration when perform a: cap deploy, runs , finishes.

what problem? searched google , other questions in stack. couldnt run. i'm not using multistage btw , gist file of deploy.rb: https://gist.github.com/adogan/2121d312c5938746acd6

for ec2 instance roles: 'web,app,db' need add together 'options' tag in aws single value, 'primary'. equivalent having config/deploy/env.rb line:

role :db, "10.1.2.3", :primary => true

deploy works because skip db:migrate if there no boxes match role 'db' primary true. you're asking db:migrate, fail if there no boxes run on.

ruby-on-rails amazon-web-services deployment amazon-ec2 capistrano

image - Adding Thorlabs DCC cmos as an input device in Matlab to record video? -



image - Adding Thorlabs DCC cmos as an input device in Matlab to record video? -

i'm trying record timing video thorlabs dcc cmos 1280x1024 code in matlab matlab don't recognize video device in imaqhwinfo, a=imaqhwinfo('winvideo',1) command. how can prepare it?

it's not supported hardware, see supported hardware page.

your options either request hardware added supported hardware list (if you're prepared wait few years...) or utilize adaptor kit write communication layer between image acquisition toolbox acquisition engine , third-party sdk , drivers hardware. however, advanced manoeuvre experienced users , requires extensive knowledge of hardware vendor's sdk (and not can help with).

image matlab

javascript - Javascrript onclick change image title -



javascript - Javascrript onclick change image title -

i need display title of loaded video under player. user clik on thumbnail load video on jwplayer. can load first title.

class="snippet-code-html lang-html prettyprint-override"><div>now playing: <span id='nowplaying'>my 40th aniversary</span> </div> <script type="text/javascript"> function changetitle(){ var video = document.getelementbyid('vidtitle').getattribute('title'); document.getelementbyid('nowplaying').innerhtml = video; } </script> <!-- body of pge --> <h2>trips</h2> <ul> <li> <a href="javascript:loadvideo('rtmp://ondemand/triptoelgin.mp4');"> <img src="http://www.example.com/images/triptoelgin.jpg" id='vidtitle' onclick='changetitle()' title="trip elgin "/></a>trip elgin</li> <li> <a href="javascript:loadvideo('rtmp://ondemand/triptowaco.mp4');"> <img src="http://www.example.com/images/triptowaco.jpg" id='vidtitle' onclick='changetitle()' title="trip waco"/></a>trip waco</li> </ul> <!-- begin snippet: js hide: false -->

how can add together variable load next video title? tried this, gives undefined value.

in html, id attribute must unique. right now, when you're calling document.getelementbyid('vidtitle'), browser picking first 1 no matter what. if want identify of images clicked on, send this changetitle function so:

javascript function changetitle(element){ var video = element.getattribute('title'); document.getelementbyid('nowplaying').innerhtml = video; } html <ul> <li> <a href="javascript:loadvideo('rtmp://ondemand/triptoelgin.mp4');"><img src="http://www.example.com/images/triptoelgin.jpg" id='vidtitle1' onclick='changetitle(this)' title="trip elgin "/></a>trip elgin</li> <li> <a href="javascript:loadvideo('rtmp://ondemand/triptowaco.mp4');"> <img src="http://www.example.com/images/triptowaco.jpg" id='vidtitle2' onclick='changetitle(this)' title="trip waco"/></a>trip waco</li> </ul>

javascript variables

angularjs - Redirect after login to backbone route with rails -



angularjs - Redirect after login to backbone route with rails -

i attempting provide users mutual functionality, redirecting them after login requested url behind secure path. example, user clicks link in email triggered via notification in system, attempts go to: https://mysite.com/secure/notifications/1 user not logged in kicked https://mysite.com/login after login should brought not home page, requested url.

i familar technique store attempted url in session before redirecting login page. issue if url contains backbone router after core url, ie https://mysite.com/secure/notifications/1#details

the #details part of url not sent server seems, typically inner page jumping. wondering how web developers dealing js mvc frameworks backbone, angular, , other emerging? trick? way have # pass server in http specification?

any ideas appreciated, give thanks you.

the easiest solution problem, if don't need back upwards behaviour older browsers, enable pushstate in backbone router don't utilize # routes:

backbone.history.state({pushstate: true});

edit:

the other potential solution, though bit messy, url tomfoolery figure out should after hash , navigate route.

for example, let's want navigate to:

http://webapp.com/abc/#page1 'page1' fragment makes backbone route.

if instead send user http://webapp.com/abc/page1. can observe whether browser has pushstate. if not, can replace after 'root' hash. here illustration code might on right track supporting both sets of browsers:

class="snippet-code-js lang-js prettyprint-override"> var _defaults = { pushstate: modernizr.history, silent: true, root: '/' }; var start = function(options) { // start routing either pushstate or without options = _.extend(_.clone(this._defaults), options); backbone.history.start(options); if (options.pushstate) { backbone.history.loadurl(backbone.history.getfragment()); return; } this.degradetononhistoryurl(); }; /** * fragment urls, check if actual request root i.e '/', * if is, can go on , backbone magic * if isn't redirect root route fragment * foo.com/bar/1 -> foo.com/#bar/1 */ degradetononhistoryurl = function() { var pathname = window.location.pathname; // if root '/', length one. if root 'foo', length 5 (/foo/) var rootlength = _getroot().length; var isrootrequest = pathname.length === rootlength; if (!isrootrequest) { var route = pathname.substr(rootlength); window.location.href = _getroot() + '#' + route + window.location.search; return; } backbone.history.loadurl(backbone.history.getfragment()); }, /** * effective root of app. it's '/', if set 'foo', want * homecoming '/foo/' can more determine if root request or not. * @returns {string} effective root */ _getroot = function() { if (backbone.history.options.root === '/') { homecoming '/'; } homecoming '/' + backbone.history.options.root + '/'; },

the trick here making pushstate url canonical urls , sending users ones. 1 time browser adoption increases, should theoretically easy cutting of crap out without having update of links.

ruby-on-rails angularjs backbone.js

entity framework - MVC class within class not being populated -



entity framework - MVC class within class not being populated -

trying create mvc application of existing php/mysql library application. i'm having problem getting basic things work, , sense idiot.

i have next classes defined:

book class:

public class book { public int bookid { get; set; } public string bookname { get; set; } public int? seriesid { get; set; } public int genreid { get; set; } public genre genre { get; set; } etc }

genre class:

public class genre { public int genreid { get; set; } public string genrename { get; set; } public virtual icollection<book> books { get; set; } }

when run see each book object created has genre object, null, , info genres isn't beingness populated.

the genreid in book class foreign key

can please tell me doing wrong?

the genre property on book should virtual. if isn't virtual plain query retrieves books leave genre blank. making virtual allows entity framework create dynamic proxy class, inherited book, implements getter of genre property code issue query populate , homecoming genre database.

you've made genre's collection of books virtual work lazy fetching property already.

an alternative lazy loading utilize .include on query include genre property.

entity-framework model-view-controller

internationalization - How to generate .po files using translated strigs from a database in php? -



internationalization - How to generate .po files using translated strigs from a database in php? -

i seek create resources files multi language php website. created .po files, converted binary .mo files little library https://github.com/josscrowcroft/php.mo, not seem work. if open generated .po file poedit nail save, observed .mo file size alter little comparing initial 1 , .po file works. not know how working, directly, without using poedit tool.

please give me suggestions if have! thanks

following text copied http://php.net/manual/en/book.gettext.php

" an of import thing maintain in mind: not forget set charset in .po file! example:

"content-type: text/plain; charset=utf-8\n"

then php able find .mo file generated, using msgfmt, .po file charset set.

because of i've wasted lot of time debugging code, testing every single little changes people suggested on manual , internet:

<?php //this: setlocale( lc_messages, 'pt_br') //or this: setlocale( lc_messages, 'pt_br.utf8') //or this: setlocale( lc_messages, '') //this: putenv("lang=pt_br.utf8"); //or this: putenv("language=pt_br.utf8"); //this: bindtextdomain('mydomain', dirname(__file__).'/locale'); //or this: bindtextdomain("*", dirname(__file__).'/locale'); //or this: bindtextdomain('*', dirname(__file__).'/locale'); //setting or not "bind_textdomain_codeset()": bind_textdomain_codeset("mydomain", 'utf-8'); ?>

as locale directory name set:

./locale/pt_br.utf8/lc_messages/mydomain.mo

or

./locale/pt_br/lc_messages/mydomain.mo

or

./locale/pt/lc_messages/mydomain.mo

finally, code brought right translated strings (also right charset) was:

<?php $directory = dirname(__file__).'/locale'; $domain = 'mydomain'; $locale ="pt_br.utf8"; //putenv("lang=".$locale); //not needed tests, people it's useful windows setlocale( lc_messages, $locale); bindtextdomain($domain, $directory); textdomain($domain); bind_textdomain_codeset($domain, 'utf-8'); ?>

and 3 directory's names worked out, using pt_br.utf8 locale. (my tests made restarting apache trying each directory).

i hope help else not waste much time i've wasted... =p

using: ubuntu 8.04 (hardy) apache 2.2.8 php 5.2.4-2ubuntu5.6 "

php internationalization po poedit

c# - Show Yes or No for a boolean column in a DevXpress grid -



c# - Show Yes or No for a boolean column in a DevXpress grid -

i using "devxpress.xtragrid.gridview" , have column there bound boolean data. column shows check boxes represent values. need show "yes/no" instead of check boxes. please advice me.

thanks helping, kushan randima.

this how in code in 1 of tools. dynamic sql query tool , returns checkmark or reddish x beside query result, @ runtime. can through designer done in code.

this winforms, low level gridview should same code wpf (i not positive).

first, in info grid gridview designer, add together column (mine "iserror" column). in form constructor or initializeform() this:

repositoryitemcheckedit checkedit = gridoutput.repositoryitems.add("checkedit") repositoryitemcheckedit; checkedit.picturechecked = global::gyrasoft.common.dx.properties.resources.exclamation; checkedit.pictureunchecked = global::gyrasoft.common.dx.properties.resources.accept; checkedit.checkstyle = devexpress.xtraeditors.controls.checkstyles.userdefined; gridviewoutput.columns["iserror"].columnedit = checkedit;

the resources, of course, have valid images.

basically add together repository item (repositoryitemcheckedit) , set checkstyle userdefined, , assign checkedit gridview column. can add together same checkedit multiple columns. rendering or editing.

c# visual-studio-2012 gridview devexpress

javascript - AngularJS - Mapping a date from a range of dates -



javascript - AngularJS - Mapping a date from a range of dates -

i have table in header, produces 12 cells start current date, subtracting 1 month, so:

22 oct 2014 | 22 sep 2014 | 22 aug 2014 etc etc

i have json file list of dates. have angular service retrieves dates however, trying do, compare range of dates in header, counts how many items json, fall in between dates.

here's plunker: http://plnkr.co/edit/8ncklxradtosc0en2swg?p=preview

html:

<table> <thead> <tr> <th></th> <th ng-repeat="months in getmonths track $index">{{ months }}</th> </tr> </thead> <tbody> <tr> <td></td> <td ng-repeat="months in getmonths track $index"> <span ng-repeat="item in filtered = (datemapping(months))"></span> <p>{{filtered.length}}</p> </td> </tr> </tbody> </table>

js:

so, output like:

22 oct 2014 | 22 sep 2014 | 22 aug 2014 etc etc 2 | 5 | 0 etc etc

update:

$scope.datemapping = function(months) { var curdate = new date(months); var prevdate = new date(months); prevdate = new date(new date(prevdate.setmonth(prevdate.getmonth() - 1)).setdate(prevdate.getdate() - 1)); //console.log("curdate: " + curdate); //console.log("prevdate: " + prevdate); var jsonentries = $scope.dates; (var = 0; < jsonentries.length; i++) { var jsondate = jsonentries[i].date.substring(6, jsonentries[i].date.length - 2); if (jsondate >= curdate && jsondate <= prevdate ) { //perform .push } else { } } };

javascript jquery angularjs angularjs-scope angularjs-ng-repeat

ios - Box: Getting sharedlink parameter immediately after uploading new file -



ios - Box: Getting sharedlink parameter immediately after uploading new file -

is there way sharedlink parameter, after uploading new file on box in boxfile block.

i've tried next code, it's returning sharedlink parameter nil.

boxfilesrequestbuilder *builder = [[boxfilesrequestbuilder alloc] init]; builder.name = imagename; builder.parentid = folderid; //--- shared link object ---// boxsharedobjectbuilder *sharedbuilder = [[boxsharedobjectbuilder alloc] init]; sharedbuilder.access = boxapisharedobjectaccessopen; builder.sharedlink = sharedbuilder; nsinputstream *inputstream = [nsinputstream inputstreamwithfileatpath:imagepath]; nsdictionary *fileattributes = [[nsfilemanager defaultmanager] attributesofitematpath:imagepath error:nil]; long long contentlength = [[fileattributes objectforkey:nsfilesize] longlongvalue]; [[boxsdk sharedsdk].filesmanager uploadfilewithinputstream:inputstream contentlength:contentlength mimetype:nil requestbuilder:builder success:fileblock failure:failureblock progress:nil];

you have create sec phone call after file uploaded.

ios box-api boxapiv2

android - No ActionBar in PreferenceActivity after upgrade to Support Library v21 -



android - No ActionBar in PreferenceActivity after upgrade to Support Library v21 -

after upgraded back upwards library v21 actionbar in preferenceactivity gone.

did miss attributes in theme activate again? had similar problem a black actionbar.

i tried add together little hackish adding toolbar root layout, did not work expected.

please find github repo: here

very similar own code added xml allow set title:

continuing utilize preferenceactivity:

settings_toolbar.xml :

<?xml version="1.0" encoding="utf-8"?> <android.support.v7.widget.toolbar xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/toolbar" app:theme="@style/themeoverlay.appcompat.dark.actionbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:minheight="?attr/actionbarsize" app:navigationcontentdescription="@string/abc_action_bar_up_description" android:background="?attr/colorprimary" app:navigationicon="?attr/homeasupindicator" app:title="@string/action_settings" />

settingsactivity.java :

public class settingsactivity extends preferenceactivity { @override protected void onpostcreate(bundle savedinstancestate) { super.onpostcreate(savedinstancestate); linearlayout root = (linearlayout)findviewbyid(android.r.id.list).getparent().getparent().getparent(); toolbar bar = (toolbar) layoutinflater.from(this).inflate(r.layout.settings_toolbar, root, false); root.addview(bar, 0); // insert @ top bar.setnavigationonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { finish(); } }); } }

result :

update (gingerbread compatibility) :

as pointed out here, gingerbread devices returning nullpointerexception on line:

linearlayout root = (linearlayout)findviewbyid(android.r.id.list).getparent().getparent().getparent(); fix:

settingsactivity.java :

public class settingsactivity extends preferenceactivity { @override protected void onpostcreate(bundle savedinstancestate) { super.onpostcreate(savedinstancestate); toolbar bar; if (build.version.sdk_int >= build.version_codes.jelly_bean) { linearlayout root = (linearlayout) findviewbyid(android.r.id.list).getparent().getparent().getparent(); bar = (toolbar) layoutinflater.from(this).inflate(r.layout.settings_toolbar, root, false); root.addview(bar, 0); // insert @ top } else { viewgroup root = (viewgroup) findviewbyid(android.r.id.content); listview content = (listview) root.getchildat(0); root.removeallviews(); bar = (toolbar) layoutinflater.from(this).inflate(r.layout.settings_toolbar, root, false); int height; typedvalue tv = new typedvalue(); if (gettheme().resolveattribute(r.attr.actionbarsize, tv, true)) { height = typedvalue.complextodimensionpixelsize(tv.data, getresources().getdisplaymetrics()); }else{ height = bar.getheight(); } content.setpadding(0, height, 0, 0); root.addview(content); root.addview(bar); } bar.setnavigationonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { finish(); } }); } }

any issues above allow me know!

update 2: tinting workaround

as pointed out in many dev notes preferenceactivity not back upwards tinting of elements, utilising few internal classes can accomplish this. until these classes removed. (works using appcompat support-v7 v21.0.3).

add next imports:

import android.support.v7.internal.widget.tintcheckbox; import android.support.v7.internal.widget.tintcheckedtextview; import android.support.v7.internal.widget.tintedittext; import android.support.v7.internal.widget.tintradiobutton; import android.support.v7.internal.widget.tintspinner;

then override oncreateview method:

@override public view oncreateview(string name, context context, attributeset attrs) { // allow super seek , create view first final view result = super.oncreateview(name, context, attrs); if (result != null) { homecoming result; } if (build.version.sdk_int < build.version_codes.lollipop) { // if we're running pre-l, need 'inject' our tint aware views in place of // standard framework versions switch (name) { case "edittext": homecoming new tintedittext(this, attrs); case "spinner": homecoming new tintspinner(this, attrs); case "checkbox": homecoming new tintcheckbox(this, attrs); case "radiobutton": homecoming new tintradiobutton(this, attrs); case "checkedtextview": homecoming new tintcheckedtextview(this, attrs); } } homecoming null; }

result:

appcompat 22.1

appcompat 22.1 introduced new tinted elements, meaning there no longer need utilise internal classes accomplish same effect lastly update. instead follow (still overriding oncreateview):

@override public view oncreateview(string name, context context, attributeset attrs) { // allow super seek , create view first final view result = super.oncreateview(name, context, attrs); if (result != null) { homecoming result; } if (build.version.sdk_int >= build.version_codes.jelly_bean) { // if we're running pre-l, need 'inject' our tint aware views in place of // standard framework versions switch (name) { case "edittext": homecoming new appcompatedittext(this, attrs); case "spinner": homecoming new appcompatspinner(this, attrs); case "checkbox": homecoming new appcompatcheckbox(this, attrs); case "radiobutton": homecoming new appcompatradiobutton(this, attrs); case "checkedtextview": homecoming new appcompatcheckedtextview(this, attrs); } } homecoming null; }

nested preference screens

a lot of people experiencing issues including toolbar in nested <preferencescreen />s however, have found solution!! - after lot of trial , error!

add next settingsactivity:

@suppresswarnings("deprecation") @override public boolean onpreferencetreeclick(preferencescreen preferencescreen, preference preference) { super.onpreferencetreeclick(preferencescreen, preference); // if user has clicked on preference screen, set screen if (preference instanceof preferencescreen) { setupnestedscreen((preferencescreen) preference); } homecoming false; } public void setupnestedscreen(preferencescreen preferencescreen) { final dialog dialog = preferencescreen.getdialog(); toolbar bar; if (build.version.sdk_int >= build.version_codes.ice_cream_sandwich) { linearlayout root = (linearlayout) dialog.findviewbyid(android.r.id.list).getparent(); bar = (toolbar) layoutinflater.from(this).inflate(r.layout.settings_toolbar, root, false); root.addview(bar, 0); // insert @ top } else { viewgroup root = (viewgroup) dialog.findviewbyid(android.r.id.content); listview content = (listview) root.getchildat(0); root.removeallviews(); bar = (toolbar) layoutinflater.from(this).inflate(r.layout.settings_toolbar, root, false); int height; typedvalue tv = new typedvalue(); if (gettheme().resolveattribute(r.attr.actionbarsize, tv, true)) { height = typedvalue.complextodimensionpixelsize(tv.data, getresources().getdisplaymetrics()); }else{ height = bar.getheight(); } content.setpadding(0, height, 0, 0); root.addview(content); root.addview(bar); } bar.settitle(preferencescreen.gettitle()); bar.setnavigationonclicklistener(new view.onclicklistener() { @override public void onclick(view v) { dialog.dismiss(); } }); }

the reason preferencescreen's such pain because based wrapper dialog, need capture dialog layout add together toolbar it.

toolbar shadow

by design importing toolbar not allow elevation , shadowing in pre-v21 devices, if have elevation on toolbar need wrap in appbarlayout:

`settings_toolbar.xml :

<android.support.design.widget.appbarlayout android:layout_width="match_parent" android:layout_height="wrap_content"> <android.support.v7.widget.toolbar .../> </android.support.design.widget.appbarlayout>

not forgetting add together add design back upwards library dependency in build.gradle file:

compile 'com.android.support:support-v4:22.2.0' compile 'com.android.support:appcompat-v7:22.2.0' compile 'com.android.support:design:22.2.0' android 6.0

i have investigated reported overlapping issue , cannot reproduce issue.

the total code in utilize above produces following:

if missing please allow me know via this repo , investigate.

android android-support-library preferenceactivity android-5.0-lollipop

sql - Order BY on column generated by select statement -



sql - Order BY on column generated by select statement -

i'm running query:

select claims.rid ,claims.client ,clients.cname ,cur.currency ,carriers.scac ,carriers.cname ,claims.client+claims.counter ,claims.dateon ,(select top 1 errorcode entries entries.rid=claims.rid) errorcode ,(select sum(refunddue) entries entries.rid=claims.rid) amount ,auditors.initials claims inner bring together clients on clients.code = claims.client inner bring together currency cur on claims.currency = cur.currencyid inner bring together entries on claims.rid = entries.rid inner bring together carriers on carriers.carrierid = claims.carrierid inner bring together auditors on claims.auditorid=auditors.auditorid grouping claims.rid ,claims.client ,claims.counter ,claims.dateon ,carriers.scac ,carriers.cname ,clients.cname ,cur.currency ,auditors.initials ,errorcode order errorcode asc

the focus should on orderby errorcode. reason, it's not ordering alphabetically errorcode. ideas why?

most databases don't allow utilize aliases created in select-list in grouping by, order , clauses. instead, have repeat look used in select-list:

select claims.rid, ..., (select top 1 errorcode entries entries.rid=claims.rid) errorcode, ... claims inner bring together ... grouping claims.rid, ..., (select top 1 errorcode entries entries.rid=claims.rid) order (select top 1 errorcode entries entries.rid=claims.rid) asc

but think improve utilize sub-select info source in from-clause:

select claims.rid, ..., e.errcode, e.amount, ... claims inner bring together clients on clients.code = claims.client inner bring together currency cur on claims.currency = cur.currencyid inner bring together (select rid, min(errorcode) errcode, sum(refunddue) amount entries grouping rid) e on claims.rid = e.rid inner bring together carriers on carriers.carrierid = claims.carrierid inner bring together auditors on claims.auditorid=auditors.auditorid grouping claims.rid, ..., e.errcode order e.errcode asc

note included sum(refunddue) amount well. if error codes can null within entries, utilize max(errorcode) instead of min(errorcode).

sql

Java : Unknown error in exception handling -



Java : Unknown error in exception handling -

i have weird question. had quiz in class today. 1 portion of quiz find , right errors in short piece of code. 1 of questions this

class illustration { public static void main(string[] args) { seek { system.out.println("xyz"); } grab (exception e) { system.out.println("exception caught"); } { system.out.println("abc"); } } }

i thought there no error in programme professor insisted there was. can guess error is?

the "error" may don't need handle exception here: system.out.println not specify checked exception. be:

public static void main(string[] args) { system.out.println("xyz"); }

since exception class covers both checked , unchecked exceptions, if add together catch block here, in case handling unchecked exceptions, should not handle.

java exception exception-handling

android - How to deal with CurpsorAdapter in connection with SQLCipher -



android - How to deal with CurpsorAdapter in connection with SQLCipher -

i'm trying set encypted sqlite3 database in adroid.

i tried 6 steps commonsware suggested in encrypt sqlite database android:. of worked fine. problem there seems no corresponding class android.widget.cursoradapter.

so when seek implement class besucheadapter extends cursoradapter next message:

the method bindview(view, context, cursor) of type besucheadapter must override or implement supertype method.

at lot of other places in project, when seek cursor adapter

final cursor cursor = adapter.getcursor();

i hint:

type mismatch: cannot convert android.database.cursor net.sqlcipher.cursor.

any ideas can do?

package net.krankenhauspfarrer.besuche; import net.sqlcipher.cursor; import android.content.context; import android.util.log; import android.view.layoutinflater; import android.view.view; import android.view.viewgroup; import android.widget.cursoradapter; import android.widget.textview; public class besucheadapter extends cursoradapter { //für die anzeige der aktuellen patienten private layoutinflater inflator; private int cip, cist, ciraum, cisex, ciname, cigeb, cikat, cilb, cihint; @suppresswarnings("deprecation") public besucheadapter(context context, cursor c) { super(context, c); log.d("besuche","besucheadapter vor constructor"); //date = new date(); // inflator = layoutinflater.from(context); cip = c.getcolumnindex(dbhandler.main_p); cist = c.getcolumnindex(dbhandler.main_st); ciraum = c.getcolumnindex(dbhandler.main_raum); cisex = c.getcolumnindex(dbhandler.main_sex); ciname = c.getcolumnindex(dbhandler.main_name); cigeb = c.getcolumnindex(dbhandler.main_geb); cikat = c.getcolumnindex(dbhandler.main_kat); cilb = c.getcolumnindex(dbhandler.main_lb); cihint = c.getcolumnindex(dbhandler.main_hint); } @override public void bindview(view view, context context, cursor cursor) { textview tvp = (textview) view.findviewbyid(r.id.listp); textview tvst = (textview) view.findviewbyid(r.id.listst); textview tvraum = (textview) view.findviewbyid(r.id.listraum); textview tvsex = (textview) view.findviewbyid(r.id.listsex); textview tvname = (textview) view.findviewbyid(r.id.listname); textview tvgeb = (textview) view.findviewbyid(r.id.listgeb); textview tvkat = (textview) view.findviewbyid(r.id.listkat); textview tvlb = (textview) view.findviewbyid(r.id.listlb); textview tvhint = (textview) view.findviewbyid(r.id.listhint); int p = cursor.getint(cip); tvp.settext (string.valueof(p)); string st = cursor.getstring(cist); tvst.settext(st); string raum = cursor.getstring(ciraum); tvraum.settext(raum); string sex = cursor.getstring(cisex); tvsex.settext(sex); string name = cursor.getstring(ciname); tvname.settext(name); long gebms = cursor.getlong(cigeb); //date.settime(timemillis); tvgeb.settext(bhelper.resolvebesuchedate2string(gebms, bhelper.rd_short)); string kat = cursor.getstring(cikat); tvkat.settext(kat); long lbms = cursor.getlong(cilb); //date.settime(timemillis); tvlb.settext(bhelper.resolvebesuchedate2string(lbms, bhelper.rd_short)); string hint = cursor.getstring(cihint); tvhint.settext(hint); } @override public view newview(context context, cursor cursor, viewgroup parent) { log.d("besuche","besucheadapter vor textviewnew"); homecoming inflator.inflate(r.layout.besuche_zeile, null); }

yo have implement cursoradapter method android sql cursor (android.database.cursor). works don't using sqlcipher.

public void bindview(view view, context context, cursor cursor) { //do cursor }

we using sqlcipher in our project , works this. no need implement adapter class or something.

net.sqlcipher.cursor extension class android.database.cursor providing gettype method sqlcipher internally uses: net.sqlcipher.cursor on github

note: cannot cast sqlcipher.cursor because contentresolver internally wraps cursor in cursorwrapperinner instance has closeguard informs if did not close cursor correctly. don't need cast. have utilize , if contentprovider implementation correctly uses net.sqlcipher.cursor fine.

android sqlite encryption sqlcipher

ios - Making a triangle in a UIView with a CGRect Frame -



ios - Making a triangle in a UIView with a CGRect Frame -

hi making game , need spike @ bottom have decided via uiview , collisions. coding in swift.

i have square:

class="lang-swift prettyprint-override"> //object setup allow square = uiview(frame: cgrect(x:100, y:100, width: 100, height: 100)) square.backgroundcolor = uicolor.purplecolor() view.addsubview(square)

and triangle, have image can utilize triangle image square certainly collision when touches image borders not actual trianlge borders please advice on how image or how got square.

thanks

alex

there tutorial here:

http://jamesonquave.com/blog/drawing-custom-views-with-swift-andrew-vanwagoner/

with code this:

func drawplaypathto(context: cgcontextref, boundedby rect: cgrect) { cgcontextsetfillcolorwithcolor(context, uicolor.blackcolor().cgcolor) cgcontextmovetopoint(context, rect.width / 4, rect.height / 4) cgcontextaddlinetopoint(context, rect.width * 3 / 4, rect.height / 2) cgcontextaddlinetopoint(context, rect.width / 4, rect.height * 3 / 4) cgcontextaddlinetopoint(context, rect.width / 4, rect.height / 4) cgcontextfillpath(context) }

ios uiview swift cgrect

android - Extend the line to the end of the screen -



android - Extend the line to the end of the screen -

i making android app have 2 circles, there line attach between 2 circles. have managed draw line between circles regardless angle between them. question extend line end of screen. can know how it? thanks.

let co-ordinates of 2 circle centres (a,b) , (c,d).

the line segment want draw goes (p,?) (q,?) p , q x-co-ordinates of left , right of screen. can use:

y = ((d - b)/(c - a))*(p - a) + b y = ((d - b)/(c - a))*(q - a) + b

to find 2 y-values of points. encounter problem if 2 points vertical (c = a) cause partition zero.

android math geometry formula

opengl - glReadPixels: Stack around variable was corrupted after read pixels -



opengl - glReadPixels: Stack around variable was corrupted after read pixels -

i trying utilize glreadpixels() read window of 5 * 5 pixels. here code.

const unsigned int window_size = 5; const unsigned int nb_components = 3; glubyte array[nb_components * window_size * window_size]; glreadpixels( 0, 0, window_size, window_size, gl_rgb, gl_unsigned_byte, array);

yet code causes next error in visual studio: "stack around variable array corrupted"

if add together +4 size of array works fine. knows why?

since you're using gl_rgb create sure gl_pack_alignment set 1.

opengl stack glreadpixels

c# - Adding Link button Event Dynamically -



c# - Adding Link button Event Dynamically -

i creating table dynamically passing html code sting.

now want add together link button , if click on row want delete.

please help me in advance

try create linkbutton first , bind event button... example

htmlgenericcontrol td = new htmlgenericcontrol("td"); linkbutton lnk = new linkbutton(); //lnk.id = set dynamic id; lnk.text = "delete"; lnk.click += new eventhandler(clicked); td.controls.add(lnk);

now create function click on button

protected void clicked(object sender, eventargs e) { // work on click... }

c#

mysql - How to create sql query to insert values from another table? -



mysql - How to create sql query to insert values from another table? -

i have table related table 1:1. first table called 'deal' has: id, deal_ext_id fields sec table called 'deal_ext' has: id, externalid, systemid fields.

i have temp table contains externalid, systemid fields need inserted sec table (deal_ext).

because relation between both tables (deal, deal_ext) 1:1, foreign need updated when values inserted 'deal_ext' table.

how can have loop, getting through temp table , first insert new line 'deal_ext' new id, second, new id, update 'deal' table accordingly?

thanks!

phase 1: insert deal_ext(external_id) select t.campaign_id tempdeal t;

phase 2: update deal set deal_ext_id = (select e.id tempdeal t, deal_ext e t.campaign_id = e.external_id , t.deal_id = deal.id)

solved!

mysql sql

sql - How to create an auto-incrementing column that doesn't skip numbers after deleting a row? -



sql - How to create an auto-incrementing column that doesn't skip numbers after deleting a row? -

i'd have column that's (automatically) enumerating sequence of rows. have table:

nr name 1 test 2 test2 3 abc 4 def

in first delete lastly row followed adding new one. problem table looks this:

nr name 1 test 2 test2 3 abc 5 ghi

how can create resume 4 ?

the formal reply reseed value. here 1 description of do.

the real answer, though, not worry it. identity values not guaranteed sequential , there variety of reasons why gaps appear. without deletes. should used gaps in auto-incremented identity.

if need values sequential no gaps, there solutions. 1 calculate value on output:

row_number() on (partition id)

works quite well.

the other write trigger enforce rules want. know, though, folks write database engines know want identity gap-less. however, don't want take performance nail guarantee this, have reasonable compromise in terms of functionality , performance. if seek enforce sequential-ness without gaps, impact performance, particularly high-volume inserts , deletes.

sql sql-server ssms

regex - In Python how to strip dollar signs and commas from dollar related fields only -



regex - In Python how to strip dollar signs and commas from dollar related fields only -

i'm reading in big text file lots of columns, dollar related , not, , i'm trying figure out how strip dollar fields of $ , , characters.

so have:

a|b|c $1,000|hi,you|$45.43 $300.03|$ms2|$55,000

where , c dollar-fields , b not. output needs be:

a|b|c 1000|hi,you|45.43 300.03|$ms2|55000

i thinking regex way go, can't figure out how express replacement:

f=open('sample1_fixed.txt','wb') line in open('sample1.txt', 'rb'): new_line = re.sub(r'(\$\d+([,\.]\d+)?k?)',????, line) f.write(new_line) f.close()

anyone have idea?

thanks in advance.

a simple approach:

>>> import re >>> exp = '\$\d+(,|\.)?\d+' >>> s = '$1,000|hi,you|$45.43' >>> '|'.join(i.translate(none, '$,') if re.match(exp, i) else in s.split('|')) '1000|hi,you|45.43'

python regex

node.js/mongoDB: Return custom value if field is null -



node.js/mongoDB: Return custom value if field is null -

what want query database documents and, if field not set, homecoming custom value instead of it.

imagine i'm having collection of songs , of these have field pathtocover set , don't. these, want homecoming url placeholder image store in config variable.

i running node.js , mongodb express , mongoose.

i not sure best approach is. obvious solution query documents , in callback iterate on them check if field set. feels quite superfluous.

currently, code looks this:

exports.getbyalbum = function listbyalbum(query, callback) { song.aggregate({ $group: { _id: '$album', artists: { $addtoset: '$artist' }, songs: { $push: '$title' }, covers: { $addtoset: '$pathtocover'}, genres: { $addtoset: '$genre'}, pathtocover: { $first: '$pathtocover'} } }, function (err, result) { if (err) homecoming handleerror(err); result.foreach(function(album) { if ( album.pathtocover == null) { album.pathtocover = config.library.placeholders.get('album'); } }) callback(result); }); }

what best approach this?

thanks lot in advance!

where value of field either null or unset , perchance missing document, utilize $ifnull in aggregation set alternate value:

exports.getbyalbum = function listbyalbum(query, callback) { var defaultcover = config.library.placeholders.get('album'); song.aggregate( [ { "$group": { "_id": "$album", "artists": { "$addtoset": "$artist" }, "songs": { "$push": "$title" }, "covers": { "$addtoset": { "$ifnull": [ "$pathtocover", defaultcover ] } }, "genres": { "$addtoset": "$genre" }, "pathtocover": { "$first": { "$ifnull": [ "$pathtocover", defaultcover ] } } }} ], function (err, result) { if (err) homecoming handleerror(err); callback(result); } ); }

if empty string utilize $cond statement $eq test in place of $ifnull:

{ "$cond": [ { "$eq": [ "$pathtocover", "" ] }, defaultcover, "$pathtocover" ] }

either statement can used within of grouping operator replace value considered.

if worried perhaps not "all" of values set on song, utilize $min or $max appropriate info pick 1 of values instead of using $first.

node.js mongodb mongoose mongodb-query aggregation-framework

swi Prolog tracing recursion depth -



swi Prolog tracing recursion depth -

why recursion depth start 6 or 7 when tracing prolog programs?

example (taken form here).

factorial(0, 1). factorial(n, nfact) :- n > 0, nminus1 n - 1, factorial(nminus1, nminus1fact), nfact nminus1fact * n.

lets trace factorial(3, x). output is:

call: (7) factorial(3, _g284) ? creep* call: (8) 3>0 ? creep exit: (8) 3>0 ? creep call: (8) _l205 3-1 ? creep

and on. first column (call, exist) ports, 3rd goals , sec recursion depth. why start 7? (when run illustration on machine starts 6) shouldn't rather start 1 or 0?

prolog tracing factorial

Yeoman MeanJS Generator Showing Bootstrap 2 Buttons -



Yeoman MeanJS Generator Showing Bootstrap 2 Buttons -

i tried using yeoman generator meanjs first time , i'm wondering why bootstrap buttons rounded in bootstrap 2. dependencies i've installed bootstrap 3 project.

{ "name": "meanjsyoe", "version": "0.0.1", "description": "full-stack javascript mongodb, express, angularjs, , node.js", "dependencies": { "bootstrap": "~3", "angular": "~1.2", "angular-resource": "~1.2", "angular-mocks": "~1.2", "angular-bootstrap": "~0.11.0", "angular-ui-utils": "~0.1.1", "angular-ui-router": "~0.2.10" } }

the code uses bootstrap's standard classes...

<a class="btn btn-primary btn-lg">learn more</a>

and yet, looks this...

meanjs includes bootstrap-theme.css default (see all.js / production.js). styles buttons bootstrap 2.x. can remove including line if don't it.

see also: how utilize bootstrap-theme.css bootstrap 3?

twitter-bootstrap twitter-bootstrap-3 yeoman bower yeoman-generator

razor - How the master page interact with the background code in ASP.NET MVC? -



razor - How the master page interact with the background code in ASP.NET MVC? -

for example, bind info on master page, don't have background of duplicated code, should how implement?

asp.net-mvc razor

c# 4.0 - Access to the path is denied - C# -



c# 4.0 - Access to the path is denied - C# -

i have written programme copies files. sometimes, while trying re-create file exception thrown - "access path ... denied". (probably because programme uses file).

notice: run programme administrator

but! when re-create same file manually works!

why? wrong program?

try { copyclass.copy(m_filessources[i].path, m_filesdestinations[i], true, m_filessources[i].postfix); } grab (exception ex) { isaccessdenied = true; tblog.text += " - " + ex.message + "\n"; } class copyclass { public static bool copy(string sourcedirpath, string destdirpath, bool copysubdirs, string postfix) { if (postfix == null) { filecopy(sourcedirpath, destdirpath, copysubdirs); homecoming true; } directorycopy(sourcedirpath, destdirpath, copysubdirs, postfix); homecoming true; } public static void directorycopy(string sourcedirname, string destdirname, bool copysubdirs, string postfix) { // subdirectories specified directory. directoryinfo dir = new directoryinfo(sourcedirname); directoryinfo[] dirs = dir.getdirectories(); // if destination directory doesn't exist, create it. if (!directory.exists(destdirname)) { directory.createdirectory(destdirname); } // files in directory , re-create them new location. fileinfo[] files = dir.getfiles(); foreach (fileinfo file in files) { string temppath = system.io.path.combine(destdirname, file.name); if (postfix == ".") { file.copyto(temppath, copysubdirs); } else if (file.name.endswith(postfix)) { file.copyto(temppath, copysubdirs); } } // if copying subdirectories, re-create them , contents new location. if (copysubdirs) { foreach (directoryinfo subdir in dirs) { string temppath = system.io.path.combine(destdirname, subdir.name); directorycopy(subdir.fullname, temppath, copysubdirs, postfix); } } } public static void filecopy(string sourcefilename, string destdirname, bool overwrite) { string destfilename = destdirname + sourcefilename.substring(sourcefilename.lastindexof('\\') + 1); // if destination directory doesn't exist, create it. if (!directory.exists(destdirname)) { directory.createdirectory(destdirname); } system.io.file.copy(sourcefilename, destfilename, overwrite); } }

}

the problem file had tried overwrite read-only. solve problem i've manually changed attributes of destination file normal (not read-only):

if (file.exists(destfilename)) { file.setattributes(destfilename, fileattributes.normal); // makes every read-only file rw file (in order prevent "access denied" error) }

hope helpful.

c#-4.0

c - What does this 'number' function do? -



c - What does this 'number' function do? -

i had question in exam - http://ideone.com/umausi

the code -

#include <stdio.h> int number(int n) { if(n == 1) homecoming n; int half = n/2; int k = 2*number(n/2) + half*half; homecoming (n%2)?(k+n):k; } int main(void) { printf("%d",number(11)); homecoming 0; }

i know to solve these type of questions, 1 should understand function doing. saves lot of time because don't have run each case(which can take longer time). instead ran case , found result. so, want know what 'number' function does? if meaningful calculating square or that. couldn't find generic reply it.

this recursive function calculate sum of n natural numbers 'n' input recursive function.

had tried sample inputs have deduced easily. below samples:-

input output

2 3

5 15

7 28

10 55

mathematical formula calculating sum of n natural numbers is:-

( n * ( n + 1 ) ) / 2

explanation ( molbdnilo ):-

suppose want sum numbers 1 100.

compute (1 + 100) + (2 + 99) + (3 + 98) + ... + (98 + 3) + (99 + 2) + (100 + 1) = 101 + 101 + ... + 101 = 100 * 101 = 10100.

since every number occurs twice in summation, sum you're looking

10100/2 = 5050;

the sum

n*(n+1)/2.

(if calculate 2*sum(n/2) number 'n', you'll notice (nn + 2n)/4, while sum(n) (2*nn + 2*n)/4). add together n*n/4 2*sum(n/2) , sum(n)).

edited in response comments:-

@halkujabra molbdnilo has given explanation.

@jonathan:- no integers include whole range of numbers on number line ( numbers without fractional part )

... -100, -50 , 0 , 50 ,100...

whole numbers non-negative integers i.e

0, 50, 100

natural numbers :- whole numbers - 0 , i.e

1, 50, 100

c function output

operating system - How is segmentation more secure than paging? -



operating system - How is segmentation more secure than paging? -

this question occurred me while reading memory management in galvin? there 2 parts didn't understand. first 1 direct question galvin. reply didn't understand "since segmentation based on logical partition of memory rather physical one, segments of size can shared 1 entry in segment tables of each user. paging there must mutual entry in page tables each page shared" 1)why easier share reentrant code in segmentation? 2)is segmentation more secure paging?why

i've never read galvin book lot of questions here asking why absurd things true , cite source.

it not easier share reentrant code using segments rather paging.

in paging system, share code can mapped different processes adding section page table. it's straight forwards process.

segmentation not more security paging.

operating-system memory-segmentation computer-science-theory

C++ How to cin a string into a vector and then display the inputs -



C++ How to cin a string into a vector and then display the inputs -

im little stuck on trying figure out how allow user come in in several strings , display strings when come in "*". help appreciated! thanks!

#include <iostream> #include <vector> #include <string> using namespace std; int main() { string input; cout<<"enter in shopping list. come in in * indicate done"<<endl; vector<string> shoppinglist(); while(cin>>input && input != *) { shoppinglist.push_back(input); } if(cin>>input == *) { write_vector(shoppinglist); } homecoming 0; }

there 2 things wrong in this:-

vector<string> shoppinglist(); //this treated function declaration...

this should be

vector<string> shoppinglist;

and then

if(cin>>input == *)

you should take input in string , compare "*"

c++ string vector cin

syntax - What does _ in Python do? -



syntax - What does _ in Python do? -

this question has reply here:

what purpose of single underscore “_” variable in python? 2 answers

i saw somewhere _ character beingness used in python like:

print _

can help me explain does?

in interactive interpreter, _ refers lastly outputed value:

>>> 1 + 1 2 >>> print _ 2 >>> 2 + 2 4 >>> print _ 4 >>>

in normal python1 code however, _ typical name. can assign other:

_ = 3 print _ # output: 3

although wouldn't recommend doing because _ terrible name. also, used convention mean name placeholder. illustration be:

a, _, b = [1, 2, 3]

which uses _ mean not interested in 2. illustration is:

for _ in range(10): function()

which means not using counter variable within loop. instead, want python phone call function 10 times , need _ have valid syntax.

1by "python", mean cpython, standard flavor of language. other implementations may take things differently. ipython illustration has underscore-only names:

the next global variables exist (so don’t overwrite them!):

[_] (a single underscore) : stores previous output, python’s default interpreter. [__] (two underscores): next previous. [___] (three underscores): next-next previous.

source: http://ipython.org/ipython-doc/rel-0.9.1/html/interactive/reference.html#output-caching-system

python syntax

jquery - css on hover text display image -



jquery - css on hover text display image -

<style> img { height: 100px; width: 100px; } .hover img { display:none; } .hover:hover img { display:block; } </style> <p>other text </p> <h1 class="hover">test 1 <img src="ghost.jpg"/></h1> <p>other text </p>

when hover moves other text display image want image hover on text , else on page. not move text create room image. know how utilize jquery, , javascript didn't know utilize in situation.

position image absolutely without top/bottom values:

class="snippet-code-css lang-css prettyprint-override">img { height: 100px; width: 100px; } .hover img { display:none; position: absolute; } .hover:hover img { display:block; } class="snippet-code-html lang-html prettyprint-override"><p>other text</p> <h1 class="hover">test 1 <img src="http://lorempixel.com/100/100" /> </h1> <p>other text</p>

jquery css image text hover

html - Centered image on top of line in Bootstrap 3 -



html - Centered image on top of line in Bootstrap 3 -

i want create layout:

<div class="row"> <div class="col-md-4 col-sm-4 col-xs-4 line"></div> <div class="col-md-4 col-sm-4 col-xs-4"><img src="http://placepic.me/profiles/160-160" width="160" height="160" class="img-circle"></div> <div class="col-md-4 col-sm-4 col-xs-4 line"></div> </div> .line { width:460px; height:2px; background:#ccc; } .img-circle { border-radius: 50%; }

http://jsfiddle.net/y8kcsr31/

i have out columns in row still doesn't work.

edit: sorry, trying accomplish https://www.dropbox.com/s/bjg2z5wud4yzy4d/screenshot%202014-11-13%2011.49.49.png?dl=0

the op has design pattern this:

using grid scheme accomplish not right way desired result.

since there no design pattern exactly in bootstrap, let's find similar:

.panel

will work. learn more: http://getbootstrap.com/components/#panels

demo: http://jsbin.com/yenade

html clean:

<div class="panel panel-default panel-profile"> <div class="panel-heading text-center clearfix"> <h4>name of person</h4> <img src="http://placepic.me/profiles/50-50" class="img-circle"> <a href="#">edit profile</a> </div> <div class="panel-body"> panel content </div> </div>

css:

.panel-profile .panel-heading { position: relative; } .panel-profile .panel-heading h4 { margin: 10px 0 20px; font-weight: normal; } .panel-profile .panel-heading img { margin: 0 auto 10px; display: block; border: 1px solid #ddd; background: #fff; } @media (min-width:400px) { .panel-profile .panel-heading { font-size: .75em; float: right; } .panel-profile .panel-heading { margin-bottom: 30px; } .panel-profile .panel-heading img { position: absolute; margin: 0; display: inline; bottom: -25px; } }

html css twitter-bootstrap twitter-bootstrap-3

web services - How do we check whether element with MinOccurs = 0 returned? -



web services - How do we check whether element with MinOccurs = 0 returned? -

i have xml schema 3rd party web service provider.

<xsd:element name="student"> <xs:sequence> <xs:element name="name" type="xs:string" minoccurs="1"/> <xs:element name="address" type="xs:string" minoccurs="0"/> <xs:element name="gender" type="xs:string" minoccurs="1"/> </xs:sequence> </xsd:element>

i going consume dataset returns web service in c# code. since address has minoccurs set 0, means web service can either homecoming value address or not returning address. example:

scenario 1: <student> <name>eddie</name> <gender>male</gender> </student> scenario 2: <student> <name>alice</name> <address>white house</address> <gender>female</gender> </student> scenario 3: <student> <name>jenny</name> <address></address> <gender>female</gender> </student>

may know how check, in c# code whether web service homecoming address.

for result set scenario 1, hide contact section form together.

for result set scenario 2, display contact section on form, , have address display.

for result set scenario 3, display contact section on form, have address field in contact section set "address not provided".

may know accomplish that?

i know can check whether elements hasvalue or isnull. how check whether result returned web service contains element (scenario 1)?

after research , testing done, think can have this:

bool showcontactflag = false; if (dataset.tables[0].columns.contains("address")) { showcontactflag = true; } else { showcontactflag = false; }

web-services

Disable all child elements using angularjs directive -



Disable all child elements using angularjs directive -

i have created directive disable of selected kid elements :

app.directive('noedisable', function () { var linkfunction = function (scope, element, attributes) { scope.text = attributes["=noedisable"]; if (scope.text == 'true') { $(element).find('input,button,a').attr("disabled", true); } }; homecoming { link: linkfunction }; });

and work example: <div noe-disable="true"> ... </div>. problem of kid elements load later, illustration after ajax phone call or when have angularjs directive within parent element add together kid elements parent, wont disabled !!! how can deal problem ?

you can utilize fieldset.

wrap fields in fieldset , utilize ng-disabled like:

<fieldset ng-disabled="shoulddisabled"> ... inputs ... </fieldset>

it automatically disable inputs within fieldset.

angularjs angularjs-directive

Magento UPS shipping don't work with Canada origin -



Magento UPS shipping don't work with Canada origin -

i using ups shipping method,my issue if set origin country usa it's showing me ups shipping options in cart , checkout page. if set origin country canada it's not showing me of ups shipping options.

i have set base of operations currency, default current , allowed currency canadian dollar, have imported rates manage currency also.

i googled lot don't found solution this.

is 1 have faced such issue, or have solution this? please help.

thank you

ups

Importing from Excel to SQL Server: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value -



Importing from Excel to SQL Server: The conversion of a varchar data type to a datetime data type resulted in an out-of-range value -

i have next excel workbook:

https://meocloud.pt/link/7cb3ef48-7556-4d36-ab9a-c247d3f7b29d/fichasteste.xls/

it's formatted imported sql database. server has next details:

as can see mapping right in importer

when seek import excel file, status same, no matter modifications columns date.

242: conversion of varchar info type datetime info type resulted in out-of-range value.

3621: statement has been terminated.

what should modify rows can imported without having error?

excel stores dates integers, if alter excel field text you'll see that, i'm not sure why you're having problem, should able direclty import excel , have dates preserved, @ to the lowest degree can using sql's import wizard ssis.

one workaround using text() function in excel date acceptable format:

=text(f2,"yyyy-mm-dd")

i importing excel using openrowset(), requires additional setup , has it's own drawbacks:

select * openrowset('microsoft.ace.oledb.12.0', 'excel 12.0;database=c:\yourexcelfile.xls', [sheet1$])

sql excel import

html5 - How I can listen for a keyword in a web browser with Javascript -



html5 - How I can listen for a keyword in a web browser with Javascript -

how can hear keyword web browser , when catched - using javascript implemented in google search app android "ok, google"?

you can pocketsphinx.js:

https://github.com/syl22-00/pocketsphinx.js

see keyword spotting demo

https://github.com/syl22-00/pocketsphinx.js/blob/master/webapp/live_kws.html

javascript html5 google-chrome voice-recognition

Running C Program on Windows 8.1 using Python (or not Python) -



Running C Program on Windows 8.1 using Python (or not Python) -

the original goal write software executable on windows platform read numbers 7-segment displays , record @ constant time interval. tried out couple of ocr libraries in python (since planning write programme in python) learned more suitable handwritten letters , redirected attending open source programme written in c, designed reading numbers 7-segment displays: http://www.unix-ag.uni-kl.de/~auerswal/ssocr/

so compiled source code in linux , planned move compiled file, along linked library files, windows machine, naively believing "exec" python script execute program. turns out couldn't - trying run programme (after manually adding .exe extension @ end , double clicking) generates response "the app cannot run on pc. find version computer, check software publisher".

so question is, whether there way execute c programme script on windows platform, , if not, might suggest me finish aforementioned task?

you can execute programme using python (like other programming languages). happens (for languages) scheme phone call , inquire underlying operating scheme execute program, because 1 of responsibilities of os.

open python repl (or write python script) , seek (this 1 of ways execute programme python)

import subprocess # if you're on windows phone call subprocess.call("notepad", shell=true) # if on linux phone call subprocess.call("ls", shell=true)

what happens python asks os execute specified programme (notepad or ls), weather os can run requested application story.

your c programme compiled on linux executable in format linux can run (probably elf format). windows requires executable files in different file format. file extensions help environment treat files appropriately. if alter extension of linux executable '.exe', not alter content, windows still not able run it.

you need recompile c programme on windows compiled programme executable on windows. if programme requires posix environment (for illustration if uses fork() syscalls or etc.), utilize cygwin on windows (that provides scheme calls , libraries available in linux windows) compile it.

python c windows

what have i done wrong (c++ quickSort)? -



what have i done wrong (c++ quickSort)? -

my quicksort code works fine number of elements except 2 elements , doesn't sort odd numbers of element.

int quicksort::partition(int beg, int end) // function find pivot point { int p = beg, pivot = list[beg], loc; (loc = beg + 1; loc <= end; loc++) { if (pivot > list[loc]) { list[p] = list[loc]; list[loc] = list[p + 1]; list[p + 1] = pivot; p = p + 1; } } homecoming p; } void quicksort::sort(int beg, int end) { if (beg < end) { int p = partition(beg, end); // calling procedure find pivot sort(beg, p - 1); // calls (recursion) sort(p + 1, end); // calls (recursion) } }

c++ quicksort

php - How do I delete a row when multiple rows have the same id -



php - How do I delete a row when multiple rows have the same id -

i have 2 tables, users , short_style.

fields of table users:

id int primary not null auto increment username password firstname lastname

data inserted users table users:

users id username password firstname lastname 1 jsmith md5hash john smith 2 jbrown md5hash jane brownish

data inserted users table short_style:

short_style id style_name style_cost style_time number_of_styles 1 bald 10 30 1 2 wash 5 15 2 1 shave 12 30 3 2 line 8 15 4 1 wash free 15 6 2 color 20 30 7

i can have users add together new style, code works perfect.

i can have users update info well, code works perfect.

i'm stuck @ deleting user info have no thought how target number_of_styles data, unique data.

from have learned (in short time) delete take 2 parameters, table name , table row (i'm assuming).

how can create work?

sorry long html, still haven't figured out how show html in comments. have:

<?php if (isset($_post['delete_servicename'])&& isset($_post['update_category'])) { $delete_servicename = $_post['delete_servicename']; $category = $_post['update_category']; $atta = '_name'; $delete = "$category$atta"; $query = "select $delete $category `id`='".$_session['user_id']."'"; $query_run = mysql_query($query); if(mysql_num_rows($query_run)==1) { $dquery = "delete $category $id = '".$_session['user_id']."'"; } } ?> <form action="services_update.php" method="post"> <div class="a_u_d_sort"> <ul> <li class="a_u_d_sort_left"> <p>category:</p> </li> <li class="a_u_d_sort_right"> <select name="update_category"> <option value="">select</option> <option value="short_style">short style</option> <option value="medium_style">medium style</option> <option value="long_style">long style</option> <option value="other_services">other service</option> </select> </li> </ul> </div> <div class="a_u_d_sort"> <ul> <li class="a_u_d_sort_left"> <p>service name:</p> </li> <li class="a_u_d_sort_right"> <input type="text" name="delete_servicename"></input> </li> </ul> </div> <button class="add" type="submit">delete</button> </form>

you should utilize auto-increment field every table create have unique id utilize when deleting rows.

if that's not alternative you, you'll have modify delete query create sure you're deleting right row:

$dquery = "delete $category $id = '".$_session['user_id']."' , `style_name` = $stylename , style_cost = $stylecost , style_time = $styletime , number_of_styles = $numberofstyles limit 1";

edit

i didn't not realize number_of_styles auto increment. in case can simply:

$dquery = "delete $category number_of_styles = $numberofstyles limit 1";

since it's unique there no need mention other fields.

php mysql delete-row

c# - Executing Sql Server Stored Procedure and getting OUTPUT INSERTED value -



c# - Executing Sql Server Stored Procedure and getting OUTPUT INSERTED value -

i want inserted row key when inserting records.then wrote sample sql sp.

create procedure temp begin set nocount on insert farmer_landdetails (oth_mas_key, fmr_key, anim_typ_key, anim_count, land_type_key, land_availability) output inserted.oth_det_key values(1,1,1,1,1,1) end go

how out value c# ?

the output clause of storedprocedure returns single row single value. right method result through executescalar method of sqlcommand

using(sqlconnection cnn = new sqlconnection(....)) using(sqlcommand cmd = new sqlcommand("temp", cnn)) { cnn.open(); cmd.commandtype = commandtype.storedprocedure; int result = convert.toint32(cmd.executescalar()); }

notice have no thought datatype oth_det_key. assume integer hence convert.toint32() on homecoming value of executescalar

c# sql-server

php - How to check if file (image) upload is completed -



php - How to check if file (image) upload is completed -

my scenario, user posting info , image via android device on server. script handles upload wait response until image uploaded 100%.

actually it's not clear me, since i'm still beginner, if script already. when posting item via android, receive response pretty fast , image between 1 , 2mb.

this script i'm using now:

<?php /************************************************ required php files ************************************************/ require_once("../models/funcs.php"); require_once("../models/db-settings.php"); /************************************************ functionality ************************************************/ $image_path = "../images/items/"; $image_name = $_files['uploaded_file']['name']; $user_id = $_post['user_id']; $query = ... $result = $my_db->query($query); $image_path = $image_path . basename( $_files['uploaded_file']['name']); if(move_uploaded_file($_files['uploaded_file']['tmp_name'], $image_path) && !$my_db->error) { echo 200; } else{ echo 400; echo $my_db->error; echo "there error uploading file, please seek again!"; echo "filename: " . basename( $_files['uploaded_file']['name']); echo "target_path: " .$target_path1; } ?>

this how php has worked. script run 1 time upload finished.

only it's possible monitor file upload progress.

php

asp.net mvc - Set Default Route for a Controller as Index View -



asp.net mvc - Set Default Route for a Controller as Index View -

so have url:

www.mywebsite/signup/index

that works fine.

what want add together new route mapping routeconfig class allows next url work:

www.mywebsite/signup

i have tried:

routes.maproute( name: "signup", url: "{controller}/", defaults: new { controller = "signup", action = "index", id = urlparameter.optional }

and:

routes.maproute( name: "signup", url: "{controller}", defaults: new { controller = "signup", action = "index", id = urlparameter.optional }

and:

routes.maproute( name: "signup", url: "{controller}/*", defaults: new { controller = "signup", action = "index", id = urlparameter.optional }

my routeconfig class has been customized , default routing when creating new asp.net mvc project has been changed, looks this:

routes.maproute( name: "defaultconstrained", url: "{controller}/{action}/{id}", defaults: new { action = "index", controller = "home", id = urlparameter.optional }, constraints: new { controller = constrollersascsv() } ); routes.maproute( name: "sitelogin", url: "{site}", defaults: new { controller = "user", action = "login", site = "" }, constraints: new { site = new excludeanduseregex() } ); routes.maproute( name: "default", url: "{controller}/{action}/{id}", defaults: new { controller = "user", action = "login", id = urlparameter.optional } );

where constraint method constrollersascsv (which don't know doing) is:

public static string constrollersascsv(string optional = null) { var list = getcontrollernames(); var sb = new stringbuilder(); sb.append("("); if (!string.isnullorwhitespace(optional)) sb.append(optional); foreach (var cont in list) { if (sb.length > 1) sb.append("|"); sb.append(cont.replace("controller", "")); } sb.append(")"); homecoming sb.tostring(); }

and implementation of getcontrollernames is:

public static list<string> getcontrollernames() { list<string> controllernames = new list<string>(); getsubclasses<controller>().foreach( type => controllernames.add(type.name.tolower())); getsubclasses<apicontroller>().foreach( type => controllernames.add(type.name.tolower())); controllernames.add("elmah"); homecoming controllernames; }

and implementation of getsubclasses is:

private static list<type> getsubclasses<t>() { homecoming assembly.getcallingassembly().gettypes().where( type => type.issubclassof(typeof(t))).tolist(); }

the error getting when going www.mywebsite.com/signup is:

**http error 403.14 - forbidden**

asp.net-mvc asp.net-mvc-4

objective c - iOS UITableViewCell needs to be pressed twice to call didSelectRowAtIndexPath -



objective c - iOS UITableViewCell needs to be pressed twice to call didSelectRowAtIndexPath -

i have uitableview requires touch twice select cell.

more specifics:

two touches needed after table has been scrolled way or way down. only sec touch calls didselectrowatindexpath. when table opens in natural "scrolled position", cells indeed selectable 1 touch. if scroll little bit (not way down/up), cells select 1 touch. if cells not fill whole table , scrolling not required, works fine. go way top or bottom , have touch twice.

i have feeling first touch making uitableviewcells selectable or activating table in way.

things have checked:

my code doesn't phone call diddeselectrowatindexpath anywhere. no uigesturerecognizers using setcancelstouchesinview:.

other settings on table:

self.tableview.scrollenabled = yes; self.tableview.showsverticalscrollindicator = no; self.tableview.bounces = no; self.tableview.separatorstyle = uitableviewcellseparatorstylesingleline;

what's causing this?

update

oddly enough, setting self.tableview.bounces = yes; fixed problem.

i still looking root cause in case has improve answer. table not bounce, not if costs key functionality.

may implemented diddeselect instead of didselect?

ios objective-c uitableview

php - when try to add more field and select then its conflict first row -



php - when try to add more field and select then its conflict first row -

when trying select alternative value form row 1 there's no problem if add together more , select optional value in sec row getting conflict first. every time when select optional value first row conflict want first row alter while changing first select alternative . sec row select alter sec row values.

index.php

<?php if(!empty($_post["save"])) { $conn = mysql_connect("localhost","root",""); mysql_select_db("ajaxphp",$conn); $itemcount = count($_post["item_name"]); $itemvalues = 0; $query = "insert item (item_name,item_price) values "; $queryvalue = ""; for($i=0;$i<$itemcount;$i++) { if(!empty($_post["item_name"][$i]) || !empty($_post["item_price"][$i])) { $itemvalues++; if($queryvalue!="") { $queryvalue .= ","; } $queryvalue .= "('" . $_post["item_name"][$i] . "', '" . $_post["item_price"][$i] . "')"; } } $sql = $query.$queryvalue; if($itemvalues!=0) { $result = mysql_query($sql); if(!empty($result)) $message = "added successfully."; } } ?> <html> <head> <title>php jquery dynamic textbox</title> <link href="style.css" rel="stylesheet" type="text/css" /> <script src="http://code.jquery.com/jquery-2.1.1.js"></script> <script> function addmore() { $("<div>").load("input.php", function() { $("#product").append($(this).html()); }); } function deleterow() { $('div.product-item').each(function(index, item){ jquery(':checkbox', this).each(function () { if ($(this).is(':checked')) { $(item).remove(); } }); }); } </script> </head> <body> <form name="frmproduct" method="post" action=""> <div id="outer"> <div id="header"> <div class="float-left">&nbsp;</div> <div class="float-left col-heading">item name</div> <div class="float-left col-heading">item price</div> </div> <div id="product"> <?php require_once("input.php") ?> </div> <div class="btn-action float-clear"> <input type="button" name="add_item" value="add more" onclick="addmore();" /> <input type="button" name="del_item" value="delete" onclick="deleterow();" /> <span class="success"><?php if(isset($message)) { echo $message; }?></span> </div> <div class="footer"> <input type="submit" name="save" value="save" /> </div> </div> </form> </body> </html>

input.php

<script type="text/javascript" src="js/jquery.min.js"></script> <script> function salesdetail(item_index) { alert(item_index); $.ajax({ url: 'getsaleinfo.php', type: 'post', data: {item_index:item_index},` success:function(result){ alert(result); $('#div1').html(result); } }); } </script> <div class="product-item float-clear" style="clear:both;"> <div class="float-left"><input type="checkbox" name="item_index[]" /></div> <div class="float-left"><select name="item_index" id="item_index" class="required input-small" onchange="salesdetail(this.value);" > <option>select</option> <?php $conn = mysql_connect("localhost","root",""); mysql_select_db("ajaxphp",$conn); $result = mysql_query("select * item"); while($row=mysql_fetch_assoc($result)) { echo "<option>".$row['item_name']."</option>"; } ?> </select> </div> <div class="float-left" id="div1"><input type="text" id="unit_price" name="unit_price" /></div> </div>

and getsaleinfo.php

<?php $conn = mysql_connect("localhost","root",""); mysql_select_db("ajaxphp",$conn); $supplier= $_post['item_index']; $sql = "select * item item_name='$supplier'"; $rs = mysql_query($sql); ?> <?php if($row = mysql_fetch_array($rs)) { ?> <div class="float-left"> <!--<label id="unit" ></label>--> <input type="text" name="unit_price" id="unit_price" class="input-mini" value="<?php echo $row['item_price'];?>" > </div> <?php } ?>

database

create table if not exists `item` ( `id` int(11) not null auto_increment, `item_name` varchar(255) not null, `item_price` int(11) not null, primary key (`id`) ) engine=innodb default charset=latin1 auto_increment=3 ; insert `item` (`id`, `item_name`, `item_price`) values (1, 'hello', 21), (2, 'hi', 22);

/*------------------------index.php--------------------------*/ <?php if (!empty($_post["save"])) { $conn = mysql_connect("localhost", "root", ""); mysql_select_db("ajaxphp", $conn); $itemcount = count($_post["item_index"]); $itemvalues = 0; $query = "insert item (item_name,item_price) values "; $queryvalue = ""; ($i = 0; $i < $itemcount; $i++) { if (!empty($_post["item_index"][$i]) || !empty($_post["unit_price"][$i])) { $itemvalues++; if ($queryvalue != "") { $queryvalue .= ","; } $queryvalue .= "('" . $_post["item_index"][$i] . "', '" . $_post["unit_price"][$i] . "')"; } } $sql = $query . $queryvalue; if ($itemvalues != 0) { $result = mysql_query($sql); if (!empty($result)) $message = "added successfully."; } } ?> <html> <head> <title>php jquery dynamic textbox</title> <link href="style.css" rel="stylesheet" type="text/css" /> <script src="http://code.jquery.com/jquery-2.1.1.js"></script> <script> var cnt = 1; function addmore() { $("<div>").load("input.php?cnt=" + cnt, function() { $("#product").append($(this).html()); cnt++; }); } function deleterow() { $('div.product-item').each(function(index, item) { jquery(':checkbox', this).each(function() { if ($(this).is(':checked')) { $(item).remove(); } }); }); } </script> </head> <body> <form name="frmproduct" method="post" action=""> <div id="outer"> <div id="header"> <div class="float-left">&nbsp;</div> <div class="float-left col-heading">item name</div> <div class="float-left col-heading">item price</div> </div> <div id="product"> <?php require_once("input.php") ?> </div> <div class="btn-action float-clear"> <input type="button" name="add_item" value="add more" onclick="addmore();" /> <input type="button" name="del_item" value="delete" onclick="deleterow();" /> <span class="success"><?php if (isset($message)) { echo $message; } ?></span> </div> <div class="footer"> <input type="submit" name="save" value="save" /> </div> </div> </form> </body> </html>

input.php

/*------------------------input.php--------------------------*/ <script type="text/javascript" src="js/jquery.min.js"></script> <script> function salesdetail(item_index, item_id) { alert(item_index); $.ajax({ url: 'getsaleinfo.php', type: 'post', data: {item_index: item_index, item_id: item_id}, success: function(result) { alert(result); $('#div_' + item_id).html(result); } }); } </script> <?php $_request['cnt'] = (isset($_request['cnt'])) ? $_request['cnt'] : 0; ?> <div class="product-item float-clear" style="clear:both;"> <div class="float-left"><input type="checkbox" name="item_ind[]" id="item_ind_<?php echo $_request['cnt']; ?>" /></div> <div class="float-left"><select name="item_index[]" id="item_index_<?php echo $_request['cnt']; ?>" class="required input-small" onchange="salesdetail(this.value, '<?php echo $_request['cnt']; ?>');" > <option>select</option> <?php $conn = mysql_connect("localhost", "root", ""); mysql_select_db("ajaxphp", $conn); $result = mysql_query("select * item"); while ($row = mysql_fetch_assoc($result)) { echo "<option>" . $row['item_name'] . "</option>"; } ?> </select></div> <div class="float-left" id="div_<?php echo $_request['cnt']; ?>"><input type="text" id="unit_price_<?php echo $_request['cnt']; ?>" name="unit_price[]" /></div> </div>

getsaleinfo.php

/*------------------------getsaleinfo.php--------------------------*/ <?php $conn = mysql_connect("localhost", "root", ""); mysql_select_db("ajaxphp", $conn); $supplier = $_post['item_index']; $sql = "select * item item_name='$supplier'"; $rs = mysql_query($sql); ?> <?php $_request['item_id'] = (isset($_request['item_id'])) ? $_request['item_id'] : ''; if ($row = mysql_fetch_array($rs)) { ?> <div class="float-left"> <input type="text" name="unit_price[]" id="unit_price_<?php echo $_request['item_id']; ?>" class="input-mini" value="<?php echo $row['item_price']; ?>" > </div> <?php } ?>

php mysql