Monday, February 21, 2011

Get records from a specific month using SQLite

How would I write a SQLite query to select all records from a specific month? My dates are stored as Unix timestamps.

PHP code is allowed in your solution if it's required. SQLite2-compatible queries only, please. :)

From stackoverflow
  • If you want an efficient query then you should use BETWEEN:

    SELECT *
    FROM Table1
    WHERE date BETWEEN $start AND $end
    

    Where start and end are the unix timestamps for the start of the month and the end of the month. These can be calculated in PHP using mktime and sent as parameters.

    soren121 : Well, it's not working, but I'll have to blame my script here, because the query (and my time-finding code) seems to be correct.
    soren121 : And it was my script. Fixed the bug in MY code and it worked fine. Thanks!
  • Use:

    SELECT *
      FROM TABLE 
     WHERE DATETIME(your_unix_timestamp_col, 'unixepoch') BETWEEN YYYY-MM-DD 
                                                              AND YYYY-MM-DD
    

    Replace the YYYY-MM-DD with the dates you desire. See the reference page for other supported formats.

    Reference:

  • Without calculating last day in month

    SELECT * 
      FROM table 
     WHERE strftime('%Y-%m',date(unix_timestamp,'unixepoch','localtime')) = '2010-03'
    

How to edit the first line in a text file in c++?

I have a text file looks like this :

100 50 20 90
4.07498 0.074984
37.1704 28.1704
20.3999 14.3999
48.627 35.627 ....

I need to edit this file so that everything is kept the same except the first line, 3rd item. The ouput should look like this:

100 50 19 90
4.07498 0.074984
37.1704 28.1704
20.3999 14.3999
48.627 35.627
....

How can I do it in c++ ? Can anybody help me?

Thanks, Hoang

