Thursday, October 31, 2013

removing all options of select box except 1st option

I’m trying to empty select options when:

id “mClick” is selected, id’s “sClick”, “cClick” & “srClick” will be emptied.

id “sClick” is selected, id’s “cClick” & “srClick” will be emptied.

id “cClick” is selected, id “srClick” will be emptied.

<form action="javascript:void(0);" method="POST" id="lForm"><table>    <tr>        <td>            <select name="module" id="mClick">                <option value="">Select Mod</option>                <option value="1">Mod 1</option>                <option value="2">Mod 2</option>                <option value="3">Mod 3</option>            </select>        </td>        <td>            <select name="state" id="sClick">                <option value="">Select State</option>                <option value="1">State 1</option>                <option value="2">State 2</option>            </select>        </td>        <td>            <select name="city" id="cClick">                <option value="">Select City</option>                <option value="1">City 1</option>                <option value="2">City 2</option>            </select>        </td>        <td>            <select name="services" id="srClick">                <option value="">Select Services</option>                <option value="1">Services 1</option>                <option value="2">Services 2</option>            </select>        </td>    </tr></table>

in scenario 3, i used this function, yet it deleted all, except the last select. Any idea’s what i’m missing? Thanks

$('#lForm select[id!="mClick"] select[id!="sClick"] select[id!="cClick"] option[value!=""]').remove().end();

The easiest way to clear the options in the way you’re describing is by using options.length = 1. Also, you can leverage the fact that each drop down clears the ones that logically follow it, so that you only need to declare a single alter handler.

