Posts

Showing posts from July, 2013

regex - Matching zero or more characters in sed -

i practicing commands using sed when confused output of following command: echo 'first:second' | sed 's_[^:]*_(&)_g' my question is: why command wrap string "first" , "second" in parentheses? shouldn't colon wrapped since specified " zero or more non-colons" in regex condition? please clarify. you use [^:] which searches characters except : . experience normal comportment.

html - custom scroller(jQuery scroller ) in bootstrap dropdown -

Image
can add custom scroller(jquery scroller ) in bootstrap dropdown ? like note red line in picture i know that's been long time, had same issue , manage maybe can someone. used malihu custom scrollbar bootstrap dropdown , worked perfectly. don't forget put height or max-height dropdown receive scrollbar.

How to parse android-php json webservice response -

i new android , studying bit. in hard duty pass json objects between android , php. i have code send json object send json object server. pretty working well. printing in toast also. can please me how read , show response server application ? my code looks like package com.test.webservice; import android.util.log; import android.view.menu; import android.app.activity; import android.os.bundle; import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstream; import java.io.inputstreamreader; import java.util.arraylist; import android.widget.textview; import android.widget.toast; import org.apache.http.header; import org.apache.http.httpresponse; import org.apache.http.client.httpclient; import org.apache.http.client.responsehandler; import org.apache.http.client.methods.httppost; import org.apache.http.entity.stringentity; import org.apache.http.impl.client.basicresponsehandler; import org.apache.http.impl.client.defaulthttpclient; import org.apache.

hadoop - How to parse for occurences based on inputs in the same file -