From stackoverflow
  • #include <stdio.h>
    
    int main()
    {
          FILE *pFile;
          pFile = fopen("example.txt", "r+");
          fseek(pFile, 7, SEEK_SET);
          fputs("19", pFile);
          fclose(pFile);
          return 0;
    }
    

    Edit: The above was of course mostly a joke. The real way to do it is to read the first line, split it into parts, change the required number, write it out, then follow with all the rest of the lines. If we know that the file contains four integers (floats?) on the first line, something like this might suffice:

    #include <fstream>
    #include <iostream>
    using namespace std;
    
    int main ()
    {
        ifstream in("in.txt");
        ofstream out("out.txt");
        float v1, v2, v3, v4;
        in >> v1 >> v2 >> v3 >> v4;
        v3 = 19.1234; // <- Do whatever you need to here.
        out << v1 << " " << v2 << " " << v3 << " " << v4;
        out << in.rdbuf();
        out.close();
        in.close();
        return 0;
    }
    
    tsubasa : Thank you for your solution. But I'm looking for a more "dynamic" way, which means I can change 20 to any number without overwriting the last number. Ex: 20, 19.9999, 19.9998, 17.36...
    Billy ONeal : @tsubasa: Then you should specify that in your question.
    calmh : Added a solution that actually fulfills the extra specifications, and can handle a new number that is longer than the previous one. :)
    tsubasa : This solution is brilliant, exactly what i'm looking for. Thank you very much calmh.
  • As long the result is the same length as the original (or shorter, and you don't mind adding spaces to cover the difference) it's pretty easy: seek to where you want to do the modification, write the new data, and you're done:

    #include <fstream>
    #include <ios>
    
    int main() { 
        std::fstream file("yourfile.txt", std::ios::in | std::ios::out);
        file.seekp(7);
        file << "19";
        return 0;
    }
    

    If the data you want to write won't "fit" in between other things you want to preserve, you need to re-write the remainder of the file, typically copying from the old file to a new one, modifying the data as required along the way through.

    Edit: something like this:

    #include <fstream>
    #include <ios>
    #include <iterator>
    #include <vector>
    
    int main() { 
        std::vector<double> data;
    
        std::fstream file("yourfile.txt", std::ios::in | std::ios::out);
        std::copy(std::istream_iterator<double>(file), 
            std::istream_iterator<double>(),
            std::back_inserter(data));
        file.clear();
        file.seekp(0);
        data[2] = 19.98;
        std::copy(data.begin(), data.end(), std::ostream_iterator<double>(file, " "));
        return 0;
    }
    

    This has a few effects that you may not want -- particularly, as it stands, it destroys whatever "line" oriented structure the original may have had, and simply writes out the result as one long line. If you want to avoid that, you can (for example) read in a line at a time, convert the numbers in the line (e.g. put then into a stringstream, then read them out of there as doubles), modify those, put the result back into a string, and write out the line with a "\n" at the end.

  • You can use a std::wfstream.

    #include <fstream>
    
    using namespace std;
    int main() {
        wfstream file(L"example.txt", std::ios::in | std::ios::out);
        std::wstring first, second, third; // The extraction operator stops on whitespace
        file >> first >> second >> third;
        third = L"Whatever I really, really, want!";
        file << first << second << third;
        file.flush(); // Commit to OS buffers or HDD right away.
    }
    

    I've probably screwed up the use of the insertion operator. But, you can reference MSDN for the exactitudes of using the wfstream. I'd absolutely advise against using any C solution, all their string manipulation functions truly suck.

Is it possible to call a procedure within an SQL statement?

Hi everyone

I thought I would use a stored routine to clean up some of my more complex SQL statements. From what I've read, it seems impossible to use a stored procedure within an sql statement, and a stored function only returns a single value when what I need is a result set. I am using mySQL v5.0

SELECT p.`id`, gi.`id`
FROM `sport`.`players` AS p JOIN `sport`.`gameinstances` AS gi
ON p.`id` = gi.`playerid`                       
WHERE (p.`playerid` IN (CALL findPlayers`("Canada", "2002")))
    AND (gi.`instanceid` NOT IN (CALL findGameInstances`("Canada", "2002")));

For example, the procedures 'findPlayers' and 'findGameInstances' are are stored routines that execute some SQL and return a result set. I would prefer not to include their code directly within the statement above.

From stackoverflow
  • Check out this discussion. This answers your questions and gives you some alternatives as well.

  • I don't know if mysql can use any of these techniques, but in SQl server I would try one of two different things (at least it might give you something to look for in th emysql documentation):

    First a table values used defined function then join to that Second, insert the results set of the sp into a temp table then join to the tem table

    You could also consider putting the complicated logic in a view and then just adding the where clause after joining to the view. This won't work if your stored proc does dynamic things a view can't do, but it is a possibilty.

Remove leading zeros from abbreviated date with PHP

Hello,

I was wondering if there is a way, using PHP, to change this date format: 01.08.86 (January 8, 1986) to this format: 1.8.86.

From stackoverflow
  • <?php
    
    $date = "01.08.86";
    $unix = strtotime($date);
    echo date('n.j.y', $unix);
    
    j-man86 : All I really needed was n.j.y Thanks alot Sean!
  • How about a regex based solution:

    $str = '01.08.86';
    $a = array('/^0(\d+)/','/\.0(\d+)/');
    $b = array('\1','.\1');
    $str = preg_replace($a,$b,$str);
    
    // $str is now '1.8.86'
    

String method to get unknown value that matches regex from string

Hi,

In Java is there a way to extract the value of an unknown subset of a string via a regex. For example in the following string "hello world 1234" I want to be able to extract the value 1234 via the regex [0-9]*. Is there a way to do this?

From stackoverflow
  • Yes - put the bit that you want into a group in the regex.

    There's a sort of tutorial here or find "capturing the string that matched a pattern" in this longer page.

  • It's actually quite easy with provided API:

    • you generate your regexp pattern by Pattern p = Pattern.compiler("regexp")
    • you try to match the pattern with the string you need: Matcher m = p.matches(string)
    • lastly you iterate over groups captured

      for (int i = 0; i < m.groupCount(); ++i) System.out.println(m.group(i));

  • Additionally, you can always check the 'official' tutorial regarding REGEX: here.

Win32 API - Create Button help

I try to create 2 buttons inside my app

case WM_CREATE:{
    hWnd =CreateWindowEx(NULL,
            L"BUTTON",
            L"Giai PTB2",
            WS_TABSTOP|WS_VISIBLE|
            WS_CHILD|BS_DEFPUSHBUTTON,
            100,
            100,
            100,
            24,
            hWnd,
            (HMENU)IDC_PTB2_BUTTON,
            hInst,
            NULL);
    HWND hWndNew =CreateWindowEx(NULL,
            L"BUTTON",
            L"Tim max",
            WS_TABSTOP|WS_VISIBLE|
            WS_CHILD|BS_DEFPUSHBUTTON,
            200,
            200,
            100,
            100,
            hWnd,
            (HMENU)IDC_PTB2_BUTTON2,
            hInst,
            NULL);
    break;
               }

The problem is , only "Giai PTB2" button shows :) Thanks first :)

From stackoverflow
  • check hWnd .. you are changing is value by the first create the side effect is that you are passing the first button as parent of the second ...

    jpyllman : And by that creating the second button inside the first button. And also hWnd is probalby your handle for the main window. So you loose that handle and doing other things wrong too.
    nXqd : Thanks it does help :)

Problem in getting refernce to ajax extender control

hi,

I am having problem in getting reference of Ajax control extender using $find() or $get or document.getElelmentById() functions in java script

Can any one tell me how can to do this?

Thanks in advance :)

