Posts

Showing posts from March, 2011

php - How to prevent duplicate email addresses from being registeres? -

i have been making login/register system , 1 problem have run not allowing duplicate email addresses being registered. want work database wont accept data duplicate email , user alerted too. sort of new php unsure of how this. thanks. my php if (empty($_post['email'])) { $error[] = 'please enter email '; } else { if (preg_match("/^([a-za-z0-9])+([a-za-z0-9\._-])*@([a-za-z0-9_-])+([a-za-z0-9\._- ]+)+$/", $_post['email'])) { //regular expression email validation $email = $_post['email']; } else { $error[] = 'your email address invalid '; } } if (empty($_post['password'])) { $error[] = 'please enter password '; } else { $password = $_post['password']; } if (empty($error)) //send database if there's no error ' { // if everything's ok... // make sure email address available: $query_verify_email = "select * members email ='

scala - Change while loop to Stream but missing the last element -

i've tried replace while loop stream when use stream version, last element missing. think understand why it's missing can't figure how fix this. suggesting? there better way this? thanks using stream: if(cursor.movetofirst) { val result = stream.continually(( song( cursor.getlong(c(basecolumns._id)), cursor.getstring(c(mediacolumns.title)) ), cursor.movetonext)) .takewhile(_._2) .map(_._1) result.tolist } here while loop version works fine. cursor.movetofirst() var = 0 var list: list[song] = list.empty while (i < cursor.getcount()) { val s = song( cursor.getlong(c(basecolumns._id)), cursor.getstring(c(mediacolumns.title))) = + 1 list = list :+ s cursor.movetonext() note: movetonext move cursor next row. method return false if cursor past last entry in result set. suppose have 1 entry. produce tuple (song, false) and throw away. that's no good. want keep song though there's not another song ther

Java read String on batch -

i have batch follows: @echo off java main 127.0.0.1 pause now want number after 'main' in code above string, can change string editing batch file. public static void main (string args[]) { .... string ip_string=args[0]; .... } does work?

android - Phonegap Storage Methods. Are they different -

http://docs.phonegap.com/en/2.8.0/cordova_storage_storage.md.html#storage this link official guide. very confused. first half of page describes storage method , seemingly lower down on page local storage method described. are these 2 things distinctly different. know there size limit of 5mb local storage implementation, there similar size limit on sqlite storage method. or wrong , these 2 things describing 2 sides of same coin? any clarification appreciated. the local storage key value paired methodology storing data sqlite storage uses actual database structure store complex data. however there 1 more option jstorage.

Word 2010 VBA: Search for text and replace with section break -

i searching specific text within document, deleting text , adding section break. can code work 1 instance. when tried while loop, checking each line, word crashed. with selection.find .text = "instructoroverview" .replacement.text = "" .forward = true .wrap = wdfindcontinue .format = false .matchcase = false .matchwholeword = false .matchwildcards = false .matchsoundslike = false .matchallwordforms = false end selection.find.execute selection if .find.forward = true .collapse direction:=wdcollapsestart else .collapse direction:=wdcollapseend end if .find.execute replace:=wdreplaceone if .find.forward = true .collapse direction:=wdcollapseend else .collapse direction:=wdcollapsestart end if .find.execute end selection.insertbreak type:=wdsectionbreaknextpage you should show loop-code well. however, setting .wrap = wdfin

c++ - compare two maps and identify distinct elements -

compare 2 maps ( std::map<std::string, std::unsigned int> ) value , identify distinct elements. typedef std::map<std::string /* file name*/, unsigned int /*crc*/> mmap; list of files each file in list calculated crc. file name not changed, crc changet. if have 2 maps, distinct entries, named oldmap , newmap , can use std::set_difference unique entries both maps. see following example of how can done. #include <map> #include <string> #include <algorithm> #include <utility> #include <iterator> #include <iostream> int main() { // 2 maps containing values. std::map<std::string, int> oldmap { {"test1", 1}, {"test2", 2}, {"test3", 3} }; std::map<std::string, int> newmap { {"test2", 2} }; // create new map holds distinct pairs. std::map<std::string, int> diffmap; // add distinct pairs diffmap. std::set_difference(begin(oldmap), end(oldma

html - CSS: onHover button to display multiple links -

i have button used part of navigation bar. what need when user hovers on button, buttons text becomes hidden, , 3 different links appear inside button. the initial button shouldn't have link attached it, 3 options appear after hovered over. hopefully makes sense; here fiddle might make clearer. <ul class="ulmenu"> <li><a href=# class="a">test</a></li> </ul> at simplest, i'd suggest following: <ul id="nav"> <li>navigation</li> <li><a href="#opt1">option 1</a></li> <li><a href="#opt2">option 2</a></li> <li><a href="#opt3">option 3</a></li> </ul> with following css: /* default display 'li' elements: */ #nav li { display: inline-block; } /* hides 'li' elements follow 'li' element, hides 'li:first-child' w

terminal - Access VMWare OS from Android Phone through WiFi -

i have centos6 installed image in vmware, lets call dev environment. host pc running windows 7. i've been developing websites setup quite time now. my problem begins when started working on themes mobile devices. sure can use chrome or firefox's developer tools over-ride user-agents , test layout in regular browser. test in android phone, i'll have commit changes , deploy site(to staging), time-consuming. i able able test work in android phone while it's still in dev environment. imagine quite possible, don't know how. so, here issues: how access vmware images on wifi? have laptop , can't access domain registered in dev environment on wifi? there setting this? or should able access have problem in laptops wifi?(which do, btw) if i'm correct, there should 'hosts' file in linux edit redirect domain? how find this? need root phone? if i'm not correct, how should able this? i able access dev environment on ssh in android device. i'

c# - MSMQ System.Messaging high resource usage -

i have make c# console application uses timer connects msmq every 10 seconds data insert oracle database. issue log in , log off domain , create high cpu create security audit log waste resources. my console application runs task schedule. code below using system; using system.collections.generic; using system.linq; using system.text; using system.messaging; using system.xml; using system.io; using system.timers; using oracle.dataaccess.client; using system.data; namespace msmq_news { class program { private static system.timers.timer atimer; static void main(string[] args) { try { // create timer ten second interval. atimer = new system.timers.timer(60000);//10000 // hook elapsed event timer. atimer.elapsed += new elapsedeventhandler(ontimedevent); // set interval 2 seconds (2000 milliseconds). //atimer.interval = 10000; atimer.enabled = true;

jquery - Getting empty Response from get request from Rest service in MVC 4 Asp.net -

Image
i have simple method create list of objects team, convert json , returns it. public actionresult index() { var teams = new list<team>() { new team{ name = "caracas f.c", city = "caracas", id = 1}, new team{ name = "millonarios", city = "bogota", id = 2}, new team{ name = "independiente", city = "bogota", id = 3}}; var jsondata = new { teamsdata = teams }; return json(jsondata, jsonrequestbehavior.allowget); } when go url ( http://prototypeteam.apphb.com/ , check out yourself), can see json {"teamsdata":[{"id":1,"name":"caracas f.c","city":"caracas"},{"id":2,"name":"millonarios","city":"bogota"},{"id":3,"name":"independiente","city":"bogota"}]} but when try json using jquery returns without response: self.allteam

d3.js - Updating graph as I drag a point around -

i making line of best fit app using d3 in want line of best fit update drag points around. got work when drag ends, line updates itself. however, when comes updating point being dragged, unable so. here drag function: var move = d3.behavior.drag() .on("drag",drag) .on("dragend",function(){ dict.length = 0; var dragpoint = d3.select(this); var newx = x_scale2(parseint(dragpoint.attr("cx"))); var newy = y_scale2(parseint(dragpoint.attr("cy"))); model.replace_point(dragpoint.attr("id"),newx,newy); updatedisplay(); }); function drag(){ var dragpoint = d3.select(this); dragpoint .attr("cx",function(){return d3.event.dx + parseint(dragpoint.attr("cx"));}) .attr("cy",function(){return d3.event.dy +parseint(dragpoint.a

php - Files losing all data when saving -

got complicated problem little information on it. ok have site people upload files onto, files base 64 encoded , sent site. second site saves file , adds database record file. somewhere in process, 1 in 8 files losing content. this system has been 5 months, error has appeared in last month, co-inciding server move. there nothing in common files e.g. extension or source, nothing significant time, , no php errors being logged. have got copies of files failed, , when try upload them, work fine. the first site wont let through blank file, has happening in second site, believe maybe have missed php config option thats causing this. thoroughness sake here code saving file: $filename = time() . ($id->count + 1) . '-' . $this->post['jobid'] . $this->post['filetype']; file_put_contents(dir_tmp . "cvs" . ds . $filename, base64_decode($this->post['cv']), file_append); the server in question linux centos 6 64 bit. so sum up, probl

c# - Backtracking Search Algorithms -

Image
my real question is, 'why doesn't backtracking speed search?' i'm not sure if makes sense without more context... this question academic - code 'works' , program finds solutions i'm expecting....but want make sure understand terminology. illustrate things, let's use specific example we'd need search algorithm - n-queens problem. n-queens problem - placing n queens on n×n chessboard in such way no queen can attack another. one solution there lots of example code on internet can found searching for, 'n-queens backtracking', , wikipedia's article on backtracking uses n-queens in explanation of backtracking ( http://en.wikipedia.org/wiki/backtracking ). idea, understand it, given board configuration invalid - let's 2 places queens can attack each other, algorithm disregards board configurations made adding additional pieces. i've implemented (non-recursive/non-backtracking) depth-first , breadth-first version

javascript - I'm `keyup` listening to elements of a class, but I want to get an attribute from the field that is "keyup'ed" -

in rails app listening on bunch of input fields class regex-field . listening coffeescript code. every time typing 1 of input fields, resetregex method triggered. can see below want value of regexfield.attr "regex" . seems same value comes out regardless of field i'm typing into. idea i'm doing wrong? $ -> createsubtable(data, email_type_id) resetregex() $(document).ajaxsuccess (event, request, settings) -> resetregex() resetregex = -> regexfield = $(".regex-field") regexfield.off "keyup" regexfield.keyup (event) -> email_type = regexfield.attr "email-type-id" console.log regexfield # => [input#order-id-regex.regex-field, input#name-regex.regex-field, input#mail-address-regex.regex-field, prevobject: jquery.fn.jquery.init[1], context: document, selector: ".regex-field", jquery: "1.9.1", constructor: function…] console.log rege

c# - Changing the property of A object affects the changing the property of B object -

i have line of code: someclass = new someclass(); someclass b = a; a.price = 15; b.price = 20; console.writeline(a.price); // output 20 first create object a, , object b. object b assigned object a. when initialize property price object, can see price of object 15 , of b 20. when assign 20 price of object b, in same time changes affected on price of object a. why? i mean happens in memory cause this? someclass reference type (declared class someclass { ... } ). a , b reference same instance of class (the 1 create new someclass() . means, points same instance (then same memory item). to have behavior want have use value type (declared struct somestruct { ... } ).

java - Draw rectangles on top of a picture in JavaFX2 -

i'm trying draw rectangles on picture using mouse events in javafx2. right now, have imageview in stackpane , add rectangles on it. problem if set rectangles' x , y mouseevent x , y, rectangles' stay centered in stackpane. i guess it's stackpane centers every child default, can't find decent solution problem. guys please point me in right direction? here code: @fxml private stackpane stack_pane; private final imageview image_view = new imageview(); private final set<rectangle> rectangles = new hashset<rectangle>(); private final simpledoubleproperty selectionrectinitialx = new simpledoubleproperty(); private final simpledoubleproperty selectionrectinitialy = new simpledoubleproperty(); private final simpledoubleproperty selectionrectcurrentx = new simpledoubleproperty(); private final simpledoubleproperty selectionrectcurrenty = new simpledoubleproperty(); private rectangle selectionrect; @override public void initialize(final url fx

Java Web Start - load native dependency with another native dependency -

i using java web start launch java application depends on third party native libraries. these native libraries subsequently load native library ( commonlib ) dependency using loadlibrary/dlopen. when not using web start, works expected when native libraries located in same directory. web start, however, requires native libraries packed in jar file , referenced in jnlp file, did: <!-- windows os --> <resources os="windows"> <nativelib href="native/native-windows.jar" /> </resource> <!-- linux os --> <resources os="linux"> <nativelib href="native/native-linux.jar" /> </resources> <!-- mac osx --> <resources os="mac os x"> <nativelib href="native/native-osx.jar"/> </resources> the native libraries load fine fail load dependency commonlib - c++ loadlibrary/dlopen call fails because file pr

Java + Jena + Rdf : need help writing the correct sparql Query -

i have rdf file 1 ( test.rdf ): <?xml version="1.0"?> <rdf:rdf xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:vocab="http://www.datiopen.it/rdf/resource/vocab/" xmlns:owl="http://www.w3.org/2002/07/owl#" xmlns:db="http://www.datiopen.it/rdf/resource/" xmlns:xsd="http://www.w3.org/2001/xmlschema#" xmlns:rdfs="http://www.w3.org/2000/01/rdf-schema#" xmlns:map="http://www.datiopen.it/rdf/resource/#" xmlns:dcterms="http://purl.org/dc/terms/" xml:base="http://www.datiopen.it/rdf/resource/" > <rdf:description rdf:about="http://www.w3.org/2000/01/rdf-schema#label"> <rdf:type rdf:resource="http://www.w3.org/1999/02/22-rdf-syntax-ns#property"/> </rdf:description> <rdf:description rdf:about="vocab/view_tbeni_architettonici"> <rdfs:label>trentino-alto adige - beni architettonici ed artistici</rdfs:label&g

dataset - How to collect data from multiple databases and bind them in single datagridview? -

following code works single dataset when try dataset array sqldataadapter.fill() not work. trying connecting 6 different databases , run same sql query on them , collect data , show whole data 6 dbs in single datagridview. how it? thanks, dataset[] myset = new dataset[6]; dataset finset = new dataset(); (int j = 0; j <= 5; j++) myconnection.open(); (int = 0; <= specrowcount - 2; i++) { cleandesc = datagridview2.rows[removalpointer].cells[1].value.tostring().replace("'", "''").trim(); classname = datagridview2.rows[removalpointer].cells[0].value.tostring().trim(); str = "use " + mydatabases[j] + " select top 1 x, y, z, t, h, f, d, " + "s, d, c, s, a, d, f, g, " + "s, f, a, dfrom tttt c=1 , a=1 , " + "d='&quo

android - I've tried everything and still can't solve the "R cannot be resolved to a variable" message -

setcontentview(r.layout.activity_main); gives me error message in title. i've tried delete , renerate r, clean project , nothing. activity_main right there registered in r. have no problems in /res, no red crosses or problems in problems tab. there's no import android.r in activity. i've tried find here , nothing. "r cannot resolved variable"? what's going on? the simplest coding pattern, , see examples do, have activities (and other resource-dependent classes) reside in java package declared in manifest's package attribute. way, r auto-imported, , don't have think it. you welcome have r references in other packages, have import r manifest's package (e.g., import com.commonsware.sample.r; ).

android - Cube in openGL ES -

Image
i draw transparent mesh cube in android similar following image: any highly appreciated. if have familarity opengl 3d programming should straightforward implement. page looks has need understand how this, few tweaks have solution. general opengl tutorials following page place reference well. if stuck implementing this, can followup specific questions issues arise.

python 2.7 - write into indexed array in pyopencl -

hi wrote code in pyopencl sparse random vector problem can not write value indexed array problem? output zero!! here code import pyopencl cl import numpy np pyopencl import array pyopencl import clrandom ctx = cl.create_some_context() queue = cl.commandqueue(ctx, properties=cl.command_queue_properties.profiling_enable) x=array.zeros(queue, 512, dtype=np.float32 ) indices = clrandom.rand(queue, 17 , dtype=np.int32 ,luxury=2, a=1 , b=512) clrandom.ranluxgenerator(queue,luxury=0).fill_normal(x[indices], mu=0, sigma=1) print x it seems x[indices] returning copy instead of view. >>> import pyopencl cl >>> import numpy np >>> pyopencl import array >>> pyopencl import clrandom >>> >>> ctx = cl.create_some_context() >>> queue = cl.commandqueue(ctx, ... properties=cl.command_queue_properties.profiling_enable) >>> >>> x=array.zeros(queue, 512, dtype=np.float32 ) >>&

php - MySQL "like" (false positive) -

i have table in database, field named "tags", e.g. ios, android, java, javascript, etc.. , want select items in table, match tag, e.g id | name | tags -- | ------- | ----- 1 | name1 | ios,android 2 | name2 | javascript,css 3 | name3 | html,java now, if want items have tag 'java' (only 1 id=3), this: select * posts tags '%java%'; but, imagine, returns me second (javascript) , third (java) items.. how can return third? in mysql, best solution find_in_set() : select * posts find_in_set('java', tags) > 0; in mysql , other databases, can like , need put delimiters around everything: select * posts concat(',', tags, ',') '%,java,%'; the delimited prevent confusion similar tags (well, confusion doesn't involve commas).

https - how to config a spdy proxy with httpclient(or others) on android platform -

recently trying setup spdy proxy android platform follows: [client] ----spdy---- [spdy proxy] ----http---- [squid] ----... i try use shrpx spdy proxy can not configure on client end, 1 has suggestions how work out? httpclient possible scenario? example codes appreciated.

PHP to jQuery - catching the json -

here's want do. user submits form (a single text input) , send php. php returns this; {"status":"true","custid":"00001","custname":"john"} i know in json format, don't know how catch , use value can returned values. $(function(){ $('#icnumber-form').submit(function(){ var icno = $('#icnumber').val(); var purl = 'php/create_process.php' $.ajax({ type : 'post', url : purl, cache : false, data : icno, datatype: 'json', success : function(response){ var json = $.parsejson(response); alert(json.message); }, beforesend:function(){ $('.cust-exist-view').show(); } }); return false; }) }); since set datatype json , response comes parsed object, don't try parse yourself. success : function

Objective C - Create text file to read and write line by line in Cocoa -

i building mac app,i have 2 problem: i want create text file read , write data on it. don't know how crate text file read , write data. use struct? i want create xml file read , write data on it. can create struct xml? do have suggestion? in advance well, create file, use [[nsfilemanager defaultmanager] createfileatpath:@"your/path" contents:nil attributes:nil]; this creates empty file, can write or read from. write text (or xml), use nsstring 's writetofile:atomically:encoding:error: method nsstring *str = //your text or xml [str writetofile:"your/path" atomically:yes encoding:nsutf8stringencoding error:nil]; to read file, make nsstring contents of file nsstring *contents = [nsstring stringwithcontentsoffile:@"your/path"]; or, if not contain string, nsdata object file nsdata *contents = [nsdata datawithcontentsoffile:@"your/path"];

How to implement mySQL dynamic query in PHP? -

i can produce output: +----------+------------+------------+------------+ | startt | 2013-04-01 | 2013-04-02 | 2013-04-03 | +----------+------------+------------+------------+ | 08:00:00 | donald | daisy | mickey | | 12:00:00 | pluto | goofy | minnie | | 14:00:00 | null | mickey | null | +----------+------------+------------+------------+ from original data: mysql> select * test; +------------+----------+----------+--------+ | startd | startt | duration | name | +------------+----------+----------+--------+ | 2013-04-01 | 08:00:00 | 4 | donald | | 2013-04-02 | 08:00:00 | 4 | daisy | | 2013-04-03 | 08:00:00 | 4 | mickey | | 2013-04-03 | 12:00:00 | 4 | minnie | | 2013-04-01 | 12:00:00 | 4 | pluto | | 2013-04-02 | 12:00:00 | 4 | goofy | | 2013-04-02 | 14:00:00 | 4 | mickey | +------------+----------+----------+--------+ mysql> using mysql dynamic query: 1 set @sql =

fragment - Trying to resume app but losing variable assignment - android -

i developing android app sends/receives data via bluetooth. i have activity has connect button , disconnect button in 1 fragment , fragment doesn't have ui contains bluetooth methods. when connect button pressed call fragment.bluetoothconnect() start connection process. process works fine, until user rotates screen. when rotate screen try initiate connection, null pointer exception thrown. the variables throwing null exceptions 3 assigned during onresume() method in bluetooth fragment. have tried moving them oncreate() , onattach() no success. in bluetooth fragments onresume method have following lines of code: @override public void onresume() { super.onresume(); appcontext = getactivity().getapplicationcontext(); //get activity context btdevicearray = new arraylist<bluetoothdevice>(); btdevicenames = new arraylist<string>(); if (appcontext == null) log.d(bttag,"appcontext null "); else log.d(bttag,"appcont

android - Ask about TranslateAnimation -

i'm using translateanimation(float fromxdelta, float toxdelta, float fromydelta, float toydelta) fromxdelta, toxdelta, fromydelta, toydelta pixel. how change pixel percentage (i don't want use animation wiht xml file)? you need use translateanimation constructor takes typing of input. animation.relative_to_self move animation in reference 1.0f equals 100% of length/width of object translated.

python 2.7 - Round pandas datetime index? -

i reading multiple spreadsheets of timeseries pandas dataframe , concatenating them common pandas datetime index. datalogger logged timeseries not 100% accurate makes resampling annoying because depending on if time higher or lower interval being sampled create nans , starts make series broken line. here's code def loaddata(filepaths): t1 = time.clock() in range(len(filepaths)): xl = pd.excelfile(filepaths[i]) df = xl.parse(xl.sheet_names[0], header=0, index_col=2, skiprows=[0,2,3,4], parse_dates=true) df = df.dropna(axis=1, how='all') df = df.drop(['decimal year day', 'decimal year day.1', 'record'], axis=1) if == 0: dfs = df else: dfs = concat([dfs, df], axis=1) t2 = time.clock() print "files loaded dataframe in %s seconds" %(t2-t1) files = ["london lysimeters corrected 5min.xlsx", "london water balance 5min.xlsx"] data = l

java - Sonar dead store to local variable -

i have following code , sonar telling me following error message: dead store descriptions1 in new com.dscsag.dsct2c.test.teststep(integer, string, model) in follwing code: for (integer count = 0; count < teststepcount; count++) { if (xmlreader.istestexistingforordernumber(count, ordernumber, version)) { if (xmlreader.checkforduplicatetest(ordernumber, count, version)) { globalvariables.logging_logger.error("### " + this.getclass().getsimplename() + ": there 1 or more duplicated order numbers test " + count + " under test step " + ordernumber + "."); model.setstatustext("status_duplicated_test", ordernumber.tostring(), statuscode.error); throw new exception(); } else { globalvariables.logging_logger.info("### " + this.getclass().getsimplename() + ": no duplicated found test " + count

Understanding exception inside linux kernel -

i trying debug our embedded linux system under low temperatures (<40c). problem not boot correctly , trying figure out why. after analysis saw kernel goes panic during start-up following output: can: controller area network core (rev 20090105 abi 8) net: registered protocol family 29 can: raw protocol (rev 20090105) /opt/elinos-5.1/linux/linux-ppc-2.6.34/drivers/rtc/hctosys.c: unable open rtc device (rtc0) addrconf(netdev_up): eth0: link not ready ip-config: complete: device=eth0, addr=192.168.100.100, mask=255.255.255.0, gw=255.255.255.255, host=192.168.100.100, domain=, nis-domain=(none), bootserver=192.168.100.20, rootserver=192.168.100.20, rootpath= freeing unused kernel memory: 156k init init started: busybox v1.6.1 (2013-06-03 11:53:03 cest) multi-call binary addrconf(netdev_change): eth0: link becomes ready udevd-work[84]: '/sbin/modprobe -bv of:nioctlt<null>cfsl,mpc5125-ioctl' unexpect ed exit status 0x000b ------------[ cut here ]----

java - Create Database -

i have small progam in java page create database application.here code.database @ mysql.but not work me.i think code correct. private databasesource dbsource = new databasesourceimpl(); private connection connection = null; private statement statement = null; private preparedstatement preparedstatement = null; private resultset resultset = null; /** creates new form loginscreen */ public loginscreen() { initcomponents(); container c =this.getcontentpane(); c.setbackground(color.white); connection = (connection) dbsource.getconnection(); signinbtn.addactionlistener(new actionlistener() { public void actionperformed(actionevent e) { string uname = usrnametxt.gettext(); char[] pword = pwordtxt.getpassword(); string password = new string(pword); if(uname.equals("")&& password.equals("")){ util.showerrormessagedialog("please fill fields.");