$('#lForm select').on('change', function() {  if (this.selectedIndex > 0) {    var $others = $(this).closest('table').find('select'),    current = $others.index(this); // find current    while (++current < $others.length) {      // for each following drop down      $others.get(current).options.length = 1;    }  }});


I’m not sure how you’re going to repopulate the drop downs though 🙂

shell get the last character of a string

I have wrote the following lines to obtain the last character of a string:

str=$1i=$((${#str}-1))echo ${str:$i:1}

It works for “abcd/”:

$ bash abcd//

It does not work for “abcd*”:

$ bash abcd*

It lists the files in the current folder.

That’s one of the reasons why you need to quote your variables:

echo "${str:$i:1}"

Otherwise, bash expands the variable & in this case does globbing before printing out. It is moreover better to quote the parameter to the script (in case you have a matching filename):

sh 'abcde*'

Also see the order of expansions in the bash reference manual. Variables are expanded before the filename expansion.

Wednesday, October 30, 2013

Update variable when checking checkbox

I have a script with some variables, & I would like to update one of these variables depending on the checkbox being checked or not. The checkbox is unselected by default. What I have now is this:

var checked = $('#accept').attr('checked');if (checked) {    permission = "Y";} else {    permission = "N";};var track = {    version: 123,    id: 123456789,    order: {        sv1: 'Y',        sv2: 'N',        sv3: 'Name',        sv4: permission,        orderid: '123xyz'    }};console.log(track);

I would like to update the content of the variable “permission” based on a click event of a checkbox:

$('#accept').click(function () {      if (checked) {      permission = "Y";      } else {      permission = "N";      };});

Fiddle here.

But how is that possible?

In order to update your object key (sv4) value:

If you already store the permission into your Object track, well, than don’t hesitate to use your object & directly manipulate it & setting a new value to it’s key using =.

var permission = $('#accept').is(':checked') ? "Y" : "N";var track = {    version: 123,    id: 123456789,    order: {        sv1: 'Y',        sv2: 'N',        sv3: 'Name',        sv4: permission,        orderid: '123xyz'    }};console.log( track.order.sv4 );                       // returns: N$('#accept').change(function () {    track.order.sv4 = this.checked ? "Y" : "N";    console.log( track.order.sv4 );                   // returns: Y});

Never forget to define internally your variables by setting var.

The $('#accept').is(':checked') uses the jQuery .is() method that returns a boolean (true/false) which than we set using Ternary Operator ( ? : ) to "Y" / "N"

Tuesday, October 29, 2013

Decompress gzipped http response inside Vim

For debugging purposes I sniffed some requests & responses from my server/client. The compression is enabled so the responses are sent in gzip format. I know that probably I could just disable mod_deflate, but… out of curiosity, is there a way to decompress the gzipped response right in vim?

Here’s an example of a response:

HTTP/1.1 200 OKDate: Tue, 09 Jul 2013 08:00:18 GMTServer: Apache/2.2.14 (Ubuntu)X-Powered-By: PHP/5.3.2-1ubuntu4.19Content-Disposition: inline; filename="combo"Last-Modified: Tue, 09 Jul 2013 08:00:18 GMTExpires: Tue, 09 Jul 2013 08:00:20 GMTPragma: Accept-Ranges: noneContent-Encoding: gzipVary: Accept-EncodingContent-Length: 209Keep-Alive: timeout=15, max=79Connection: Keep-AliveContent-Type: text/css^_<8b>^H^@^@^@^@^@^@^C<94><8f>Í^N<82>0^P<84>ï>E^SÏ%^H)<87>öiJ»@cm<9b>º <84>øîò#ê^Ac<ìafvçË&JZpZF^]8¤A:°d,¥:×Ñ·NSå­<8f>üX^T<85>(}Ô^Py^VzrõÖhòáÒ<9b>ÑØp<92><92>9<9e>'^U÷C²[<9f>^L­É©ï Z9L^@<87>S¶^G­ªj<83><9e>ÞPÆ<98>¸ÈX^[GÑ^GNYè7m¡ÂÕø<8f>Ýdɲ<84>^F-<90>qmãùÄdë7"H­<8d>«y*^Pz¤Ò<9a>Úq5<9d>@üÎZÄë¿g+ûÕö^@^@^@ÿÿ^C^@d«^X^^<94>^A^@^@

I’d like to select the gzipped text section & decompress it on the fly (maybe running a terminal command on it? something like :!sort to sort lines…)

Select the gzipped text section (or provide a range, e.g. :/^$\n\zs/,$). Then you can unzip the part by piping it through the external gunzip command (which naturally must be installed & accessible):

:!gunzip -

When I tested this, the buffer had to be opened in 'binary' mode: :edit ++bin filename. Also, I received gzip: stdin: unexpected end of file after the unpacked contents, yet that probably can be tolerated.

How to apply different sorting methods to different columns in a CSV file in BASH?

I have a CSV file like this:


awk -F',' '{print length($1),$0}' file.csv | sort -k1nr | cut -d' ' -f 2- will sort the file by word length, for all words appearing in the first column:


sort -t, -k+2 -n -r file.csv will sort the file from greatest to least according to the number appearing in the second column:


How can I use these two commands together such that the CSV file is first sorted by word length, according to the words appearing in the first column, then any rows containing words of equal length within the first column are sorted according to the number appearing in the second column from greatest to least. The resulting output would look like this:


How can these two sorting methods be used together?

If you are using then you can use the asort function to perform sort, so no other utility has to be called. You can try something like this:

awk -F, 'function cmp(i1,v1,i2,v2) {split(v1,a1); split(v2,a2)  l1=length(a1[1]); l2=length(a2[1])  return l1 > l2 ? -1 : l1 < l2 ? 1 : a1[2] > a2[2] ? -1 : a1[2] < a2[2]}{a[n++]=$0}END{asort(a,a,"cmp"); for(i in a) print a[i]}' infile



This script reads all the lines first then it sorts the array called a with the function cmp. The only trick I used that a > b returns the usual 1 or 0 for true or false.

A little bit shorter version in :

perl -F, -ane 'push @a,[@F];   END{for $i(sort {length $b->[0]<=>length $a->[0] or $b->[1]<=>$a->[1]} @a) {printf "%s,%d\n", @$i}}' infile

This is not 100% correct as $F[1] contains the \n, yet printf handles it properly.

Sunday, October 27, 2013

Codeigniter - check if user is logged and exists (it's a real user)

I’m setting a session data for users when they log to my website.

So if the user exists in db i set a session data like : $this->session->set_userdata('user_exists','1');

Now every time i want to check if user exists & is logged i do:

if($this->session->userdata('user_exists')){ //do somenthing for logged user}

Now i’m wondering if this means that user is logged & exists in db since he logged & i setted him a session param, is this true? Or i’ll obtain security problems?

NB: i’m using session database


//session encryption is mandatory

  $sess_id = $this->session->userdata('user_id');   if(!empty($sess_id))   {        redirect(site_url().'/reports');   }else{        $this->session->set_userdata(array('msg'=>''));         //load the login page        $this->load->view('login/index');           }    

Tuesday, October 22, 2013

Download only email subject in JavaMail & imaps

I’m trying to download only subject of emails, because it should take less time (downloading ~10 emails with photos take approximately 10 min :/).

Code that I’m now using is:

    try {        Store store = session.getStore("imaps");        store.connect(...);        Folder folder = store.getFolder(folderName);;        message = folder.getMessages();        for (Message m : message) {            System.out.println(m.getSubject());        }        folder.close(false);        store.close();    } catch (MessagingException e) {        ...    } catch (IOException e) {        ...    }

it seems to me that you should look into prefetching the messages with:

FetchProfile fp = new FetchProfile();fp.add(FetchProfile.Item.ENVELOPE);fp.add("Subject");folder.fetch(message, fp);

Monday, October 21, 2013

Tell when Android device is in sleep mode

Is there a way to tell when an Android device is in sleep mode? When testing my app, I press the power button to turn off the screen & need to wait until sleep mode is active. I then send messages to my device using Google Cloud Messaging (GCM) & then play a sound & notification once it arrives. But if I send this message before sleep mode is active, then I am not sure whether it received the message because it was still alive or because my service routine received started by the GCM broadcast receiver.

You can find out when the screen goes off using android.intent.action.SCREEN_OFF intent yet there is no Intent to find out with certainty if the device is in sleep mode as far as I know.

erasing EditText and EditView in Android

This is linked to a previous post:
My layout is like this:




When the user enters an input & upon button click the output text appears.
I have to make sure I make the input & output disappear some 10 seconds after the button click(and after the output text appears).

Now, I cannot add a “TextWatcher” on TextView.
Initially I tried to use Handler on inputText which can have a TextWatcher. But somehow the Handler keeps running all the time in the background & I cannot “cancel” it.

So I switched to using timers. I used a method in the button onCick() method:

onClick(){...    eraseText();....}public void eraseText(){TimerTask task = new TimerTask() {            public void run() {               inputText.setText("");               outputText.setText("");            }        };        Timer timer = new Timer();        timer.schedule(task, 1000,10000);}

And after 10 seconds I would like to call timer.cancel() ( yet don’t know where!!)
As you can see the problem is that I obtain an error complaining that only UI threads can alter views. How can do this ?


I would use Handler class. You can easily post delayed code & cancel it. It will run in correct Thread. Also, you can add TextWatcher or OnFocusChangeListener to detect & cancel text erasing when a user starts editing text again.

Handler handler;@Overrideprotected void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.activity_main);    handler = new Handler();    final TextView textView = (TextView) findViewById(;    final EditText editText = (EditText) findViewById(;    final Runnable eraseText = new Runnable() {        @Override        public void run() {            textView.setText("");            editText.setText("");        }    };    editText.addTextChangedListener(new TextWatcher() {        @Override        public void onTextChanged(CharSequence s, int start, int before, int count) {            handler.removeCallbacks(eraseText);        }        @Override        public void beforeTextChanged(CharSequence s, int start, int count,                int after) {            // TODO Auto-generated method stub        }        @Override        public void afterTextChanged(Editable s) {            // TODO Auto-generated method stub        }    });    editText.setOnFocusChangeListener(new OnFocusChangeListener() {        @Override        public void onFocusChange(View arg0, boolean arg1) {            handler.removeCallbacks(eraseText);        }    });    findViewById( OnClickListener() {        @Override        public void onClick(View arg0) {            textView.setText(editText.getText().toString());            handler.removeCallbacks(eraseText);            handler.postDelayed(eraseText, 1000);        }    });}

Saturday, October 19, 2013

select from multiple tables and sum vs join and sum

I am doing internship in an advertising company, i already implemented a tool to gather all the necessary data form facebook & import them on a database.

Now i am trying to manipulate that data, first by making some test cases & getting some results. The tables grow by 35k rows per day so after a month of using the tool i noticed that the query i use to obtain the sum of certain adcreatives clicks is starting to slow down.

i am asking if the query i use can speed up if i use it with a join & how.

here is the query i have for the sum of clicks per adcreative (with adgroup_id,campaign_id as connect to the other tables):

<!-- language-all: lang-sql -->SELECT t1.adgroup_id, t1.campaign_id, t1.creative_ids, SUM( t2.clicks ) AS clicksFROM adgroups t1, adgroup_stats t2WHERE t1.adgroup_id = t2.adgroup_idGROUP BY t1.creative_idsORDER BY clicks DESC 

currently the query takes 3 secs to complete on a dedicated server, i guess after 6 months it will be at more than 60 secs or so as the tables grow.

edit: here is the explain of the query ( although this is the first time i actually use it & not so sure what it means)

id  select_type table   type    possible_keys   key key_len ref rows    Extra1   SIMPLE  t2  ALL PRIMARY NULL    NULL    NULL    671549  Using temporary; Using filesort1   SIMPLE  t1  ref PRIMARY PRIMARY 8   fbads.t2.adgroup_id 358 Using index

That looks like a full table scan, & with that rapid growth small performance changes won’t make a huge difference on the long run. You need a different approach.

I would calculate aggregates for the previous months (days, etc) with a cron job, & when you need stats then merge that with the fresh results (using the query you already wrote). That why you only have to scan the fresh record, which means the queries is going to be fast.

Alternatively, you can keep up-to-date counters in the adgroups table, & update them on each click. Not sure if mysql is the right tool for this, I can recommend MongoDB, it can do very swift atomic increments on fields, & though it doesn’t donate you as strict guarantees (ACID) as a relational database, in this case it’s not a problem, ad clicks aren’t mission critical data, nobody is going to complain, if you lose < 0.01% percent of click information.

Friday, October 18, 2013

css whole menu color change on hover

i’m really new to html & css, & i thought having a project while working through tutorials would assist me stay motivated while learning a lot.

i’ve been playing around with this menu, & it’s almost there – yet now there seems to be this wall & i just don’t obtain how to obtain over it! i have searched for hours on several sites & am now ready to throw this thing outta the window…

here’s a jsfiddle:

so what i wanted to achieve is that on hover of one submenu the whole menu changes color (instead of the hovered link now). if i hover on “more stuff” for example, all of “menupoint2, stuff, more stuff, even more stuff….” should alter color.

how should i go with that? i’ve tried putting different classes, to no avail – i guess i put them at the wrong place. or is this possible with some kind of box?

i apologize for the messiness of my css (just a beginner messing around..), & i’d really appreciate it if somebody had concrete tips on how to do this 🙂

thank you very much!


#navigation ul{   margin:0px;    padding:0px;   position:relative;   text-align:center;}#navigation ul li{   display:inline;    float:right;    line-height:20px;   list-style:none;    margin-right:3%;   margin-top:5%;   position:relative; }#navigation li a{    display:block;   font-family: "Helvetica", "Arial", sans-serif;   font-size:1em;   color:#04B4AE;    text-decoration:none;}#navigation li a:hover{     color:#08298A;   text-decoration:none;}#navigation li ul{    font-size:0.8em;   background-color:transparent;   display:block;     margin:0px;    padding:0px;   top:0.5em; }#navigation li:hover ul{      color:#04B4AE;}#navigation li li{   vertical-align:middle;   list-style:none;    display:list-item;   margin:auto;   float:none;}#navigation li li a{   color:#04B4AE;    text-decoration:none;}#navigation li li a:hover{    color:#08298A;   text-decoration:none;}

you need to set :hover on li :

li:hover a {color:red}

Adding custom rewrite rules to WordPress

My WordPress site has a portfolio that is at The portfolio sections & items are administered through a custom plugin I created. I want to access the individual items like & have that put “my-cool-photo” into a query string like ?portfolio_item=my-cool-photo so I can read it from my code.

In the plugins activation PHP file I have this code:

function add_rewrite_rules($wp_rewrite) {    $new_rules = array(        'portfolio/(.+)/?$' => 'index.php?&portfolio_item=$1'    );    $wp_rewrite->rules = $new_rules + $wp_rewrite->rules;}add_action('generate_rewrite_rules', 'add_rewrite_rules');function query_vars($public_query_vars) {    $public_query_vars[] = "portfolio_item";    return $public_query_vars;}add_filter('query_vars', 'query_vars');

This adds the rewrite rule to the array OK. The problem is it’s not doing anything. When I go to I obtain the “This is somewhat embarrassing, isn’t it?” WordPress 404 error page. Obviously the redirect isn’t working, so the query string won’t be filled, yet just to make sure I did this:

global $wp_query, $wp_rewrite;if ($wp_rewrite->using_permalinks()) {    $searchKey = $wp_query->query_vars['portfolio_item'];} else {    $searchKey = $_GET['portfolio_item'];}

…and sure enough the query string isn’t getting passed.

Is there something I’m missing?

After you update the WordPress rewrite rules, you need to flush them:

You can select to flush with the $hard parameter true, & then you should be able to see your rewrite rules in the .htaccess file.

Force directly linked file to download

Is there any way to provide a direct link to a file & force the browser to download it using PHP?


We’re dealing with huge files here & Chrome in particular seems to have a problem rendering the image, so all the user sees is a blank screen when visiting the file directly. Even though they can still right-click in the blank screen & download the file it’s confusing.

We used to output the files from PHP yet we ran into memory problems so switched to providing a direct link instead. The files go up to approximately 5GB, they aren’t all images. We have zips, PDFs, PSDs etc.

Currently, the file is requested through a PHP script which accepts the ID of the file & obtain its URL. The PHP script then redirects to the user to full URL of the file.

How can we ensure that downloads are forced & we don’t run into memory issues with the larger files?

Thank you

Just use X-Sendfile yet you need to configure it first … using XSendFilePath

if (file_exists($file)) {    header("X-Sendfile: $file");    header("Content-Type: application/octet-stream");    header(sprintf("Content-Disposition: attachment; filename=\"%s\"", basename($file)));    exit();}

Note* Please ensure $file is properly escaped before you verify & serve the file

XSendFilePath only works on Apache for other servers please see : Caching HTTP responses when they are dynamically created by PHP

Thursday, October 17, 2013

Change CSS to increase font-size inside li

I can’t work out how to increase my font-size in the ‘teaching points’ section of this WP post

I’d like it to be 15px like the rest yet it’s only 12px.

I can’t work out how to reference that section. Help!


ul, ol {  padding-left: 19px;  font-size: 15px;}


Oracle extract values from xmltype

This is the code I am currently using:

SET serveroutput ONCREATE OR REPLACEPROCEDURE test_proc(i_xml varchar2)ISl_name VARCHAR2(20);l_age NUMBER;l_xml xmltype;BEGINl_xml := xmltype(i_xml);FOR x IN(SELECT VALUE(p) col_valFROM TABLE(XMLSEQUENCE(EXTRACT(l_xml, '/ROWSET/ROW'))) p)LOOP     IF x.col_val.existSNode('/ROW/name/text()') > 0 THEN          l_name:= x.col_val.EXTRACT('/ROW/name/text()').getstringVal();     END IF;     IF x.col_val.existSNode('/ROW/age/text()') > 0 THEN          l_age := x.col_val.EXTRACT('/ROW/age/text()').getstringVal();     END IF;end loop;end;/BEGINtest_proc('<ROWSET><ROW><name>aa</name><age>20</age></ROW><ROW><name>bbb</name><age>25</age></ROW></ROWSET>');END;/

The above code uses xml to extract & save the existing node values to particular local variables. It is been used in the case for multiple sets of data & is working fine. I just wanted to know whether can I able to use the same without “for x loop”, because I will only have one data in the i_xml from now onwards & I will only have either
name or age tags .

The following code should be used to save into l_name or l_age without the “loop” method like I used above:

<ROWSET><ROW>    <name>aa</name></ROW></ROWSET>


<ROWSET><ROW>    <age>18</age></ROW></ROWSET>

And I’ve tried using the following:

SELECT     CASE          WHEN VALUE(p).existsNode('/ROW/name/text()') = 1          THEN p.EXTRACT('/ROW/name/text()').getstringVal()          WHEN VALUE(P).existsNode('/ROW/age/text()') = 1          THEN p.EXTRACT('/ROW/age/text()').getstringVal()     ENDINTO l_newFROM TABLE(xmlsequence(EXTRACT(l_xml, '/ROWSET/ROW'))) p;

Any better way is appreciated.. Thanks

If you’re really sure you’ll only have one ROW then you can do:

begin  l_xml := xmltype(i_xml);  if l_xml.existsnode('/ROWSET/ROW/name') > 0 then    l_name := l_xml.extract('/ROWSET/ROW/name/text()').getstringval();  end if;  if l_xml.existsnode('/ROWSET/ROW/age') > 0 then    l_age := l_xml.extract('/ROWSET/ROW/age/text()').getnumberval();  end if;end;

That will work if you have name or age, or both, or neither (where ‘work’ means doesn’t error, at least). If you did have more than one row it would concatenate the results, so with your original data, l_name would be aabbb, & l_age would be 2025. Which might not be what you expect.

Wednesday, October 16, 2013

HTML table with 100% of height, and the rows equally divided in height. How to make it possible?

please go through this fiddle to see what I have tried so far.

<div class="outer">    <div class="inner">        <table style="background-color: red; width:100%; height:100%;">            <tr style="background-color: red; width:100%; min-height:30%;">                <td>Name</td>            </tr>            <tr style="background-color: blue; width:100%; min-height:30%;">                <td>Nirman</td>            </tr>            <tr style="background-color: blue; width:100%; min-height:30%;">                <td>Nirman</td>            </tr>            </table>    </div></div>

I need to display this table occupying full height of the div, & rows of this table should be equal in height to occupy space of full table.
That means, table’s height should be 100% of div’s height.
and each row’s height should be 30% of div’s height.

Any idea of how to achieve this? Also, I would like a solution that should work on most of the browsers, at least, starting from IE 8.

Any assist on this much appreciated.

In styles of the inner div class, alter min-height:100% to height:100% .
That’s all you need!

(This is because min-height can not be inherited)

Here’s the jsfiddle

Which memory is used for variables defined globally?

Suppose we need to work with 8MB stack, & wish to use standard C++ arrays.
Is it true, that

const int MX = 10000;int DP[MX][MX];int main() {  printf("%likB\n", (sizeof(DP))>>10);}

uses heap memory, & for that reason does not segfault (as opposed to when DP is declared in main)? Is it different from allocating the memory via new / malloc in main (besides free issues)?

In modern OS’s, the memory used by an executable is split into (usually) five distinct sections:

  • The Code section (also known as text in Linux/Unix systems for hystericalhistorical reasons). This is where your functions “live”. Often moreover used for constant values, such as char *s = "Hello, World";, the “Hello, World!” part is stored in the CODE section.

  • The “Initialized” data section (also known as “data”) – for global (in C & C++ terms static) data that has been given a value, e.g. int x = 42;

  • Uninitialized data, moreover known as BSS, Block Storage section – for global data that is not given a value, & thus initialized to zero. int y; in a global context, or static int status; would fall into this section.

All of the above sections are defined in the executable. Some executables have more sections than this, yet these are the “typical” ones. An example of an “extra” section is a “read-only data” section, which may be used to store for example string data, rather than storing it in the “code” section.

Once the executable is loaded, two more sections are created by the OS:

  • A stack, which is used to hold local variables inside functions, & is moreover used to “get back” to the calling function. The stack is commonly fairly restricted in size, yet nowhere near as small as it used to be – these days, the stack is regularly in the “a few megabytes” size range. My first machine I used, had a stack of 256 bytes (and that was hard-coded). If you wanted more than that, you had to arrange that by making your own software defined stack. Not very pleasant!

  • A heap. This is used for “dynamic allocation” – for example when creating storage for arrays that vary in size depending on program input. The contents of the heap is not known before the program has started to run. In modern systems, the heap starts out with a small size, & is allowed to grow (but there is a limit, if nothing else when the machine itself runs out of memory – yet often the limit may be lower than that from a system configuration, to avoid one application using up all of the memory in the machine).

In the above example, DP is in the “uninitialized data” section.

SQL and number combination search

I have table with 10 number fields (let’s say F1, F2... F10).

Now I have 4 numbers (N1, N2, N3, N4).

I have to find if those 4 numbers appear anywhere in the above table. For example, if F2=N4 & F1=N2 & Fx=N3 & Fy=N1 (any order, any combination).

I was wondering is there quick way to do it via SQL or is it only way to write looooong combination of selects (I am not sure I will be able even complete that in this life time).

Here is SQLFiddel Demo

Below is the sample Query

select * from Tempwhere 'N1' in (F1,F2,F3,F4,F5,F6,F7,F8,F9,F10)  & 'N2' in (F1,F2,F3,F4,F5,F6,F7,F8,F9,F10)  & 'N3' in (F1,F2,F3,F4,F5,F6,F7,F8,F9,F10)  & 'N4' in (F1,F2,F3,F4,F5,F6,F7,F8,F9,F10)

Tuesday, October 15, 2013

how to add multiple columns to a group by case?

I have the following group by clause on my query which uses a case statement yet I want to add another column to the group by too:

        group by case @dateTypeWHEN 'Daily' then i.overridedateWHEN 'Weekly' then dateadd(day,-1*datepart(weekday,i.overridedate)+1,i.overridedate) WHEN 'Monthly' THEN DATEADD(day, -1*DATEpart(day,i.overridedate)+1, i.overridedate) WHEN 'Quarterly' THEN dateadd(mm,-3,DATEADD(qq, DATEDIFF(qq,0,i.overridedate )+1, 0)) END

how do I add another column to this group by?

group by case @dateTypeWHEN 'Daily' then i.overridedateWHEN 'Weekly' then dateadd(day,-1*datepart(weekday,i.overridedate)+1,i.overridedate) WHEN 'Monthly' THEN DATEADD(day, -1*DATEpart(day,i.overridedate)+1, i.overridedate) WHEN 'Quarterly' THEN dateadd(mm,-3,DATEADD(qq, DATEDIFF(qq,0,i.overridedate )+1, 0)) END--Edited,col1,col2,etc..,coln

Regex to validate alpahanumeric or a set of special characters

I have a requirement to ensure that the string has only alphanumeric or a set of characters like + ( ) , ‘ . – =
I tried like

    String regex = "([a-zA-Z0-9]+)|([\\'|\\()|\\+|\\,|\\-|\\.|\\="]+)";    System.out.println("Regex : " + regex);    Pattern pattern = Pattern.compile(regex);    Matcher matcher = pattern.matcher(str);    if (matcher.matches()) {        System.out.println("Match");    } else {        System.out.println("Not Matching");    }

Bt it is not working, Can anyone assist me please

Thanks in advance

It looks like it will not match a whole string containing a mix of alphanumerics & symbols because of the OR in the middle.

e.g. it wont match abcABC()+, yet will match abcABC & will match ()+



Hope this helps!

Scrolling with jQuery when scrolling is disabled on CSS

I would like to scroll the page using a jQuery animation yet the scrolling is disabled in the CSS & it doesn’t allow the animation to take place:

$('html, body').css({    'overflow': 'hidden',    'height': '100%'});$('html, body').animate({    scrollTop: 939}, 2500);

Here’s the fiddle:

If you set overflow:hidden, the scroll event doesn’t happen. So you can’t trigger it using the animation either. And really, what’s the point of animating a scroll if the user can’t scroll anyway :p

One solution is to wrap the content in another container & animate the container instead, like this:


<div id="content">    <div class="text">text</div>    <div class="text">text</div></div>



And the Javascript:

$('#content').animate({ top: -939 });

Monday, October 14, 2013

filter array using NSPredicate for Names with beginning strings

I want to filter an array of Names (strings) which will be starting with a specific String in first name or last name. For example i have to obtain search results “Joel Mathew” & “Steve Joe” if i gave the string “Jo” to search. Thanks in advance.

Try this.

NSString *nameFilter = @"Steve*";NSPredicate *pred = [NSPredicate predicateWithFormat:@"(name like %@", nameFilter];

Then, filter the array

NSArray *personArray = /* obtain from somewhere */;NSArray *filtered = [personArray filteredArrayUsingPredicate:pred];NSLog(@"%@",filtered);

How to know if a dialog is dismissed in Android?

Sunday, October 13, 2013

Instantiate particular class based on object value

I have classes for each payment mode for e.g. Cash, Cheque, Card. I have to pass object as a parameter based on object value I have to instantiate a relevant class.

How can I achieve this? Suggest me a better design

public interface CollectionInfo {    //Code Goes here}public class Cash implements CollectionInfo {    //Code goes here}public class CollectionFactory {    public void newInstance(Enum<CollectionMode> collectionMode) {    }}public interface Receipts {    public Receipt createReceipt(String Amount, /*(Here i need to pass parameter of object either cash ,Cheque or card),*/Date date);}

You could pass an enumeration (Cash/Cheque/Card) into a factory ?


Payment p = PaymentFactory.newInstance(PaymentMode.Cash);

and within that method you would do:

switch(mode) {   case PaymentMode.Cash:      return new CashPayment();   // ...}

where CashPayment, ChequePayment etc. are subclasses of Payment.

Need a Bitmap image of TabHost Layout

Hi friends am new to android. I created an application form filling with 4 tabs & now I need a screen shot of the layout if its edit text is filled on button click of save. Is it possible to do in android, if not in any format yet i want a copy of the fields with its image

Calendar.setOnClickListener(new OnClickListener() {@Overridepublic void onClick(View v) {    // TODO Auto-generated method stub     loadBitmapFromView((;}});}public static Bitmap loadBitmapFromView(View v) {    Bitmap b = Bitmap.createBitmap( v.getLayoutParams().width,         v.getLayoutParams().height, Bitmap.Config.ARGB_8888);                    Canvas c0 = new Canvas(b);    v.measure(v.getWidth(),v.getHeight());    v.layout(1,1,v.getWidth(),v.getHeight());    v.draw(c0);    return b;}

Hi in the above code its a relative layout where i tried for the layout output as image yet it shows error as width & height > 0

try this it may assist you

 public static Bitmap loadBitmapFromView(View v) {              Bitmap b = Bitmap.createBitmap( v.getWidth(), v.getHeight(), Bitmap.Config.ARGB_8888);                              Canvas c = new Canvas(b);              v.measure(v.getWidth(),v.getHeight());              v.layout(0,0,v.getWidth(),v.getHeight());              v.draw(c);              return b;        }

Saturday, October 12, 2013

Custom view with button in ArrayAdapter

I have defined a custom view (xml) for my ArrayAdapter for a ListView, which adds a Button. I’d like to create an OnClickListener for this Button per row, yet without creating a custom adapter. Is that possible, or does Android force me to create a custom ArrayAdapter for my ListView?

Here’s a snippet of what I’m doing:

glAdapter = new ArrayAdapter<Group>(getActivity(), R.layout.fragment_grouprow,, ListOfGroups);ListView groupListView = (ListView)mainView.findViewById(;groupListView.setAdapter(glAdapter);groupListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {    @Override      public void onItemClick(AdapterView<?> parent, View view, int position, long id) {          // Call function      }});

Now I’d like to add an OnClickListener for the Button in my custom view.

Thanks in advance,


You have to implement you own Adapter & in getView() method set OnClickListener on your button. Here kick off example:

public class CustomAdapter extends ArrayAdapter<Integer> {    private ListView listView;    public CustomAdapter(Context context, int textViewResourceId, Integer[] objects, ListView listView) {        super(context, textViewResourceId, objects);        this.listView = listView;    }    static class ViewHolder {        TextView text;        Button btn;    }    @Override    public View getView(final int position, View convertView, ViewGroup parent) {        Integer color = getItem(position);        View rowView = convertView;        if (rowView == null) {            LayoutInflater inflater = ((Activity) getContext()).getLayoutInflater();            rowView = inflater.inflate(R.layout.list_view_row, parent, false);            ViewHolder h = new ViewHolder();            h.text = (TextView) rowView.findViewById(;            h.btn = rowView.findViewById(;            rowView.setTag(h);        }        ViewHolder h = (ViewHolder) rowView.getTag();        h.text.setText(color);        h.indicator.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                // DO what you want to recieve on btn click there.            }        });        return rowView;    }}

ViewHolder here for optimization. You can read approximately this there.

Transforming Curl into Python using Urllib with Sentiment140 API

I am trying to use Python to request data from the Sentiment140 API.
The API is using a Bulk Classification Service (JSON). Within terminal it is working fine

curl -d "{'data': [{'text': 'I love Titanic.'}, {'text': 'I hate Titanic.'}]}"

leading to the following response:

{"data":[{"text":"I love Titanic.","polarity":4,"meta":{"language":"en"}},{"text":"I hate Titanic.","polarity":0,"meta":{"language":"en"}}]}

I thought I could just use urllib to obtain the same response from my python code. I tried:

import urllibimport urllib2url = ''values = {'data': [{'text': 'I love Titanic.'}, {'text': 'I hate Titanic.'}]}data = urllib.urlencode(values)response = urllib2.urlopen(url, data)page =

The code works yet it does not donate me any results.
Am I missing something?

I think you need to use json here.

Try to do:

data = json.dumps(values) # instead of urllib.urlencode(values)response = urllib2.urlopen(url, data)page =

and on the top

import json 

Friday, October 11, 2013

LinearLayout dynamically display depending on a given number

I want to create a method that can dynamically display LinearLayout in a LinearLayout moreover that is located in a specified area in my Android application, the number of this linear layout changes depending on a given number.

Also, in each LinearLayout I want to display a Button & below it a TextView.

Here is the method I have already created:

public void putLinearLayout(double number){       int mButtonHeight = 100;        int mButtonWidth = 80;         LinearLayout Linear = (LinearLayout)findViewById(;        for(int i=1;i<=number;i++)        {            LinearLayout L = new LinearLayout(this);            Button b= new Button(this);            TextView tv = new TextView(this);            L.setOrientation(LinearLayout.HORIZONTAL);            b.setWidth(mButtonWidth);            b.setHeight(mButtonHeight);            L.addView(b);            L.addView(tv);            Linear.addView(L);        }    }

you just need to set the layoutparams

public void putLinearLayout(double number){        LinearLayout Linear = (LinearLayout)findViewById(;               int mButtonHeight = 100;                int mButtonWidth = 80;                for(int i=1;i<=number;i++)                {                    LinearLayout L = new LinearLayout(this);                    L.setBackgroundColor(Color.WHITE);                    LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT); //<--this line , is what you were missing                    L.setLayoutParams(params); //<-- & then this                    Button b= new Button(this);                    b.setText(i+"");                    TextView tv = new TextView(this);                    tv.setText("i am textview number: "+i);                    L.setOrientation(LinearLayout.HORIZONTAL);                    b.setWidth(mButtonWidth);                    b.setHeight(mButtonHeight);                    L.addView(b);                    L.addView(tv);                    Linear .addView(L);                }


Thursday, October 10, 2013

To display the searched item in the same page

The following code present in srches_controller

def index   @srches = Srch.all   respond_to do |format|     format.html # index.html.erb     format.json { render :json => @srches }end. ..def search    @srch=Srch.find(:all,                :conditions => ["name LIKE ? OR address LIKE ?", "%#{params[:search]}%", "%#{params[:search]}%"])end

The searched item is now displayed in the new search page.
But I need to display the searched item in the same index page.
What is the solution?

You can pass parameter search to index page & search your results with:

def index  @srches = Srch.scoped  if params[:search].present?    @srches = @srches.where(['name LIKE ? OR address LIKE ?', "%#{params[:search]}%", "%#{params[:search]}%"])  end  respond_to do |format|    format.html    format.json { render :json => @srches }  endend

or you can set scope in your model:

scope :search, lambda{|query|  if query.present?    where(['name LIKE ? OR address LIKE ?', "%#{query}%", "%#{query}%"])  end}

and call it in controller with:

@srches =[:search])

Display scrollview button click event

I have images under scrollview. I have a button to click event. When i click the button i need to display scrollview. But when i install app the scrollview is automatically displaying bottom of the page.


<RelativeLayout xmlns:android=""    xmlns:tools=""    android:layout_width="match_parent"    android:layout_height="match_parent"    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=".Scroll" >    <HorizontalScrollView        android:id="@+id/scrl"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:layout_marginTop="250dp" >        <LinearLayout            android:layout_width="wrap_content"            android:layout_height="wrap_content"            android:orientation="horizontal" >            <Button                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:background="@drawable/access"                />            <Button                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:background="@drawable/access1"                 />            <Button                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:background="@drawable/access2"                />            <Button                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:background="@drawable/access3"                 />            <Button                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:background="@drawable/access4"                />            <Button                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:background="@drawable/access5"                 />            <Button                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:background="@drawable/access6"                 />            <Button                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:background="@drawable/access7"                 />            <Button                android:layout_width="wrap_content"                android:layout_height="wrap_content"                android:background="@drawable/access8"                 />        </LinearLayout>    </HorizontalScrollView>    <Button         android:id="@+id/btn"        android:layout_width="fill_parent"        android:layout_height="wrap_content"/>        <TextView        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="@string/hello_world" /></RelativeLayout>

Button click:

Button btn=(Button)findViewById(;btn.setOnClickListener(new OnClickListener(){            @Override            public void onClick(View v) {                // TODO Auto-generated method stub    HorizontalScorllView    srl=(HorizontalScrollView)findViewById(;                  }        });

By default set visiblity of android:id=”@+id/scrl” as invisible in xml.
After click on button
HorizontalScorllView srl=(HorizontalScrollView)findViewById(;
set visiblity of srl as visble.

Wednesday, October 9, 2013

calling javascript objective-c without visible uiwebview

I want to call javascript functions from my objective-c. This for iphone. I understand how the call to the javascript function is done with this line

NSString *returnValue = [webView stringByEvaluatingJavascriptFromString:method];

But I dont actually want a webview to be seen or used as part of the UI. So can I just create an instance of it right before calling the method above in some way.

I have tried:

UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectZero];[webView loadRequest:[NSUrLRequest requestWithUrl:url]];

but nothing seems to happen. So is there a method similar to the above that I am meant to use.

add the webview in your controller’s view in order to run the javascript. it won’t be visible since it has zero height & width.

Linq to object Right outer join

I have written following linq query yet I am not getting expected result.My Expected result is all the matching record bettween lst & list & all the non matching record from list
for example.

I want following result


public class Com : IEqualityComparer<DuplicateData>    {        public bool Equals(DuplicateData x, DuplicateData y)        {            return x.address.Equals(y.address);        }        public int GetHashCode(DuplicateData obj)        {            return obj.address.GetHashCode();        }    }static void Run (){    List<string> lst = new List<string>();    lst.Add("a");    lst.Add("b");    lst.Add("c");    lst.Add("p");    List<DuplicateData> list = new List<DuplicateData>()    {        new DuplicateData{address="a"},        new DuplicateData{address="a"},        new DuplicateData{address="a"},        new DuplicateData{address="b"},        new DuplicateData{address="b"},        new DuplicateData{address="c"},        new DuplicateData{address="d"},        new DuplicateData{address="e"},        new DuplicateData{address="f"},    };    var dup = list.Distinct(new Com());    var RightJoin = from x in dup                    join y in lst                    on x.address equals y                    into right                    from z in right                    select new                    {                        UniqueAddress = z,                    };}

Try it like this:

var RightJoin = from x in dup                join y in lst                on x.address equals y                into right                from z in right.DefaultIfEmpty(x.address)                select new                {                    UniqueAddress = z,                };

result is (a,b,c,d,e,f)

Working sample:


To make a left/right join in linq you have to use DefaultIfEmpty method, that will yield (default) result when there is no match (the joined result is empty). However, default value for string is null so you have to provide default value from the “left side” collection to see it in the result set.

Alternative approach

This is probably more convenient approach. Instead of selecting from z & providing the default value, you will select from x.address – the left side of the join.

var RightJoin = from x in dup                join y in lst                on x.address equals y                into right                from z in right.DefaultIfEmpty()                select new                {                    UniqueAddress = x.address,                };

Tuesday, October 8, 2013

Implement getDirection in google map V2

I have a marker on a predefined location .What I want is to obtain the direction to that marker from my current location which I obtain from the GPS.
I tried many SO links yet they didn’t assist as there were only few links for Google maps v2. It would be wonderful if I obtain some updated tutorial or code snippets of the same .

Check this example i think it suits your requirement link

toString method for SonataAdminBundle Listing in Symfony2

In Symfony 2.3 i am using SonataAdminBundle ( master ) & i am trying to obtain ManyToMany working in Listing. The Problem is that SonataAdminBundle is asking for a toString() method. Implementing this method to the related Entity solves the problem.

My Question: Do i have to implement the toString method or is there a Option to tell SonataAdminBundle a property for using instead of calling the toString method?

Thank you

As far as I know, is mandatory.

But you can return another property value if you want. Also, you can prevent yourself from trying to display a property when the object has no data (for example, when you are “Adding a new object”)

There is a simple way:

public function __toString(){    return ($this->getName()) ? : '';}

Monday, October 7, 2013

Setting base path dynamically through jquery/javascript?

Is there a way to dynamically alter the content inside the tag?, throught jquery or javascript?

I am not using php or any server side script. I am using backbone.js & hence i have a .html file.

I have come to a situation where i would need to type in base path.


<base href="" />

I have searched around & i havent received anywhere.

Probably this is not possible at all, yet just wanted to check it here in stackoverflow.

Using jQuery. Here is jsFiddle I’ve made


<base href="" /><div id="valueBefore"></div><div id="valueAfter"></div>


$(document).ready(function(){    $('#valueBefore').text( $('base').attr('href') );    $('base').attr('href','kjhsgdkjahgdjkahgdf');    $('#valueAfter').text( $('base').attr('href') );});

Will produce:

Sunday, October 6, 2013

Find the value for the address in GDB (Cent OS 6)

For analysis purpose we want to know the which data(message) is stored in the address. Is there any option to find the message in GDB.

In the other words we know the address (0x80488b4) of memory yet we want moreover know the message stored in that address through GDB.

Sample code :

(gdb) print option_value$1 = (const void *) 0x80488b4

If you know the type typemsg_tof the message, you could dereference it, e.g. print *(typemsg_t*) option_value

You might moreover be interested by the GDB watchpoint ability.

It is worth taking some time to read GDB documentation !

How to match an apostrophe (') unless it is escaped (\')?

Is it possible to construct a regular expression for this? If so, I’d appreciate if someone shows how.

Use this regular expression:


It means match all apostrophe chars not preceeded by a backslash (the backslash is escaped itself because it is a special char for regexps)

PHP 5.3 accessing array key from object getter

I have a Form object $form. One of its variables is a Field object which represents all fields & is an array (e.g $this->field['fieldname']). The getter is $form->fields().

To access a specific field method (to make it required or not for example) I use $form->fields()['fieldname'] which works on localhost with wamp yet on the server throws this error:

Parse error: syntax error, unexpected '[' in (...)

I have PHP 5.3 on the server & because I reinstalled wamp & forgot to alter it back to 5.3, wamp runs PHP 5.4. So I guess this is the reason for the error.

How can I access an object method, which returns an array, by the array key with PHP 5.3?

Array dereferencing as described in the question is a feature that was only added in PHP 5.4. PHP 5.3 cannot do this.

echo $form->fields()['fieldname']

So this code will work in PHP 5.4 & higher.

In order to make this work in PHP 5.3, you need to do one of the following:

  1. Use a temporary variable:

    $temp = $form->fields()echo $temp['fieldname'];
  2. Output the fields array as an object property rather than from a method:
    ie this….

    echo $form->fields['fieldname']

    …is perfectly valid.

  3. Or, of course, you could upgrade your server to PHP 5.4. Bear in mind that 5.3 will be declared end-of-life relatively soon, now that 5.5 has been released, so you’ll be wanting to upgrade sooner or after anyway; maybe this is your cue to do? (and don’t worry approximately it; the upgrade path from 5.3 to 5.4 is pretty easy; there’s nothing really that will break, except things that were deprecated anyway)

self join on one table

I have a table STARTSTOP

ACTION  DATA                    ID_PPSTARTSTOPPOZ0   2013-03-18 08:38:00 104511   2013-03-18 09:00:00 104530   2013-03-18 09:50:00 104661   2013-03-18 10:38:00 104670   2013-03-19 11:54:00 104991   2013-03-19 12:32:00 10505

Action 0 -> START ACTION
Action 1 -> STOP ACTION
DATA is a timestamp of action

I would like to run a select statement that would return records something like:

ACTION_1   ACTION_2    DURATION10451        10453       2210466        10466       48             ...

OR summary for all actions duration in one row.

Is it feasible with a single database query? (without creating additional tables)

select A1.ID_PPSTARTSTOPPOZ as Action_0,       A2.Action_1,       datediff (minute, A1.DATA ,A2.DATA)from STARTSTOP A1JOIN (  select ID_PPSTARTSTOPPOZ as Action_1,         DATA,         (select max(ID_PPSTARTSTOPPOZ)           FROM STARTSTOP           where ID_PPSTARTSTOPPOZ<T.ID_PPSTARTSTOPPOZ                AND                ACTION=0) AS PREV_ACTION  from STARTSTOP T  where ACTION=1 ) A2 on A1.ID_PPSTARTSTOPPOZ=A2.PREV_ACTIONwhere ACTION = 0order by A1.ID_PPSTARTSTOPPOZ 

DATEDIFF function

SQLFiddle Example for MSSQL yet it has to work under Firebird too

Why below code's output is “not found” instead of “found”?

below code gives “Not found” output. But I expect it to donate “found”. Where is my mistake?

#include <stdio.h>void compare(char *x, char *face);int i;int main(void){char array[5]="Two";char *numbers[4]={"One", "Two", "Three", "Four"};compare(array, *numbers);}void compare(char *x, char *y){for (i = 0; i < 4; i++){    if (*x==y[i])    {        printf("\n found");        return;    }}printf("\n not found\n");}

In *x==y[i] you are comparing the value of two chars instead of the data pointed to by two pointers. Use the strcmp function instead. It returns 0 if the two strings pointed to by the given two pointers are equal. So alter it to strcmp(x, y[i]) == 0

Also you should alter the char *y parameter to char **y or char *y[] because y is an array of pointers to strings, not just one pointer.

Finally, compare(array, *numbers); should be called as compare(array, numbers); because you want to pass a pointer to the array of strings, not just a pointer to one string (numbers is of type char*[4] yet it will decay to type char** when passed as an argument).

Saturday, October 5, 2013

CSS3 collapse works with latency

I want to make an expandable block using css transitions.

.box {    width: 300px;    max-height: 30px;    overflow: hidden;    background: #aaa;    -webkit-transition: max-height 400ms ease-in-out;    -moz-transition: max-height 400ms ease-in-out;    -ms-transition: max-height 400ms ease-in-out;    -o-transition: max-height 400ms ease-in-out;    transition: max-height 400ms ease-in-out;} {    max-height: 999px;}

Here’s working example:

When I expand the block, it slides down well, yet when I want to collapse it, it occurs with some latency.
This is noticed in lastest versions Chrome, Firefox, Opera & IE.
Why does it happen & May I avoid this without using javascript animations?

P.S. If use height animation instead of max-height, collapse works well, yet I need collapse & expand block with unknown expanded height.

It looks that it happens because the collapsing animation starts to alter the max-height from the very large value & it takes to it some time to cross the actual height of the element, & the visible alter of the height starts only after that moment. The only workaround I see is to use separate animations for expansion & collapsing — a bit longer one with easing-in for the first & a bit shorter one that starts very sharply & eases out just before ending for the latter, like the following:

.box {    width: 300px;    max-height: 30px;    overflow: hidden;    background: #aaa;    transition: max-height 300ms cubic-bezier(0, .6, .6, 1); /* for collapsing */} {    max-height: 999px;    transition: max-height 400ms ease-in; /* for expansion */}


Splitting a string while keeping the delimiters except escaped ones (regex)

If I have a String which is delimited by a character, let’s say this:


and I want to keep the delimiters, I can use look-behind & look-ahead to keep the delimiters themselves, like:


which results in

  • a
  • -
  • b
  • -
  • c

Now, if one of the delimiters is escaped, like this:


And I want to honor the escape, I figured out to use a regex like this:

((?<=-(?!(?<=\\-))) | (?=-(?!(?<=\\-))))  



Now, this works & results in:

  • a
  • -
  • b\-c

(The backslash I’d after remove with string.replace("\\", "");, I haven’t found a way to include that in the regex)

My Problem is one of understanding.
The way I understood it, the regex would be, in words,

split ((if '-' is before (unless ('\-' is before))) or (if '-' is after (unless ('\-' is before))))

Why shouldn’t the last part be “unless \ is before”? If ‘-‘ is after, that means we’re between ‘\’ & ‘-‘, so only \ should be before, not \\-, yet it doesn’t work if I alter the regex to reflect that like this:

((?<=-(?!(?<=\\-))) | (?=-(?!(?<=\\))))  

Result: a, -, b\, -c

What is the reason for this? Where is my error in reasoning?

Why shouldn’t the last part be “unless \ is before”?


(?=-(?!(?<=\\-))))     ^here

cursor is after - so "unless \ is before" will always be false since we always have - before current position.

Maybe easier regex would be


  • (?<=(?<!\\\\)-) will check if we are after - that has no \ before.
  • (?=(?<!\\\\)-)will check if we are before - that has no \ before.

Friday, October 4, 2013

rails input selected values from params to select_tag (multiple => true)

I want to keep the select_tag(:multiple => true) options to be selected which were selected by user once search is performed

<%= select_tag 'values[]', method_for_options_for_select, :class => 'some-class', :multiple => true, :size => 6 %>

Suppose a user select 4 values from the select tag then for values should be selected,
How can we pass this 4 values to the select_tag?

I tried using :selected => params['values[]'] yet this doesnt works for multiple true

Any assist will be appreciated

Ref this & options_for_select

Something like following

<%= select_tag 'values[]', options_for_select( {|s| [s.store_name, s.store_id]}, {|j| j.store_id}),:class => 'some-class', :multiple => true, :size => 6 %>

use parentheses in c# calculator

Hello I just write a simple calculator in C# & I want to improve my program to handle parentheses.

Here is my button to add 1(digit):

 private void btnOne_Click(object sender, EventArgs e)        {            txtResult.Text += '1';        }

This is a method for my Plus button:

private void btnPlus_Click(object sender, EventArgs e)        {            lblChar.Text = "+";            num1 = float.Parse(txtResult.Text);            txtResult.Text = "";        }

And this is for to calculate final result:

private void btnEqual_Click(object sender, EventArgs e)        {    num2 = float.Parse(txtResult.Text);                if (lblChar.Text == "+")                {                    num3 = num1 + num2;                    txtResult.Text = Convert.ToString(num3);                }}

Anyone can assist me to write parentheses for my program?

You can use NCalc – Mathematical Expressions Evaluator for .NET

 Expression e = new Expression("2 + (3 + 5)*6"); var result = e.Evaluate();

Thursday, October 3, 2013

C# Get generic non-array type from generic array type

Given the following function;

void SomeFunction<T>(...){    SomeOtherFunction<T>();}

This works fine, yet sometimes the function fails before T passed is an array type, yet it mustn’t be an array type. These functions have to do with JSON deserialization of a dictionary, yet for some reason it doesn’t accept the T array argument when the dictionary has only one entry.

In short, I want to do this

void SomeFunction<T>(...){    try {    SomeOtherFunction<T>();    } catch ( Exception e ){        SomeOtherFunction<T arrayless>();    }}

I’ve tried a ton of stuff, & I realize the real problem is somewhere else, yet I need to temporary fix this so I can work on a real solution in the deserializer. I tried reflection too using the following method;

MethodInfo method = typeof(JToken).GetMethod("ToObject", System.Type.EmptyTypes);MethodInfo generic = method.MakeGenericMethod(typeof(T).GetElementType().GetGenericTypeDefinition());object result = generic.Invoke(valueToken, null);

But that doesn’t quite work either.

Thank you!

I am not really sure what you are trying to achieve here, yet to obtain the type of the elements in an array, you have to use Type.GetElementType():

void SomeFunction<T>(){    var type = typeof(T);    if(type.IsArray)    {        var elementType = type.GetElementType();        var method = typeof(Foo).GetMethod("SomeOtherFunction")                                .MakeGenericMethod(elementType);        // invoke method    }    else        foo.SomeOtherFunction<T>(...);}

Horizontal image align CSS

I’m having some trouble aligning a main image. It should be center-aligned horizontally, yet keeps going all over the place. The page can be found here

<img src="images/background-space.png" class="displayed" border="0" />IMG.displayed{    display: inline-block;    margin-left: auto;    margin-right: auto;}

That’s basically the CSS I have applied to the image, all the source code is on main index.html (no separate style sheet).


Add this to your CSS style.

img.displayed {    display: table-caption;    margin: 0 auto;}


From the inputs of IlyaStreltsyn, I agree with the point of clearing the right with display:block for the image to be centered.

For Instance,

img.displayed {    display: block;    margin: 0 auto;    clear: right;}

Python regexp multiple expressions with grouping

I’m trying to match the output given by a Modem when asked approximately the network info, it looks like this:

Network survey started...For BCCH-Carrier:arfcn: 15,bsic: 4,dBm: -68For non BCCH-Carrier:arfcn: 10,dBm: -72arfcn: 6,dBm: -78arfcn: 11,dBm: -81arfcn: 14,dBm: -83arfcn: 16,dBm: -83

So I’ve two types of expressions to match, the BCCH & non BCCH. the following code is almost working:

match = re.findall('(?:arfcn: (\d*),dBm: (-\d*))|(?:arfcn: (\d*),bsic: (\d*),dBm: (-\d*))', data)

But it seems that BOTH expressions are being matched, & not found fields left blank:

>>> match[('', '', '15', '4', '-68'), ('10', '-72', '', '', ''), ('6', '-78', '', '', ''), ('11', '-81', '', '', ''), ('14', '-83', '', '', ''), ('16', '-83', '', '', '')]

May anyone help? Why such behaviour? I’ve tried changing the order of the expressions, with no luck.


That is how capturing groups work. Since you have five of them, there will always be five parts returned.

Based on your data, I think you could simplify your regex by making the bsic part optional. That way each row would return three parts, the middle one being empty for non BCCH-Carriers.

match = re.findall('arfcn: (\d*)(?:,bsic: (\d*))?,dBm: (-\d*)', data)

Wednesday, October 2, 2013

Add radio input dynamically to jQuery Mobile fieldset controlgroup

I’ve seen variations on this question yet not my specific case on SO, so here goes.

I’m having trouble adding a new radio input dynamically to an existing control group using jQuery Mobile. It will add, yet the style is not correct & it doesn’t appear to interact with the other inputs correctly.

Here’s my fiddle:

Can anyone see what I’m doing wrong? Or is is a case of regenerating the whole fieldset /controlgroup again? 🙁

Thanks! Code below too…

        <div id="testPage" data-role="page">        <div data-role="content">    <fieldset data-role="controlgroup">        <legend>Radio buttons, vertical controlgroup:</legend>            <input type="radio" name="radio-choice-1" id="radio-choice-1" value="choice-1" checked="checked">            <label for="radio-choice-1">Cat</label>            <input type="radio" name="radio-choice-1" id="radio-choice-2" value="choice-2">            <label for="radio-choice-2">Dog</label>            <input type="radio" name="radio-choice-1" id="radio-choice-3" value="choice-3">            <label for="radio-choice-3">Hamster</label>            <input type="radio" name="radio-choice-1" id="radio-choice-4" value="choice-4">            <label for="radio-choice-4">Lizard</label>    </fieldset>        </div>    </div>$('<input type="radio" name="radio-choice-5" id="radio-choice-5"><label for="radio-choice-5">Horse</label>')    .appendTo("fieldset");$("fieldset").trigger('create');

You need to use name="radio-choice-1" as you have used in above. This solves you behavior problem

Behavior problem solved with below change
Your modified code for dynamically adding radio.

 $('<input type="radio" name="radio-choice-1" id="radio-choice-5"><label for="radio-choice-5">Horse</label>').appendTo("fieldset");

Style problem solved with below change
Just recreate div instead of fieldset


Check Fiddle Demo

CSS alternating rowbased floating

Im not sure how exactly to call my problem, hence the cryptic title.

The situation I have is the following:

<div class="widget full">foobar</div><div class="widget half">left</div><div class="widget half">right</div><div class="widget half">left</div><div class="widget full">foobar</div><div class="widget full">foobar</div><div class="widget half">left</div><div class="widget half">right</div>

I let these widgets float left & right, based on the odd or even css:

#main > div.widget.full { display: block; width: 100%; }#main > div.widget.half { display: block; width: 49%; }#main > div.widget.half:nth-child(2n+1) { float: right; }

Works like a charm on the first 2 ‘half’ ones, yet the 2 after that obtain screwed over by the 3rd ‘half’. The last 2 are in ‘reversed order’. What I need is some sort of reset or other solution that will put the divs in the right place, regardless of what is between them.

If there is no CSS answer for this I can fix it generating them in PHP, yet CSS has my preference since its a style-issue.

Thanks in advance

Unfortunately, you will not able to achieve this via css only.

This selector:

#main > div.widget.half:nth-child(2n+1)

Will not look for 2n+1 occurrences of .widget.half children, yet instead will target only .widget.half elements that are children number 1, 3, 5, etc.

Tuesday, October 1, 2013

Hibernate: How to get full sql query for method?

I’m saving new object via Hibernate. What I would like to obtain is full sql query which was use. In debug Im getting query with “?” .

 ... values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)

How to obtain same query with values.


This is from my log4j configuration (Hibernate 3.6.8). = DEBUG, C = TRACE, C

log4j.appender.C = org.apache.log4j.ConsoleAppender

log4j.appender.C.layout = org.apache.log4j.PatternLayout

log4j.appender.C.layout.ConversionPattern = [%d{dd MMM yyyy HH:mm:ss,SSS}] %-5p %C.%M : %m%n

SQL has the logger for the SQL statement (you need to set it to DEBUG level) & BasicBinder the logger for the actual parameters (TRACE level)

change date format Y-m-d H:i:s from json feed with jquery

I have received a problem with converting the date format from Y-m-d H:i:s to dd-MM-YYYY by using JQUERY.

My json looks like:

{  "status": "ok",  "posts": [    {       "id": "21",      "title": "Title",      "date": "2013-06-26 06:46:29"    }  ]}

And ajax request:

       $.ajax({         url: ,        async: false,        callback: 'callback',        crossDomain: true,        contentType: 'application/json; charset=utf-8',        dataType: 'jsonp',        timeout: 2000,        success: function (data, status) {           if (data !== undefined && data.posts !== undefined) {            $('#news').append('<a class="item" href="single.html?type=news&id=' + + '">' + item.title  + + '</a>');           }            } });

Can anyone kindly assist me by using jsfiddle? I am new to jquery….

Utilize the split function in pure JavaScript, & toss the varaibles around.

var date = "2013-06-26 06:46:29";var dateSplit = date.split(" ");var dateSplit2 = dateSplit[0].split("-");var formattedDate = dateSplit2.reverse().join('-');   // 26-06-2013

This might seems a yet ugly, & it is. But it suits, as long as you don’t actually need to format the date in other ways (like timezone & such). Then you’d have to look into the Date() object.

EDIT: I want to encourage people to use as much pure JavaScript as possible, due to it’s speed. Often jQuery libraries & functions is filled with overhead, which causes your site to not only load slow, yet moreover process slow. There are no short-cuts to the perfect code, you’ll have to spend some time with it, & learn some tips & tricks. Good luck 🙂

Regex before a colon

I have this string:

[Provider].[Provider]=[ProviderArea].&[X12: WALES]

I want to grab just the X12 part.

I tried:

(?<=: )\w+(?=\]$)

However, this only gets WALES.

I moreover tried:


But this gets the whole string before & including the colon.

Where am I going wrong?

If you wan’t to find word (\\w+) between &[ & : then try maybe


Sum a multidimensional list in python

How can i compute this :

[["toto", 3], ["titi", 10], ["toto", 2]]

to obtain this:

[["toto", 5], ["titi", 10]]


You can use collections.defaultdict

>>> from collections import defaultdict>>> d = defaultdict(list)>>> for i, j in L:...     d[i].append(j)... >>> [[i, sum(j)] for i, j in d.items()][['titi', 10], ['toto', 5]]

Thanks @raymonad for the alternate, cleaner, solution:

>>> d = defaultdict(int)>>> L = [["toto", 3], ["titi", 10], ["toto", 2]]>>> for i, j in L:...     d[i] += j... >>> d.items()[('titi', 10), ('toto', 5)]