event1 foo_id1 event1 foo_id2 event1 foo_id4 event1 foo_id6 event1 foo_id7 event1 foo_id8 event1 foo_id8 event1 foo_id1 event1 foo_id4 event2 foo_id1 event2 foo_id2 event2 foo_id3 event2 foo_id4 event2 foo_id5 event2 foo_id6 event2 foo_id8 event2 foo_id9 event2 foo_id11 the above information available file in s3 under bucket (say s3://hadoop.mycompany.com/bucket1/foo1.txt ). all events have foo_ids . events in " event2 ", know how many times foo_id (s) occur in event1 . e.g. in above case, foo_id1=2 foo_id2=1 foo_id3=0 foo_id4=2 foo_id5=0 foo_id6=1 foo_id8=2 foo_id9=0 foo_id11=0 how write hive script return data in expected format? hi can accomplished using following hive script: first need create hive external table using command create external table events (event stri

wso2esb - WSDL for WSO2 ESB proxy service -

i have done few use cases on wso2-esb including protocol mediation transformation , service-chaining. in of them had manually write wsdl proxy service. having experienced other vendor products including oracle , tibco wsdl generation done tool. would right assume in wso2 esb 1 needs manually write wsdl file expose proxy service on protocol , not see documents calling out. considering usage of wsdl in practical use cases. i have seen posts stating "you can give wsdl available @ axis2 service" of real time use cases not pass through , have custom request , response. thanks, wajid i'm confused manual wsdl creation. far can see there gaps in wsdl proxy description. when wsdl proxy wso2 have indicate wsdl expose either as: "none" , have mediate function exposed "same contract" , breaks whole idea of proxy because after clients read original wsdl , go straight original server access point. or , have several options make own wsdl.

php mysql + create a friend request system -

i creating friend request system allow user send request each other add friends facebook , have 2 conditions if : the user profile owner can not add him self echo error msg the user not owner of profile echo message wait request send if user has send request echo message infor user request had been send. but error in first condition because system display user owner profile wrong can me ?? this chunk of code function addasfriend(a,b){ //alert("member id:" + + "request friendship memeber id:" + b); var url = "script_for_profile/request_as_friend.php"; $("#add_friend").text("please wait...").show(); $.post(url,{request:"requestfreindship",mem1:a,mem2:b},function(data){ $("#add_friend").html(data).show().fadeout(12000); }); } <div class="interactcontainers" id="add_friend"> <div align="right"><a href="#" onclick=

php - header() function not working after $_SESSION -

i have big issue , can't solve it. made simple login script , worked on laptop's lamp server. happy , uploaded host, there couldn't log in. solved header() not working after $_session. current test code without login , everything: <?php session_start(); $_session['test'] = 10; header("location: anything.php"); ?> and doesn't redirect. problem? the problem headers have been send. is, session_start sends out several http headers. http://php.net/manual/en/function.session-start.php : this function sends out several http headers depending on configuration. see session_cache_limiter() customize these headers. try turning warnings , errors on (this should give warning) error_reporting(-1); . doing during development practice anyway. if it's not that, must sending output before header. although, looking @ example code gave, that's not case. see this nicely answered question more information problem.

javascript - Raphael js. Fill color along a curve -

i have created circle in can choose 2 points along circumference of of circle. i want fill portion between 2 points. demo if see demo, want fill angle between 2 points. js: (function (raphael) { raphael.colorwheel = function (x, y, size, initcolor, element) { return new colorwheel(x, y, size, initcolor, element); }; var pi = math.pi, doc = document, win = window, colorwheel = function (x, y, size, initcolor, element) { size = size || 200; var w3 = 3 * size / 200, w1 = size / 200, fi = 1.6180339887, segments = 3,//pi * size / 50, size20 = size / 20, size2 = size / 2, padding = 2 * size / 200, t = this; var h = 1, s = 1, b = 1, s = size - (size20 * 4); var r = element ? raphael(element, size, size) : raphael(x, y, size, size), xy = s / 6 + size20 * 2 + padd

javascript - Stop page reload of an ASP.NET button -

net application, have inserted button call javascript function ( onclientclick event) , vb.net function ( onclick event) <asp:button onclientclick="jsfunction() " onclick="vbfunction" text="submit" runat="server" /> the problem when click button, refreshes page , delete content of text boxes. i have tried inserting return false; on onclienclick event, doesn't execute onclick event. how can avoid page reload ? p.s.: @ end of javascript function new window opened window.open(newwindow.aspx) , want first page mantain value inserted user in text boxes. thanks in advance :) you need use return statement @ 2 points. onclientclick="return jsfunction();" function jsfunction() { // return false; } or, you can return false after function call this. onclientclick="jsfunction(); return false;" note if want postback conditionally need return true or false. onclientclick="return js

java - Auto-detect tomcat failed start by bash scripts -

i wrote bash script auto-deploy web-application tomcat container whenever triggered. pretty straight-forward: dump current database back-up shutdown current tomcat process delete web-application folder replace war file new one start tomcat again however, want have fall-back. if there's problem in start-up process, database restored , old war file deployed again. my problem don't know when web-application failed start. 1 of implementation check size of logging file of web application, if after while doesn't increase (which means there's nothing written), system should understand deployment failed , should restore old web-application. however, kind of dirty , i'm not sure happen if logging file rolled right @ time. does tomcat has mechanism support start-failed detection of web-application? have looked @ manager ships tomcat? gives api determine status of web apps deployed inside it.

asp.net - Pagination Not Working On Gridview -

i have gridview control contains label template field. label values filled during rowdatabound. when pagination except template field , paginated. think, when pagination, each time label template field filled on rowdatabound . now not able pagination . please help this code <asp:updatepanel id="updatepanel1" runat="server"> <contenttemplate> <asp:gridview id="gridview1" runat="server" allowpaging="true" backcolor="white" bordercolor="#cccccc" borderstyle="none" borderwidth="1px" cellpadding="3" ondatabound="gridview1_databound" onpageindexchanging="gridview1_pageindexchanging1" onrowdatabound="gridview1_rowdatabound1" pagesize="3"> <columns> <asp:templatefield headertext="first row"> <itemtempla

c# - Redirect on button click in alert-dialog -

i show alert box @ end of code insert operation complete. there easy way show kind of alert box says "inserted successfully" , shows ok-button. click on "ok" should redirect specific page. the code i'm using: scriptmanager.registerclientscriptblock(this, this.gettype(), "alertmessage", "alert('inserted successfully')", true); clientscript.registerstartupscript(typeof(page), "alertmessage", "<script type='text/javascript'>alert('inserted successfully');window.location.replace('http://stackoverflow.com');</script>");

sql - Filter rows that have the same data in different columns -

this question has answer here: sql query: how items 1 col paired not visa versa 3 answers i have data looks this: | b 97 |556 257|803 803|257 257|323 556|97 i'm trying figure out best way filter results such removes duplicate rows. example shows row 257|803 , not 803|257. best way this? select * t x x.a < x.b or not exists ( select * t y y.a = x.b , y.b = x.a ); the truth table strange condition: | b | (a<b) | (not exists) | (a<b or not exists) ---+----+-------+--------------+---------------------- 97 |556 | true | false | true 257|803 | true | false | true 803|257 | false | false | false 257|323 | true | true | true 556|97 | false | false | false result: | b -----+----- 97 | 556 257 | 803 257 | 323 (3 rows)

python - django-tables - cannot concatenate 'str' and 'tuple' -

i'm trying use django-tables2 in project. here model class client(models.model): comp = models.foreignkey(company) user = models.foreignkey(user) def __unicode__(self): return u'%s\'s client data' % self.user class meta: unique_together = (('user', 'comp')) my table class clienttable(tables.table): class meta: model = client fields = ('user') empty_text = _('no client') my view @login_required def client_list(request): obj = {} try: clients = request.user.staff.company.client_set.all() client_table = clienttable(clients) # <-- error here except staff.doesnotexist: raise http404 obj['client_table'] = client_table obj['client_nb'] = clients.count() return render_to_response('company/client_list.html', obj, context_instance=requestcontext(request),) this gives me error: cannot

php - putting the array data into separate variables -

i trying put array data 2 separate variables. not getting it. here code if($option_query->row['type'] == 'date') { $array1[0] = $option_value; foreach ($array1 $key => $value) { echo "$key = $value<br>"; } now getting result : 0 = 2013-05-05 0 = 2013-05-07 i want put 1st date in variable called datestart , 2nd date in dateend . how can achieve this? output var_dump(array1); array (size=1) 0 => string '2013-05-05' (length=10) array (size=2) 0 => string '2013-05-05' (length=10) 1 => string '2013-05-07' (length=10) edited here (adding) if($option_query->row['type'] == 'date' ) { $arr = array( //assuming should map of array array( $option_value ), array( $option_value //$option_value ) ); // var_dump($arr); echo $arr[1][0]; echo $arr[1][1];

Infer type of a string containing a Haskell expression -

i need (quick , dirty) way representation of type of haskell expression given string. i see 3 options: use ghc api -- however, documentation loses me pretty quickly. use other type inference tool -- i've been suggested try haskell-type-exts, fails type trivial expressions. don't know of other such tool. roll own hm inferer -- i'd avoid unless absolutely necessary i don't need complete solution, in sense library/tool can type reasonable basic subset of haskell suffice me. so simplest way achieve this? the hint package offers restricted, perhaps more understandable interface ghc api. perhaps sufficient purposes? if not, can perhaps @ sources better idea of how use ghc api directly. here's example program: import language.haskell.interpreter main :: io () main = r <- runinterpreter $ setimports ["prelude"] typeof "map (+1)" either print putstrln r if run, prints num b => [b] -> [b]

default view resolution in spring -

i spring newbie , have question view resolution. changing webapp downloaded online , uses simple view resolver strategy: <bean id="jspviewresolver" class="org.springframework.web.servlet.view.internalresourceviewresolver"> <property name="viewclass" value="org.springframework.web.servlet.view.jstlview" /> <property name="prefix" value="/web-inf/view/" /> <property name="suffix" value=".jsp" /> </bean> and keep getting 404 errors view resolution , suspecting uses sort of rewriting / filtering mechanism. there log can view in tomcat / spring class can override in order understand file spring trying when resolving incoming request? i understand operation of internalresourceviewresolver strips file name extensions. if request not have extension? instance: @requestmapping("/foo") protected modelmap render

python - Cannot import flask from project directory but works everywhere else -

so have run funny problem when trying use flask, can run ~/ (home) , not ~/projects/projectfolder. i'm using python 2.7.4 installed via homepage, virtualenv , virtualenvwrapper. every time it's same: $ mkvirtualenv project new python executable in project/bin/python installing setuptools............done. installing pip...............done. then install flask: $ pip install flask [...] installed flask werkzeug jinja2 cleaning up... then open python home directory: (project) $ python >>> flask import flask >>> then quit , go project folder: (project) $ cd ~/projects/example (project) $ python >>> flask import flask traceback (most recent call last): file "<stdin>", line 1, in <module> file "flask.py", line 1, in <module> flask import flask importerror: cannot import name flask and i'm bit lost why happening, have ideas? according traceback, have module of own called flask.p

c# - Regular expression for specific number of digits -

i want write regular expression in c# inputs specific number of numbers. like writing regular expression validate 5 digits number "12345" use following regex regex.ismatch method ^[0-9]{5}$ ^ , $ anchors match beginning , end of string (respectively) prevent match found in middle of long string, such 1234567890 or abcd12345efgh . [0-9] indicates character class specifies range of characters 0 9 . range defined unicode code range starts , ends specified characters. {5} followed behind quantifier indicating repeat [0-9] 5 times. note solution of ^\d{5}$ equivalent above solution, when regexoptions.ecmascript specified, otherwise, it equivalent \p{nd} , matches unicode digits - here the list of characters in nd category . should check documentation of language using shorthand character classes matches. i suggest read through documentation . can use other resources, such http://www.regular-expressions.info/ , always check on documentation of

Android Textview ellipsize with multiple rows -

Image
i trying ellips @ end of textview has multiple lines of text. "..." showing @ last space in text , other followed other characters. how make sure "..." @ end. see example image the xml layout file : <?xml version="1.0" encoding="utf-8"?> <relativelayout xmlns:tools="http://schemas.android.com/tools" xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_marginright="5dp" android:orientation="horizontal" > <textview android:id="@+id/nfdatemonth" android:layout_width="64dp" android:layout_height="wrap_content" android:layout_marginleft="10dp" android:layout_marginright="8dp" android:layout_margintop="2dp" android:background="@drawable/topsegment" android:gravity="cente

c++ - Getting a record from SQLite? -

how can specified record table , row? example: here pseudo structure of datebase (sqlite): row1 row2 row3 line1 line1 line1 line2 line2 line2 ... ... ... i want use line record datebase via qt. example how can row2-> line2 string? i tried this: qsqldatabase db = qsqldatabase::adddatabase("qsqlite"); db.setdatabasename("db.db"); //yes name of datebase db.db if (db.open()) { qsqlquery sorual("select question questions",db); sorual.exec();sorual.first(); //these line not affect result "qsqlquery::value: not positioned on valid record". qdebug() << sorual.value(5).tostring(); // here want 5. line of question row in questions table. } else { qdebug() << "error"; } but response debugger "qsqlquery::value: not positioned on valid record" you're doing wrong. here's the example of doing right also recommend read qtsqlquery help - described there. great 1 of strong

php upload file on Edit form, prevent UPDATE if no file -

i have form edit existing values in mysql table. 1 of fields stores filename of image, (another stores folder location of image) file has upload field upload image , replace image name in original image name field. this works fine if choose file, replace existing image. if don't choose replace image, field update empty data. basically trying update sql query if there image chosen , uploaded. i using code: if(!empty($_files['file_slick'])) { $slick = $_files['file_slick']['name']; copy($_files['file_slick']['tmp_name'],'../images/product/'.$folder.'/'.$slick); $sql_slick = "update tbl_product set prod_slick = '".$slick."' prod_id = '".$prodid."'"; mysql_query($sql_slick); } i have tried if(!empty($_post['file_slick'])) neither works. if file chosen , uploaded, moved correct folder , image filename updated field. if image not chosen, empty data updated image fi

php - if statement's not working -

forgive noobness coding teach myself php (lol)! code below works form want create. whenever user hits submit button, provided form filled in correctly, text "e-mail sent successfully" message appears @ top of page. if of mandatory fields incomplete or invalid, error message returned underneath corresponding input field , "e-mail sent successfully" message not appear. works last if statement (antispam). essentially, if enter correct answer (3) antispam box, regardless of other fields being filled in or not, "e-mail sent successfully" message appears (it shouldn't other fields not filled out correctly). "e-mail sent successfully" message should appear if mandatory fields completed correctly. whatever 'if statement' goes @ bottom adhere's same rule (i.e. if name @ bottom of if statements, name need entered correctly e-mail sent message appear). feels though if last if statement passed true, other statements don't work. &l

c# - Retrieve/insert data using SQLiteDataAdapter -

i'm creating small application using windows forms , sqlite. after reading tutorials implemented method data retrieval: public datatable getdatatable(ref sqlitedataadapter adapter, string sql) { datatable dt = new datatable(); // connect database. using (sqliteconnection connection = new sqliteconnection(connectionstring)) // create database adapter using specified query using (adapter = new sqlitedataadapter(sql, connection)) // create command builder generate sql update, insert , delete commands using (sqlitecommandbuilder command = new sqlitecommandbuilder(adapter)) { // populate datatable return, using database adapter adapter.fill(dt); } return dt; } (as getdatatable doesn't take sqlitedataadapter parameter) i have 3 classes, let's call them ui, link , database. ui nothing disp

file io - Python read() function returns empty string -

if type in python: open("file","r").read() sometimes returns exact content of file string, other times returns empty string (even if file not empty). can explain depend on? when reach end of file (eof) , .read method returns '' , there no more data read. >>> f = open('my_file.txt') >>> f.read() # read entire file 'my file has data.' >>> f.read() # you've reached end of file '' >>> f.tell() # give current position @ file 17 >>> f.seek(0) # go starting position >>> f.read() # , read file again 'my file has data.' doc links: read() tell() seek() note: if happens @ first time read file, check file not empty. if it's not try putting file.seek(0) before read .

c# - Parsing results from HTMLAgiltyPack -

i'm trying parse yahoo finance page list of stock symbols , company names. url i'm using is: http://uk.finance.yahoo.com/q/cp?s=%5eftse the code i'm using is; htmlagilitypack.htmldocument page = new htmlweb().load("http://uk.finance.yahoo.com/q/cp?s=%5eftse"); var titles = page.documentnode.selectnodes("//td[@class='yfnc_tabledata1']"); // returns titles on home page of site in array. foreach (var title in titles) { txtlog.appendtext(title.innerhtml + system.environment.newline); } the txtlog.appendtext line me testing. code correctly gets each lines contains class of yfnc_tabledata1 under node of td. when i'm in foreach loop need parse title grab symbol , company name following html; <b><a href="/q?s=glen.l">glen.l</a></b> glencore xstrat <b>343.95</b> <nobr><small>3 may 16:35</small></nobr> <img width="

Ember.js: How are Views connected to Controllers? -

this.get('controller') is coming null. i wondering if can explain how ember views associated ember controllers. thank you. if follow ember's naming conventions, example view infoview hooked automatically infocontroller ember. app.infoview = ember.view.extend({ templatename: 'info' }); app.infocontroller = ember.controller.extend({}); so if later this.get('controller') in view should controller. see fiddle working example: http://jsfiddle.net/intuitivepixel/aywvw/20/

java - Why to use interface while we can make all methods abstract? -

this question has answer here: abstract class vs interface in java 14 answers in abstract class can make methods abstract can work interface, why use interface @ all?? 1 of reason come can implement multiple interface not extend multiple class.. there design or performance related thing involved?? you got answer. using interfaces can enforce multiple types of behaviours using classes not work you. example, can enforce class icomparable inumerable not possible if want classes.

Lagrange interpolation in JAVA -

i have done search around, there isnt code available in java hence have write own , have encountered issue. got code c++ source , trying hard convert workable java program. http://ganeshtiwaridotcomdotnp.blogspot.sg/2009/12/c-c-code-lagranges-interpolation.html public static void main(string[] args) { int n; int i, j; int a; int x[] = null; int f[] = null; int sum = 0; int mult; scanner input = new scanner(system.in); system.out.println("enter number of point: "); n = input.nextint(); system.out.println("enter value x calculation: "); = input.nextint(); (i = 0; < n; i++) { system.out.println("enter values of x , corresponding functional vale: "); x = input.nextint(); f = input.nextint(); } (i = 0; <= n - 1; i++) { mult = 1; (j = 0; j <= n - 1; j++) { if (j != i) { mult *= (a - x[j]) / (x[i] - x[j]);

Some proofs of validity using Z3 SMT 2.0 online -

lemma: forall x : r, x <> 0 -> (x / x) = 1. proof: (declare-const x real) (push) (assert (or (> x 0) (< x 0))) (assert (not (= (/ x x) 1))) (check-sat) and output : unsat qed. lemma: forall x y : r, x <> 0, y <> 0 -> (x / x + y / y) = 2. proof: (declare-const x real) (declare-const y real) (push) (assert (or (> x 0) (< x 0))) (assert (or (> y 0) (< y 0))) (assert (not (= (+ (/ x x) (/ y y)) 2))) (check-sat) and output is: unsat qed. lemma: forall x y : r, x <> 0, y <> 0 -> (x / x + x / y) = ((x + y) / y). proof: (declare-const x real) (declare-const y real) (push) (assert (or (> x 0) (< x 0))) (assert (or (> y 0) (< y 0))) (assert (not (= (+ (/ x x) (/ x y)) (/ (+ x y) y)))) (check-sat) and output is: unsat qed. these lemmas proved using coq + maple at http://coq.inria.fr/v8.2pl1/contribs/maplemode.examples.html and using z3py online at some proofs of validity using z3py o

c# - How to make multiplication operator (*) behave as short-circuit? -

i have lots of computations, specially multiplication, first part 0 , don't want evaluate second operand in case. there @ least 2 short-circuit operators in c#: && , || evaluate second operand if necessary. want achieve similar behavior multiplication operator. in .net can't overload && operator directly, can overload & , false operators, can use extension points change behavior of short-circuit operator. can find more details @ article c# operator overloading: ‘&&’ operator is there means achieve or similar behavior multiplication operator? this pure syntax question, because implementation simple. next method achieves want in terms of functionality: public static double shortcircuitmultiply(double val, func<double> anothervalue) { var epsilon = 0.00000001; return math.abs(val) < epsilon ? 0 : val * anothervalue(); } note: implementation not full: in c# if multiply 0.0 double.nan or double.negativeinfinit

.net - What is &HA0000 constant in this code -

public class form1 protected overrides readonly property createparams() createparams dim cp createparams = mybase.createparams cp.style = &ha0000 return cp end end property end class i did google search , found &ha0000 appcommand_volume_up. code minimize , restore non-border form when click on taskbar icon. please give me explain. thanks. these window styles. list of can found on over msdn . window styles bit flags combined using bitwise or. so, first decompose 000a0000 constituent parts: 00080000 , 00020000 . now, ws_sysmenu 00080000 , ws_minimizebox 00020000 . whoever wrote code using magic constants should given suitably humiliating punishment. code should read: cp.style = ws_sysmenu or ws_minimizebox obviously you'll need define ws_* constants, take time benefit of future readers of code.

android - There is no error shown and when any of the buttons in the activity are pressed, the app forces close? -

Image
why buttons forcing app close, there no errors have been highlighted , new android development, can't find problem. appreciated thanks. this xml <linearlayout android:layout_width="fill_parent" android:layout_height="447dp" android:background="@drawable/background" android:orientation="vertical" android:paddingbottom="@dimen/activity_vertical_margin" android:paddingleft="@dimen/activity_horizontal_margin" android:paddingright="@dimen/activity_horizontal_margin" android:paddingtop="@dimen/activity_vertical_margin" tools:context=".categories" > <button android:id="@+id/author" android:layout_width="match_parent" android:layout_height="45dp" android:layout_alignparentend="true" android:layout_alignparentstart="true" android:background=&quo

How to create "averaged values" table in Excel using primary keys? -

Image
i have huge excel table looks : the names of states primary keys . how can create new table show average prices across states? should contain 51 rows , this: use subtotal feature. select cells contain data , open subtotal dialog box (data menu, subtotals command). for information calculating subtotals , working levels in excel