From stackoverflow
  • Try this

    $get('<%=extenderId.ClientID %>') or document.getElementById('<%=extenderId.ClientID %>')

    Neo : i already tried it but it wont work for mw
    schrodinger's code : can you post your .aspx or .ascx markup here?

Icons in dired in Emacs (on Mac or Linux)

I'd like to have dired show a little icon next to each file, similar to what you'd see in "list" or "details" view on a graphical file browser. Someone posted a similar question but the only answer was for Windows only; I want to be able to do this on Linux or Mac.

From stackoverflow
  • I'm pretty sure the sad answer is "no, unless you do some extensive hacking of the dired-mode source code".

  • I think "bignose" is right, you would not be able to do that easily. But check out Dired+. It can colorize files by type so you can get some visual feedback on your dired buffer.

ibatis/Oracle - SELECT query inside INSERT is failing

Hi,

I'm trying to do an Insert operation using iBatis.

    INSERT INTO SCHEMA.TABLE
       (FIELD1, 
        FIELD2, 
        FIELD3)
     VALUES
       (#field1#, 
            (SELECT 
                ANOTHER_FIELD
            FROM 
                SCHEMA.TABLE
            WHERE 
                FIELD4= #field2#), 
        #field2#)

The inner select query always fails and returns NULL. But if I substitute #field2# with the actual value only in the inner query, it works fine. Why is iBatis not substituting fieldvalues in the innerqueries?

Any ideas?

From stackoverflow
  • The following way using a single sub-query and omitting the VALUES keyword would work with Oracle, please try with iBatis:

    INSERT INTO SCHEMA.TABLE
       (FIELD1, 
        FIELD2, 
        FIELD3)
       (
            SELECT
                #field1#, 
                ANOTHER_FIELD,
                #field2#
            FROM 
                SCHEMA.TABLE
            WHERE 
                FIELD4= #field2#
       )
    
    whoopy_whale : It works! Thanks a lot...
    Jeffrey Kemp : Note: the parentheses around the SELECT are optional.
  • That syntax is invalid for Oracle. Try the following:

    INSERT INTO SCHEMA.TABLE
       (FIELD1, 
        FIELD2, 
        FIELD3) 
       SELECT 
           #field1#,
           ANOTHER_FIELD,
           #field2#
       FROM 
           SCHEMA.TABLE
       WHERE 
           FIELD4= #field2#
    

Rubygems auto install from source code

Hi all,

I was wondering if there was a solution to automatically - from my ruby source code - ask Gem to install various librairies my code my require to work?

From what i read on the internet, it seems we are obliged to either use an install script that directly runs "gem install ..." commands or do it manually or some people have posted a ruby script that simply iterate over a list of dependencies and use the system command to install them.

Any other better options?

Thanks for your time.

From stackoverflow
  • You could use internal RubyGems commands, but that's a pain and error-prone process, especially for dependencies.

    I would setup a Gemfile and use Bundler instead. http://github.com/carlhuda/bundler

  • How is it possible to auto install gems automatically when the application is run without having to type "bundle install" in terminal previously? What is the code? I have been trying to do so, but the only thing that i succeeded with was to bypass rubygems so that application has its own local repository with gems, and that it uses these rather than gems on ruby path load (by creating a preinitializer.rb). I am using bundler 0.9.11 and rails 2.3.5.

one more question on sqlite3 for iphone..sorry*

let's say i am trying to save an image selected from photo library to database..is the following code correct?

Snap.m

- (void) addSnap {
  if(addStmt == nil) {
  const char *sql = "insert into Snap(snapTitle, snapDesc, snapImage) Values(?, ?, ?)";
  if(sqlite3_prepare_v2(database, sql, -1, &addStmt, NULL) != SQLITE_OK)
    NSAssert1(0, @"Error while creating add statement. '%s'", sqlite3_errmsg(database));
  }
  sqlite3_bind_text(addStmt, 1, [snapTitle UTF8String], -1, SQLITE_TRANSIENT);//bind titleSnap to insert statement
  sqlite3_bind_text(addStmt, 2, [snapDescription UTF8String], -2, SQLITE_TRANSIENT);
  sqlite3_bind_int(addStmt, 3, snapID);

  NSData *imgData = UIImagePNGRepresentation(self.snapImage);
  int returnValue = -1;
  if(self.snapImage != nil)
    returnValue = sqlite3_bind_blob(addStmt, 3, [imgData bytes], [imgData length], SQLITE_TRANSIENT);
  else
    returnValue = sqlite3_bind_blob(addStmt, 3, nil, -1, NULL);

  sqlite3_bind_int(addStmt, 4, snapID);

  if(returnValue != SQLITE_OK)
    NSLog(@"Not OK!!!");



  if(SQLITE_DONE != sqlite3_step(addStmt))//execute step statement if it return SQLITE_DONE
    NSAssert1(0, @"Error while inserting data. '%s'", sqlite3_errmsg(database));
  else
//sqlite3_last_insert_rowid
    snapID = sqlite3_last_insert_rowid(database);//get primary key for the row which was inserted

//reset add statement
   sqlite3_reset(addStmt);
}

- (void)setSnapImage:(UIImageView *)theSnapImage {
  self.isDirty = YES;
  [snapImage release];
  snapImage = [theSnapImage copy];
}

then to get the "object" i use..

snap2playObj.snapImage = imageView.image;

i am using UIImageView by the way..my error message..

-[UIImage copyWithZone:]: unrecognized selector sent to instance 0xd74750
 2010-03-18 16:22:27.808 Snap2Play[68317:20b] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[UIImage copyWithZone:]: unrecognized selector sent to instance 0xd74750'
From stackoverflow
  • Your SQL statement does not match the parameters your are binding. You have three parameters in your insert statement:

    const char *sql = "insert into Snap(snapTitle, snapDesc, snapImage) Values(?, ?, ?)";
    

    but you bind four parameters:

    sqlite3_bind_text(addStmt, 1, [snapTitle UTF8String], -1, SQLITE_TRANSIENT);//bind titleSnap to insert statement
    sqlite3_bind_text(addStmt, 2, [snapDescription UTF8String], -2, SQLITE_TRANSIENT);
    sqlite3_bind_int(addStmt, 3, snapID);
    
    sqlite3_bind_int(addStmt, 4, snapID);
    

    You need to make these statements match.

    summer : how do i retrieve the image that was save?
    kharrison : did you not already post that question here: http://stackoverflow.com/questions/2445889/sqlite3-problem-need-help-urgently-help/2446195#2446195 Would be good if you started accepting some of the answers

Creating an application for facebook that could gather data on page views by others

Is it possible to pull the information on someone viewing someone else's profile? Would that app be leagal on Facebook? There are lot of "fake" apps like that exist now on Facebook. But can that be done really?

From stackoverflow
  • In short answer, No. Long answer, if Facebook allowed apps to collect such info it would a mess.

Getting the physical path

I have to fetch all the files from a folder and i am using the function GetFiles() like

string[] dirImages = Directory.GetFiles(strPathYearImages + intYear , "*.png");

where strPathYearImages="Images\Holiday\2010\"

but when i write the whole path like

string[] dirImages = Directory.GetFiles(@"E:\IWP\Images\Holiday\"+ intYear , "*.png");

i get the required result.

How to solve this problem? I dont want to use the whole path. Help me out.

Regards, Jigar <3

From stackoverflow
  • The problem is the first snippet tries to get the images under current path. So you could tell the images path relative to your current path.

    Brigadier Jigar : Yes but how can i get the whole path? It is like the Images folder can be placed anywhere so i have to make the path dynamicaccording to the path where Images folder is placed.
    thelost : You cannot determine the full path to something you do not know where it resides. So you have to search fist.
  • Maybe it's because you are running it from VS inside. Your executable is in ProjectName\bin\Debug, therefore it looks for ProjectName\bin\Debug\Images, which obviously does not exists.

    Brigadier Jigar : No it is not the case. Thank You.
  • The documentation for GetFiles() says:

    The path parameter is permitted to specify relative or absolute path information. Relative path information is interpreted as relative to the current working directory

    So you would want to make sure the current working directory is set correctly before trying to use the relative paths (eg to E:\IWP):

    GetCurrentDirectory

    SetCurrentDirectory

  • Use Application.StartupPath to get the location where the executable is running. From there you need to know where the images directory is relative to that directory. The only other option is the absolute path. How else would it know where to look?

    You can also try using System.IO.Path methods to help - especially for combining path strings, plus it also gives you the location of special folders like My Documents, AppData, and the desktop.

  • Hey all, i got the answer to my question. I just had to write

    string[] dirImages = HttpContext.Current.Server.MapPath(strPathImages + intYear , "*.png");

    Hope that it is helpful to all...

Mapping from different properties based on discriminator value using AutoMapper

I have one very general object that I want to map to a destination type using AutomMapper, but I want to map it to different types depending on the value of a property in the source type. For example, let's say I have:

public class Source
{
    public string Discriminator { get; }
    public string ValueA { get; }
    public string ValueB { get; }
}

public class Target
{
    public string Value { get; set; }
}

And I want to map Source.ValueA to Target.Value if Source.Discriminator == "A" and Source.ValueB to Target.Value if Source.Discriminator == "B".

Is this possible using AutoMapper?

From stackoverflow
  • You can do something like this:

    Mapper.Map<Spurce, Target>().ForMember(x => x.Value, x => x.MapFrom(y => {
        if(y.Discriminator == "A")
            return y.ValueA;
        return y.ValueB;
        });
    
    Karl : I could, but I want to use Automapper's functionality if possible. I reality I have several source fields and several target fields. If I use the method you suggest I will have to add several if/else-statements for each target member which is what I want to avoid.
    Mattias Jakobsson : @Karl, You don't need to hard code it the way I did here. You might just as well use reflection based on your conventions.
    Karl : Ahh, yes, that would work. Thanks!

what does 'legend' mean in sql?

im doing some practice sql problems

one of the questions is:

Prepare a shipping statement for customer 'C001' it should show the date, the legend 'Delivery' and the total value of the products shipped on each day.

'delivery' is not a table nor is it a column in any table.

what does legend mean??

From stackoverflow
  • It doesn't mean anything in SQL. In English it means the label at the top of the column or next to the data that explains what the data is.

    In other words, produce a listing showing the customer number, the date, and a column labeled "Delivery" that shows the total value of goods shipped to that customer on that date.

  • In this case I think it means the title for the shipping statement.

    From the dictionary -

    Legend

    3 an inscription, esp. on a coin or medal. • a caption : a picture of a tiger with the legend “Go ahead, make my day.” • the wording on a map or diagram explaining the symbols used

  • "Legend" is not strictly speaking an SQL term - but in that case it is used to indicate the name of the column. Somewhat poor naming, since legend actually means overall set of labels/explanations and not a single label

how to add markup to text using JavaScript regex

I need to add markup to some text using JavaScript regular expressions. In Python I could do this with:

>>> import re
>>> re.sub('(banana|apple)', r'<b>\1</b>', 'I have 1 banana and 2 apples!')
'I have 1 <b>banana</b> and 2 <b>apple</b>s!'

What is the equivalent in JavaScript? string.replace(regex, newstring) seems to only take a raw string for replacing.

From stackoverflow
  • In the new string, you can reference capture groups via the tokens $1, $2, etc. A lot of the high-level reference sites (like w3schools) fail to document that. It's in the spec, of course, or more accessibly discussed on MDC.

    So taking your example:

    "I have 1 banana and 2 apples!".replace(/(banana|apple)/gi, "<b>$1</b>");
    

    (Of course, the "s" in "apples" won't be inside the tag...) I used the 'i' flag there assuming you want to process "Banana" and "Apple" as well as "banana" and "apple".

    Plumo : thanks - I was working from the w3schools documentation
    T.J. Crowder : @Richard: Glad to help. Amusingly, I was surprised when I ran across this feature of #replace...because I, too, had been working from the w3schools pages. :-) Those pages are useful, but really *really* incomplete, so I work from the spec and MDC a lot more now.
    Plumo : wow the Mozilla JavaScript documentation is so detailed! - I will have to get into the habit of checking there first.
  • You can use String.replace() for this and use $n to reference captured groups from the regular expression:

    var in = 'I have 1 banana and 2 apples!';
    var out = in.replace(/(banana|apple)/g, "<b>$1</b>");
    

Replace CHAR with VARCHAR2

How can I replace CHAR with VARCHAR2 in all tables in a schema?

Note: I'm content with a query that returns the ALTER TABLE statements so I can save the script and run it again.

From stackoverflow
  • select 'ALTER TABLE "' || owner || '"."' || table_name
    || '" MODIFY ("' || column_name
    || '" VARCHAR2(' || data_length || '));'
    from all_tab_columns
    where data_type = 'CHAR'
    and owner = :schemaname
    and exists (
        select 1
        from all_tables t
        where tc.owner = t.owner
        and tc.table_name = t.table_name
    );
    
    Aaron Digulla : I've extended the original answer to omit tables which are in the recycle bin. See http://stackoverflow.com/questions/2446053/what-are-the-bin-tables-in-oracles-all-tab-columns-table

What's the significant improve from UML 2.0 to UML 1.4?

BTW,what's the latest version of UML,and how often does it release a new version?

From stackoverflow
  • As far as I'm aware there's no regular release schedule. As for the differences between versions, you can find a summary for example here, probably a bit more readable here.

  • The latest version of UML is UML 2.2 which is built on the top of xmi 2.1. See more at: http://www.eclipse.org/modeling/mdt/?project=uml2

Google Analytics: Avg. Time on Site

Hi,

i have a website and i have a Google Analytics code only on index.html code.

What does Avg. Time on Site measure? Average time spend by visitors on all sites or average time on one website (index.html)?

Regards

From stackoverflow
  • Average Time on Site measures the time an user spent on all pages (the site). If it would be the time spend on e.g. index.html it would be named "Average Time on Page". Which is hard to measure as people very often keep tabs open will browsing other stuff.

    MB1 : Thank you. Regards
  • MB, reading this page may be helpful for you.

How can I partition a vector?

How can I build a function

slice(x, n) 

which would return a list of vectors where each vector except maybe the last has size n, i.e.

slice(letters, 10)

would return

list(c("a", "b", "c", "d", "e", "f", "g", "h", "i", "j"),
     c("k", "l", "m", "n", "o", "p", "q", "r", "s", "t"),
     c("u", "v", "w", "x", "y", "z"))

?

From stackoverflow
  • You can use the split function:

    split(letters, as.integer((seq_along(letters) - 1) / 10))
    

    If you want to make this into a new function:

    slice <- function(x, n) split(x, as.integer((seq_along(x) - 1) / n))
    slice(letters, 10)
    
  • slice<-function(x,n) {
        N<-length(x);
        lapply(seq(1,N,n),function(i) x[i:min(i+n-1,N)])
    }
    
    Karsten W. : Seems to be faster than the split solution...

What's the simplest way to create a Zend_Form tabular display with each row having a radio button?

I've seen simple examples of rendering a Zend_Form using decorators, but I'm not sure they are able to handle the issue I'm facing very well.

I query the database and get an array of user objects. I want to display these users as a form, with a radio button next to each of them and a submit button at the bottom of the page.

Here's roughly what the form will look like:

   [user id]  [email]         [full name]
( ) 1         test@test.com   Test user 1
(*) 2         test2@test.com  Test user 2
[SUBMIT]

Is this something achievable in a reasonably straightforward way or do I need to use the ViewScript partial?

From stackoverflow
  • You should easily achieve this layout Leveraging Zend Form Decorators.

    Edit:

    You may be interested also on Zendcasts:
    Zend Form decorators explained and Creating custom Zend Form Decorators.

    BTW, This is pretty common layout for preferences:

    Display preferences

    Once you are finished, post your working code here for reference.

    RenderIn : Thanks! I've seen lots of articles on decorators but that's the first that tackles things in a way that works in my situation -- templating with sprintf rather than just clothing an input in static HTML.
    takeshin : I have added two more links to my original post.
  • Just a quick suggestion. Why do you need table for this? The default definition list markup can be styled to look exactly like you want it to look.

    RenderIn : I need 3+ columns per row and I need headers for each column. Not sure how a list can ensure each column will line up with other rows' data and also with the headers.

Why is the value of this string, in a bash script, being executing?

Hello

Why is this script executing the string in the if statement:

#!/bin/bash
FILES="*"
STRING=''

for f in $FILES
do
  if ["$STRING" = ""]
   then
    echo first
    STRING='hello'
   else
    STRING="$STRING hello"
  fi
done

echo $STRING

when run it with sh script.sh outputs:

first
lesscd.sh: line 7: [hello: command not found
lesscd.sh: line 7: [hello hello: command not found
lesscd.sh: line 7: [hello hello hello: command not found
lesscd.sh: line 7: [hello hello hello hello: command not found
lesscd.sh: line 7: [hello hello hello hello hello: command not found
hello hello hello hello hello hello

p.s. first attempt at a shell script
thanks

From stackoverflow
  • You are trying to execute the command [hello. Put a space after [ so it will be regognized as a test.

    for f in $FILES
    do
      if [ "$STRING" = "" ]
       then
        echo first
        STRING='hello'
       else
        STRING="$STRING hello"
      fi
    done
    
    Ross : thanks. i'm going to learn ruby instead : )
  • Assuming that the line 'echo first' is merely for debugging, you can achieve the same thing with:

    STRING=$STRING${STRING:+ }hello
    

    (That is, the above line will produce the same result as your if statement, but will not echo 'first')

    The expression '${STRING:+ }' evaluates to nothing if $STRING is empty or null, and it evaluates to a space otherwise.

Make process run on non EDT (event dispatch thread) thread from EDT

I have a method running on the EDT and within that I want to make it execute something on a new (non EDT) thread. My current code is follows:

@Override
    public void actionPerformed(ActionEvent arg0) {
//gathering parameters from GUI

//below code I want to run in new Thread and then kill this thread/(close the JFrame)
new GameInitializer(userName, player, Constants.BLIND_STRUCTURE_FILES.get(blindStructure), handState);
}
From stackoverflow
  • You can create and start a new Java Thread that executes your method from within the EDT thread :

    @Override
        public void actionPerformed(ActionEvent arg0) {
    
            Thread t = new Thread("my non EDT thread") {
                public void run() {
                    //my work
                    new GameInitializer(userName, player, Constants.BLIND_STRUCTURE_FILES.get(blindStructure), handState);
                }
    
            };
            t.start();
        }
    
    Aly : I want it to be executed outside of the EDT, on a new thread
    Amir Afghani : Look at my example, the work would not be executed on the EDT.
    Aly : Thanks I called t.run() instead which made it break
    Tom Hawtin - tackline : Why no `@Override` on `run`, or better why not use `Runnable`?
    Amir Afghani : I'm not here to spoon feed - both of those are great ideas.
  • You can use SwingWorker to undertake a task on a worker thread off the EDT.

    E.g.

    class BackgroundTask extends SwingWorker<String, Object> {
        @Override
        public String doInBackground() {
            return someTimeConsumingMethod();
        }
    
        @Override
        protected void done() {
            System.out.println("Done");
        }
    }
    

    Then wherever you call it:

    (new BackgroundTask()).execute();
    
  • Sorry, wrong thread.

Lucene wildcard queries

Hello,

I have this question relating to Lucene.

I have a form and I get a text from it and I want to perform a full text search in several fields. Suppose I get from the input the text "textToLook".

I have a Lucene Analyzer with several filters. One of them is lowerCaseFilter, so when I create the index, words will be lowercased.

Imagine I want to search into two fields field1 and field2 so the lucene query would be something like this (note that 'textToLook' now is 'texttolook'):

field1: texttolook* field2:texttolook*

In my class I have something like this to create the query. I works when there is no wildcard.

String text = "textToLook";
String[] fields = {"field1", "field2"};
//analyser is the same as the one used for indexing
Analyzer analyzer = fullTextEntityManager.getSearchFactory().getAnalyzer("customAnalyzer");
MultiFieldQueryParser parser = new MultiFieldQueryParser(fields, analyzer);
org.apache.lucene.search.Query queryTextoLibre = parser.parse(text);

With this code the query would be:

field1: texttolook field2:texttolook

but If I set text to "textToLook*" I get

field1: textToLook* field2:textToLook*

which won't find correctly as the indexes are in lowercase.

I have read in lucene website this:

" Wildcard, Prefix, and Fuzzy queries are not passed through the Analyzer, which is the component that performs operations such as stemming and lowercasing"

My problem cannot be solved by setting the behaviour case insensitive cause my analyzer has other fields which for examples remove some suffixes of words.

I think I can solve the problem by getting how the text would be after going through the filters of my analyzer, then I could add the "*" and then I could build the Query with MultiFieldQueryParser. So in this example I woud get "textToLower" and after being passed to to these filters I could get "texttolower". After this I could make "textotolower*".

But, is there any way to get the value of my text variable after going through all my analyzer's filters? How can I get all the filters of my analyzer? Is this possible?

Thanks

From stackoverflow
  • Can you use QueryParser.setLowercaseExpandedTerms(true)?

    http://wiki.apache.org/lucene-java/LuceneFAQ#Are_Wildcard.2C_Prefix.2C_and_Fuzzy_queries_case_sensitive.3F

    ** EDIT **

    Okay, I understand your issue now. You actually want the wildcarded term to be stemmed before it's run through the wildcard query.

    You can subclass QueryParser and override

    protected Query getWildcardQuery(String field, String termStr) throws ParseException
    

    to run termStr through the analyzer before the WildcardQuery is constructed.

    This might not be what the user expects, though. There's a reason why they've decided not to run wildcarded terms through the analyzer, per the faq:

    The reason for skipping the Analyzer is that if you were searching for "dogs*" you would not want "dogs" first stemmed to "dog", since that would then match "dog*", which is not the intended query.

    Javi : I had already seen this, but it doesn't solve the problem. I have more filters than the lowercase one. As I mentioned one of them eliminates suffixes of words, so if I index for example "changeable" it would be index as "change", so if I would search for "changes" in the query should get the root of the word ("change") and look for "change*" and these words would match.

Ftp library on c++ with uploading over HTTP proxy

Is anybody knows the free library for uploading over proxy with Http authentication? Maybe some url on samples how it could be.

From stackoverflow
  • You can use libcurl. You can see a FTP upload sample here.

    For adding http proxy authentication, you will need to use options CURLOPT_PROXY, CURLOPT_PROXYPORT, CURLOPT_PROXYTYPE, CURLOPT_PROXYUSERPWD and CURLOPT_PROXYUSERNAME with curl_easy_setopt.

    I might be missing something since I can't test it right now, but you can see the documentation in detail here.

  • Thanks. I'l try it.

How do I nest my header object in the jQuery Accordion

I've got a UL list and for reasons of CSS styling, I need to nest the object I wish to use as the header for my accordion inside a div within the LI. Such that:

<ul>
    <li>
        <div>
            <h4>Header</h4>
        </div>
        <p>This is my content</p>
    </li>
    ... other lis...
</ul>

Now, I'm wanting to hook up my accordion:

$(document).ready(function() {
    $('ul').accordion({
        header: '' //What do I put here?
    });
});

When I set the header to h4, it doesn't work, when I use the div, it only works at the edge where the padding in the div reveals it from under the h4. Is there a way of referencing the h4 within the div as the header? I tried 'div>h4' but that doesn't work. I'm sure this is quite simple but I haven't discovered how.

Cheers in advance.

From stackoverflow
  • The accordion works by finding your header selector matches then calling a .next() to get the content portion. So for your markup, just use this:

    $('ul').accordion({
        header: 'li>div' //.next() will get the <p>
    });
    

    I tested this, works fine here.

    BenAlabaster : It seems to work okay if you're using the click event, but not if you're using the mouseover event.
    Nick Craver : @BenAlabaster - This is working here for me in Firefox, Chrome and IE, what browser are you seeing problems in? `$('ul').accordion({ header: 'li>div', event: 'mouseover' });`

Edit Html.ActionLink output string

I'm trying to output the following HTML using Html.ActionLink:

<a href="/About" class="read-more">Read More<span class="arrow">→</span></a>

I'm getting it done by doing an ActionLink, which outputs an <a> tag and then manipulating the string.

<%= Html.ActionLink("[[replace]]", "Index", "About", null, new { @class = "read-more" }).ToHtmlString().Replace("[[replace]]", "Read More" + "<span class='arrow'>→</span>")%></p>

It'd be good if I could put HTML directly into the ActionLink but there doesn't seem to be a way based on my internet searches. Sure, it works but it seems like a hack. Is there a better way to accomplish this?

From stackoverflow
  • You could write you're own HTML helper class and make it fit whatever needs you have. I've wrote a few before, I see the ones you get with MVC as just a start.

    Here's a link with a tutorial. And here's and official MS video on how to.

  • If all you need is the arrow and you could use an image, you could use stylesheet to put that image after the link

    .readmore-link{background-image: url('/image.png'); padding-right: 16px; /*...*/}
    

    just tweak the image position etc.

    Otherwise I'd recommend writing extension method for HtmlHelper.

  • Aaron...Did you work this out?

    I use Url.Action in the href attribute when I need something other than just the link text in the outputted HTML.

    <a href="<%= Url.Action("About") %>" class="read-more">Read More<span class="arrow">→</span></a>
    

    Hope this helps.

    Cheers, -jc

Using MicrosoftReportViewer with Web Forms programmatically

Hi, I'm repeating my question because the prior one under this topic was lost. Could you please help me? I want to use MicrosoftReportViewer for Web Forms so that the DataSource be set programmatically. There is some sample code on the Internet for Windows Forms but I haven't found anything for Web Forms. For example, here is some code I've tried to use. It gives no errors but nothing is displayed.

How should I modify the code to display a table in the ReportViewer?

Imports System.Data Imports Microsoft.Reporting.WebForms

Partial Class TestReportViewer Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    CreateReport()
End Sub

Sub CreateReport()
    Dim dt As DataTable
    Dim rpt As ReportDataSource
    dt = New DataTable("Sample")
    With dt
        .Columns.Add("No", GetType(Integer))
        .Columns.Add("Name")
        .Rows.Add(1, "A1")
        .Rows.Add(2, "A2")
        .Rows.Add(3, "A3")
        .Rows.Add(4, "A4")
        .AcceptChanges()
    End With
    rpt = New ReportDataSource
    rpt.DataMember = "Sample"
    rpt.Value = dt
    rpt.Name = "test"

    With ReportViewer1
        .LocalReport.DataSources.Add(rpt)
        .DataBind()
        .LocalReport.Refresh()
    End With
End Sub

End Class

From stackoverflow
  • Have a look at this link: http://odetocode.com/articles/128.aspx

    You can basically do the same as in WinForms:

    Instantiate ReportViewer in your code behind and set

     ReportViewer reportViewer1 = new ReportViewer(); 
     reportViewer1.ServerUrl="http://localhost/ReportServer";
     reportViewer1.ReportPath="/SampleReports/Sales Order Detail";
    

    Or

    reportViewer1.LocalReport.DataSources.Add(new ReportDataSource("datasetname", dataSet.Tables[0]));
    

    Michael

JavaScript image popup library that allows you to open several images on the same time?

I'm looking for a JS library that will allow me to open several images by clicking on their thumbnails and be able move the opened windows (divs) by dragging them.

It has to allow you to open more than one image at a time (so you could drag them and compare them).

From stackoverflow
  • A library which would work for you is Highslide (free for non commercial use), which I've found easy to use. Click the images on the home page and you'll see you can have multiple open at once.

    There are also lots of popup gallery plugins for jQuery, you may find something of interest in this Top 14 list.

  • How about using ZoomImage (uses JQuery).