Thursday, April 19, 2012

Is there a better way to iterate over this multi-dimensional array in PHP?

I am using the Solr search engine. It returns my search results like so:



array(2) {
["responseHeader"]=>
array(3) {
["status"]=>
int(0)
["QTime"]=>
int(1)
["params"]=>
array(5) {
["wt"]=>
string(3) "php"
["start"]=>
string(1) "0"
["q"]=>
string(7) "monitor"
["version"]=>
string(3) "2.2"
["rows"]=>
string(2) "10"
}
}
["response"]=>
array(3) {
["numFound"]=>
int(2)
["start"]=>
int(0)
["docs"]=>
array(2) {
[0]=>
array(11) {
["id"]=>
string(6) "VA902B"
["name"]=>
string(49) "ViewSonic VA902B - flat panel display - TFT - 19""
["manu"]=>
string(15) "ViewSonic Corp."
["weight"]=>
float(190.4)
["price"]=>
float(279.95)
["price_c"]=>
string(10) "279.95,USD"
["popularity"]=>
int(6)
["inStock"]=>
bool(true)
["store"]=>
string(18) "45.17614,-93.87341"
["cat"]=>
array(2) {
[0]=>
string(11) "electronics"
[1]=>
string(7) "monitor"
}
["features"]=>
array(1) {
[0]=>
string(75) "19" TFT active matrix LCD, 8ms response time, 1280 x 1024 native resolution"
}
}
[1]=>
array(12) {
["id"]=>
string(7) "3007WFP"
["name"]=>
string(34) "Dell Widescreen UltraSharp 3007WFP"
["manu"]=>
string(10) "Dell, Inc."
["includes"]=>
string(9) "USB cable"
["weight"]=>
float(401.6)
["price"]=>
float(2199)
["price_c"]=>
string(8) "2199,USD"
["popularity"]=>
int(6)
["inStock"]=>
bool(true)
["store"]=>
string(18) "43.17614,-90.57341"
["cat"]=>
array(2) {
[0]=>
string(11) "electronics"
[1]=>
string(7) "monitor"
}
["features"]=>
array(1) {
[0]=>
string(71) "30" TFT active matrix LCD, 2560 x 1600, .25mm dot pitch, 700:1 contrast"
}
}
}
}
}


I am capturing this response inside a variable called $results. On my page I am doing a vardump to get each result set like so:



foreach($results['response'] as $result) {
if(is_array($result)) {
foreach($result as $v) {
var_dump($v);
}
}
}


This is the output of that:



array(11) {
["id"]=>
string(6) "VA902B"
["name"]=>
string(49) "ViewSonic VA902B - flat panel display - TFT - 19""
["manu"]=>
string(15) "ViewSonic Corp."
["weight"]=>
float(190.4)
["price"]=>
float(279.95)
["price_c"]=>
string(10) "279.95,USD"
["popularity"]=>
int(6)
["inStock"]=>
bool(true)
["store"]=>
string(18) "45.17614,-93.87341"
["cat"]=>
array(2) {
[0]=>
string(11) "electronics"
[1]=>
string(7) "monitor"
}
["features"]=>
array(1) {
[0]=>
string(75) "19" TFT active matrix LCD, 8ms response time, 1280 x 1024 native resolution"
}
}

array(12) {
["id"]=>
string(7) "3007WFP"
["name"]=>
string(34) "Dell Widescreen UltraSharp 3007WFP"
["manu"]=>
string(10) "Dell, Inc."
["includes"]=>
string(9) "USB cable"
["weight"]=>
float(401.6)
["price"]=>
float(2199)
["price_c"]=>
string(8) "2199,USD"
["popularity"]=>
int(6)
["inStock"]=>
bool(true)
["store"]=>
string(18) "43.17614,-90.57341"
["cat"]=>
array(2) {
[0]=>
string(11) "electronics"
[1]=>
string(7) "monitor"
}
["features"]=>
array(1) {
[0]=>
string(71) "30" TFT active matrix LCD, 2560 x 1600, .25mm dot pitch, 700:1 contrast"
}
}


This is exactly what I need but I was wondering if there is a more elegent way to get it than my "nested foreach loop and is array check" approach.





Matching numbers

I'm trying to finish a homework assignment and I can't find this anywhere. I'm trying to match input numbers with randomly generated numbers and displaying how many of the 5 are correct(also with a win/lose message) This is what I have so far and any help would be appreciated. :)



#include <iostream>
#include <cstdlib>

using namespace std;



void main()
{
//variables
int lottery[5], user[5];
int count = 0;
int num1, num2, num3, num4, num5;
int winnum;
//generating numbers
for (int i=0; i <5; i++)
{
lottery[i] =1+rand()%9;
}
//input
cout << "Enter a digit between 0-9: ";
cin >> num1;
cout << "Enter a digit between 0-9: ";
cin >> num2;
cout << "Enter a digit between 0-9: ";
cin >> num3;
cout << "Enter a digit between 0-9: ";
cin >> num4;
cout << "Enter a digit between 0-9: ";
cin >> num5;


winnum = rand();

//for (int i=0; i<5; i++)
// cin >> user[i];

//display


cout << "Winning Lottery Numbers: " << winnum << endl;

cout << "Your ticket Numbers: " << num1 << num2 << num3 << num4 << num5 << endl;




//matching the numbers

//HELP!
system("pause");

}




Buffered versus unbuffered output for Python in Windows

I use NppExec/Notepad++ to run Python scripts, and flush my output buffers continuously during runtime to update my console window with print statements (The default buffered output only shows all print statements after the script finishes execution).



This link shows that all you need to do is use the command python -u to get unbuffered output. Is there a downside to using this execution mode for all my Python scripts, regardless of the editor used? I'm not clear about the difference between a buffered an unbuffered output.





Tcl Tk treeview with checkbuttons

Is is possible to add check button to ttk::treeview column.



Specifically I am trying to create a checklist for the user to hide or show items on the canvas when the checkbox is selected or deselected. Since there are a lot of canvas items with specific type and sub type I need a list box kind of mechanism.





Final Local Variable may not have been initialized in anonymous inner class

Here is my code:



final Foo myFoo = new Foo(new Inner() {
@Override
callback(){
myFoo.bar();
}
});


Java is giving me an error about how myFoo might not have been initialized. Is there any way to fix this? I can potentially set the callback to null when I construct the object and then change it afterwards, but I'd hope for there to be a cleaner way. Any ideas? (Also that wouldn't work if Foo wasn't written by me and didn't expose an interface to change the callback later)



In case anyone is curious, in my specific scenario, Foo is an ArrayAdapter, and the callback is notifyDataSetChanged(). What is displayed by the adapter depends on the values of the items in the array, and those values change when they are clicked on. The callback is the clickListener.





How to update for each records without looping in SQL Server

I have a table and contained data show below, it's called TABLE_A




+++++++++++++++++++++++++++++++++++++++++++++
PrimaryID | Col2 | SecondaryID
+++++++++++++++++++++++++++++++++++++++++++++
1 | Description 1 | 0
2 | Description 2 | 0
3 | Description 3 | 0
4 | Description 4 | 0
. | ... | .
. |
.


please see SecondaryID, above. its has zero value as an initial value



and I have another table, it's called TABLE_B, below




+++++++++++++++++++++++++++++++++++++++++++++
PrimaryID | Col2 | ForeignKeyID
+++++++++++++++++++++++++++++++++++++++++++++
1 | Description 1 | 123
2 | Description 2 | 320
3 | Description 3 | 111
4 | Description 4 | 999
. | ... | .
. |
.


I have trouble in SQL Server,
How to update SecondaryID column on TABLE_A with ForeignKeyID value on TABLE_B for each row in TABLE_A's PrimaryID is equal TABLES_B's PrimaryID.
But, I don't want to solve this problem using LOOPING CURSORS or another else.



Are there a simple way??



I need urgent, and thank you in advanced.





How to get jQuery dialog to wait before displaying?

I'd like my jQuery dialog to display exactly 3 seconds after a user hovers over an image. Currently I have:



$(".imgLi").live('hover', function() {
showDialog();
});

function showDialog()
{
$('#imageDialogDiv').dialog({
modal:true
});
}

<div id="imageDialogDiv" title="Blah">...</div>


Not sure where too put the time code or how to implement jQuery's timer object here. If the use "mouses away" (moves the mouse away from the image) at any point during that 3 second timeframe, I do not want the dialog to display. Thanks in advance for any help here.





Overlapping views crossing boundaries (Fake actionbar)

I am trying to create a custom title bar strictly for Android 2.1 that somewhat emulates the ActionBar found in Android 3.0 and up.



So far I've had fairly decent luck, but I cannot find an easy way to make the drop-down lists that can appear below the icon / buttons in the ActionBar.



I would like these drop-down lists to be able to cross the boundary between the title layout and the content layout without being clipped / cut off. I would also like the drop-down lists to be positioned relatively below the icons / buttons in the ActionBar. I've seen advice to use FrameLayouts and RelativeLayouts already but these did not seem to solve my particular problem (unless I'm looking at it wrong). I keep thinking it must be possible since I believe the newer versions of Android have support for exactly this type of behavior.



Here is a screenshot of what I am trying to accomplish with some notes.
http://img217.imageshack.us/img217/3279/67343249.png



Please help. Thanks!!!





iReport 4.5.1 No Data Band display Sub Report

Hi I have to display a set of values which is my input parameter (displayed as sub report) even when the main report does not return any data. I added the sub report in the No data band and nothing is displayed. how do I resolve this issue...



I am using iReports 4.5.1 / Oracle Stored Procedure....



Also I have set "When No Data" report property to "No Data Section"



Thanks for your help in advance.



Meeza





Self is not defined

Here is the stack trace:



Traceback (most recent call last):
File "V:\Users\Administrator\AppData\Roaming\Blender Foundation\Blender\2.61\scripts\addons\ArenWorldExporter.py", line 73, in execute
_mkdir(self.filepath[:-4] + "\\models\\")
File "V:\Users\Administrator\AppData\Roaming\Blender Foundation\Blender\2.61\scripts\addons\ArenWorldExporter.py", line 73, in _mkdir
_mkdir(self.filepath[:-4] + "\\models\\")
NameError: global name 'self' is not defined


Here is the code:
http://pastebin.com/B2U0DAr8



All the spacing is set to 4 spaces, no tabs (not even sure if the python editor supports tabs)



Why is it saying that self is not defined? As it clearly is in the function.





query with grouped results by collum

I've got a many to many relationship between items-itemnames-languages



the itemnames don't appear for every language.



I'd like to get a result with all the items only represented once, but be able to set the languageId to default to.



for example items 1,2,3 are defined in two languages, and item 4 and 5 have one language each, but the languages are different



[itemid][languageid][name]
1, 1, item1
1, 2, leItem1
2, 1, item2
2, 2, leItem2
3, 1, item3
3, 2, leItem3
4, 1, item4
5, 2, leItem5


I'd like to create a query that only gives me one of each itemID, but allow me to specify which language to prefer, so if I select a languageID of 2, my query would only return item names for that start with 'leItem' with the exception of item 4, which should still give me item4



Any ideas how to achieve this with a SELECT?





How does one properly "forward" function arguments in bash?

I am wondering how arguments given to a function in bash can be properly "forwarded" to another function or program.



For example, in Mac OS X there is a command line program open (man page) that will open the specified file with its default application (i.e. it would open a *.h file in Xcode, or a folder in Finder, etc). I would like to simply call open with no arguments to open the current working directory in Finder, or provide it the typical arguments to use it normally.



I thought, "I'll just use a function!" Hah, not so fast there, I suppose. Here is what I've got:



function open
{
if [ $# -eq 0 ]; then
/usr/bin/open .
else
/usr/bin/open "$*"
fi
}


Simply calling open works great, it opens the working directory in Finder. Calling open myheader.h works great, it opens "myheader.h" in Xcode.



However, calling open -a /Applications/TextMate.app myheader.h to try to open the file in TextMate instead of Xcode results in the error "Unable to find application named ' /Applications/TextMate.app myheader.h'". It seems passing "$*" to /usr/bin/open is causing my entire argument list to be forwarded as just one argument instead.



Changing the function to just use usr/bin/open $* (no quoting) causes problems in paths with spaces. Calling open other\ header.h then results in the error "The files /Users/inspector-g/other and /Users/inspector-g/header.h do not exist", but solves the other problem.



There must be some convention for forwarding arguments that I'm just missing out on.





Pass data with (Intent putextra) in listactivity not working

i have listactivity forming 5 rows each row when clicked open new activity ,



i set separate class for each one (to customize it ) so i have 5 class:as (FirstCity,SecondCity,and so on )



in each row class i have many views , one of them button when clicked open customized infinite gallery ,



i want to pass this infinite gallery to 5 row classes by use putextra intent



but its not show the images ( show GalleryCity screen with customized title only)



, i have little experiance in android development ,



would you please help me , any advice will be appreciated , thanks



my code : GalleryCity class



 public class GalleryCity extends Activity {

/** Called when the activity is first created. */
static String city;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

Boolean customTitleSupported = requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
// Set the layout to use
setContentView(R.layout.main);
if (customTitleSupported) {
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.custom_title);
TextView tv = (TextView) findViewById(R.id.tv);
Typeface face=Typeface.createFromAsset(getAssets(),"BFantezy.ttf");
tv.setTypeface(face);
tv.setText("MY PICTURES");
}

Intent intent = getIntent();
city = intent.getStringExtra("galleryimags");

InfiniteGallery galleryOne = (InfiniteGallery) findViewById(R.id.galleryOne);



}
}


class InfiniteGalleryAdapter extends BaseAdapter {

private Context mContext;

public InfiniteGalleryAdapter(Context c, int[] imageIds) {
this.mContext = c;
}

public int getCount() {
return Integer.MAX_VALUE;
}

public Object getItem(int position) {
return position;
}

public long getItemId(int position) {
return position;
}

private LayoutInflater inflater=null;
public InfiniteGalleryAdapter(Context a) {
this.mContext = a;
inflater = (LayoutInflater)mContext.getSystemService (
Context.LAYOUT_INFLATER_SERVICE);
getImagesforCity();
}

private int[] images;
private void getImagesforCity() {
if(GalleryCity.city.equalsIgnoreCase("FirstCity")){
int[] imagestemp = {
R.drawable.pic_1, R.drawable.pic_2,
R.drawable.pic_3, R.drawable.pic_4,
R.drawable.pic_5
};
images=imagestemp;

}
if(GalleryCity.city.equalsIgnoreCase("SecondCity")){
int[] imagestemp = {
R.drawable.pic_6, R.drawable.pic_7,
R.drawable.pic_8, R.drawable.pic_9,
R.drawable.pic_10 };
images=imagestemp;

}


}

public class ViewHolder{
public TextView text;
public ImageView image;
}

private String[] name = {
" my picture " ,
" garden ",
" lake ",
" home land ",
" my car "
};

public View getView(int position, View convertView, ViewGroup parent) {
ImageView i = getImageView();

int itemPos = (position % images.length);

try {
i.setImageResource(images[itemPos]); ((BitmapDrawable) i.getDrawable()).
setAntiAlias (true);
}

catch (OutOfMemoryError e) {
Log.e("InfiniteGalleryAdapter", "Out of memory creating imageview. Using empty
view.", e);
}

View vi=convertView;
ViewHolder holder;
if(convertView==null){
vi = inflater.inflate(R.layout.gallery_items, null);
holder=new ViewHolder(); holder.text=(TextView)vi.findViewById

(R.id.textView1);
holder.image=(ImageView)vi.findViewById(R.id.image);
vi.setTag(holder);}
else {
holder=(ViewHolder)vi.getTag();
}
holder.text.setText(name[itemPos]);

final int stub_id=images[itemPos];
holder.image.setImageResource(stub_id);

return vi;
}

private ImageView getImageView() {

ImageView i = new ImageView(mContext);
i.setBackgroundResource(android.R.drawable.btn_default);
return i;
}
}

class InfiniteGallery extends Gallery {

public InfiniteGallery(Context context) {
super(context);
init();
}

public InfiniteGallery(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}

public InfiniteGallery(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}

private void init(){

setSpacing(25);
setHorizontalFadingEdgeEnabled(false);
}

public void setResourceImages(int[] name){
setAdapter(new InfiniteGalleryAdapter(getContext(), name));
setSelection((getCount() / 2));
}
}


in each row class (FirstCity,SecondCity,and so on ):



i put this code :



 public void handleClick(View v){


Intent intent = new Intent(this, GalleryCity.class);
intent.putExtra("galleryimags",city);
startActivity(intent);

}

}


also please advice me how to set different images String names for each row class :



   private String[] name = {
" my picture " ,
" garden ",
" lake ",
" home land ",
" my car "
};




Ruby 1.9.3 hash syntax not working with rspec-rails 2.9?

I have a Rails 3.2 project I just started, and I'm trying to write some tests.



When I try to utilize Ruby 1.9.3's JSON-esque hash syntax and do this:



let(:user) { User.new(first_name: 'Joe', last_name: 'Blow') }


or this:



let(:user) { User.new({first_name: 'Joe', last_name: 'Blow'}) }


I get this error:



syntax error, unexpected ':', expecting ')' (SyntaxError)
let(:user) { User.new(first_name: 'Joe', last_name: 'Blow') }
^


When I revert to the :key => 'value' syntax, rspec then looks at the user.rb file I'm requiring and says it doesn't know what is going on with the syntax present there, either.



Is there a way I can remedy this?





Cannot compile simple programme that uses libxml++ because glibmmconfig.h not found

After stripping away all of the unnecessary code, this is the barebones version that refuses to compile:



#include <iostream>
#include <libxml++/libxml++.h>

using namespace std;

int main (int argc, char *argv[]) {
cout << "Hello, World!" << endl;
return 0;
}


I'm using an up-to-the-minute version of Fedora 16. Initially, the compiler could not find even libml++/libxml++.h, because Fedora's yum puts these files in /usr/include/libxml++-2.6/libxml++. So I got around that by creating the symlink /usr/include/libxml++ to /usr/include/libxml++-2.6/libxml++. That stopped the compiler from complaining about not finding libxml++.h, but then, in libxml++.h there is the line



#include <ustring.h>


which again the compiler could not find. So once again I created a symlink from /usr/include/glibmm to /usr/include/glibmm-2.4/glibmm, which is where ustring.h actually resides.



Now the compiler has stopped complaining about ustring.h, but the first (actual) line in ustring.h is



#include <glibmmconfig.h>


which the compiler cannot find.



The actual location of glibmmconfig.h is /usr/lib64/glibmm-2.4/include. But I would prefer not to alter ustring.h.



Is there a way out of my problems without constantly having to create symlinks, etc.?



Thanks in advance for your help.



EDIT



I was able to get around my problems with the following compiler options:



`pkg-config --cflags --libs glibmm-2.4 libxml++-2.6`


Thanks to jpalecek for pointing the way, but I had to hunt some more until I was able to get around my problem.



But while these compiler options compile the simple programme above, they fail to compile the tutorial on the libxml++ tutorial page:



#include <iostream>
#include <libxml++/libxml++.h>
#include <string.h>

using namespace std;

int main (int argc, char *argv[]) {
string FilePath = "SampleXMLDocument.xml";
try {
xmlpp::DomParser Parser;
Parser.set_substitute_entities ();
Parser.parse_file (FilePath);
cout << "Successfully parsed XML file" << endl;
} catch (const exception& excp) {
cout << "Exception caught: " << excp.what () << endl;
}
return 0;
} // End main ()


I guess my search continues.





NSMutableDictionary value lookup

What is a good way of looking through a NSMutableDictionary to see if there is a key that corresponds to another variable?



Lets say i have a NSString "test"
and a mutable dictionary that has some values and NSString keys for those values.



What would be a good way of reading through the dictionary values to see if any of its keys are "test".



Would i have to have a for loop to read through dictionary values or is there something already a part of NSDictionary object that will do this that I'm not seeing.





python without wing

Okay, I'm really new with python and in my class the prof assigned a homework where we fix codes without wing. I'm really confused because the prompt asks us to 'open a terminal window by clicking on the icon in the task bar that looks like a terminal screen. After it opens, it will display a prompt. Type the commands:
cd Desktop/cs141/11execution
python hello.py
so i understand what it is asking me to do and i think i opened the terminal window... but it gives me a syntax error. Can someone explain to me how to actually use python (how to open files without using wing.). I'm sorry if this sounds dumb but i'm extremely confused because i can't even open the file to get working on it.
Sorry, this isn't specific... okay so i opened the terminal window and i typed in the command that the homework told me to do and it gave me this:



cd Desktop/cs141/11execution
File "<stdin>", line 1
cd Desktop/cs141/11execution
SyntaxError: invalid token


D: i have no idea what's going on because i'm already having problems :[





Can't use 'rails' command after installing using gem install

I've installed rails using 'gem install rails', but when I try to create a new project, I get the error:
The program 'rails' is currently not installed. You can install it by typing:



sudo apt-get install rails


There were no error messages when I ran 'gem install rails'. How come I cannot run rails commands?





How to make a reusable EditText with clear button?

I want to make a compound control that is a EditText with a clear button. Since the main functionality will be the EditText functionality, I want it to be declarable in layout xmls with all the attributes of an EditText. But, it is actually going to be a LinearLayout with an EditText and an ImageButton in it.



Also, I want it to be used just like an EditText in the code, so I can just drop it in as a replacement.



I have this layout so far:



<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:background="@android:drawable/editbox_background" >
<EditText
android:id="@+id/editText"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_vertical"
android:background="#FFF" />
<ImageButton
android:id="@+id/clear"
android:src="@drawable/clear_text"
android:background="#FFF"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical" />
</LinearLayout>


But I am unsure how to proceed. How do I define a control that extends EditText if I need it to be a LinearLayout in order to use this layout? Or is my only option to draw the x manually in onDraw() and handle clicks myself?





Gnuplot: Black and White contour plot

I have the following gnuplot plot embedded in my Latex document:



\begin{gnuplot}[terminal=epslatex,terminaloptions={color size 14.5cm, 9cm}]
set view map
unset surface

unset key
unset xtics
unset ytics
unset ztics

set contour base
set cntrparam levels discrete 2,4,8,16,32,64,128,256,512
set isosamples 100

splot y**2 + 0.1*x**2 notitle
\end{gnuplot}


The plot is alright. All I want to achive is that the contour lines all have the same style, i.e. line type and the same colour, black if possible.



Thanks for any advices.





Efficient way to search a string in an array of string in C. (Case insensitive)

I am working on a project (implemented in C) where we are required to maintain a list of a features or keywords. The user enters a string. We need to do case insensitive search for this string in the stored array of string. The list currently consists of 100 strings and new strings may be added (5 strings a year or so).



I want to know the best way to store this array and make the search more efficient.



The solution which is currently implemented is something like below:(I have not compiled this code. This is just a code snippet.)



    char **applist={ asdf , adgh, eftg , egty, ...} 
char *user_input; // this string contains user entered string
int id;
switch(user_input[0])
{
case 'a':
case 'A':
switch(user_input[1]
{
case 's':
case 'S':
id=0
break;

case 'd':
case 'D':
id=1
break;
}
break;
case'e':
case'E':
switch(user_input[1])
{
case 'f':
case 'F':
id=2
break;

case 'g':
case 'G':
id=3
break;
}
break;
}
if(stricmp(user_input,applist[id]))
return id;
else
return -1;


In actual code applist is not sorted. As new strings are added to applist I need an efficient way to store this array.



If I store the string sorted alphabetically then every time a new string is added I have to manually find the correct position of the new string. (New Strings are added to applist before compiling the code not at the runtime)



Suggest an efficient way of doing this.



EDIT: My current approach leads to a longer code but its efficient. But this code is not easy to maintain. What I need is a data structure which can do search with same efficiency as this but with smaller code. The datastructure you suggest, should not have additional overhead. The only requirement is efficient searching. And a way to add elements to the data structure at compile time easily. Sorting at run-time is not my requirement as new strings are added at compile time(This is to avoid restrict user from adding any new string to the list).





Java Quick Way to Create an Array with Set of Possibilities

What would be a quick and simple way to create a two-dimensional array with set of possibilities?



For example, if the number is 5, I want the array to be:



{{0,1},{0,2},{0,3},{0,4},{1,2},{1,3},{1,4},{2,3},{2,4},{3,4}}


if the number is 6,



{{0,1},{0,2},{0,3},{0,4},{0,5},{1,2},{1,3},{1,4},{1,5},{2,3},{2,4},{2,5},{3,4},{3,5},{4,5}}


Thanks in advance.





Limiting a draggable element within a container

I have made a div draggable without using the jquery ui library, but I want to make the draggable box, not to leave its container.



Here is my demo



$(document).ready(function() {
var $dragging = null;

$(document.body).on("mousemove", function(e) {
if ($dragging) {
$dragging.offset({
top: e.pageY,
left: e.pageX
});
}
});

$(document.body).on("mousedown", ".box", function (e) {
$dragging = $(e.target);
});

$(document.body).on("mouseup", function (e) {
$dragging = null;
});
});?


How to do this? Please NOTE, I am not using JQUERY UI.





Override Power button just like Home button

Well, i am Doing a stuff in which I want to disable all hard button of the device



Hard button like Power, Home, Volume up, Volume down, Search, Back.



I successfully override almost all buttons Here except Power



so i just want you people to see and please share some idea so that I can away with it



I am getting the long press Power keyevent in onDispatchKeyEvent(), sameway i wanted to catch short click of the same. Morever when pressing power i also tried to stop Screen off by getting the Broadcast of SCREEN_OFF and succeed to receive but not able to handle it.



Thanks.



Till i had created a RecieverScreen which recieves broadcast of Screen on/off



ReceiverScreen.java



public class ReceiverScreen extends BroadcastReceiver {

public static boolean wasScreenOn = true;

@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// do whatever you need to do here
wasScreenOn = false;
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// and do whatever you need to do here
wasScreenOn = true;
}
}
}


DisableHardButton.java



public class DisableHardButton extends Activity {

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.main);
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ReceiverScreen();
registerReceiver(mReceiver, filter);
}

@Override
protected void onPause() {
// when the screen is about to turn off
if (ScreenReceiver.wasScreenOn) {
// this is the case when onPause() is called by the system due to a screen state change
System.out.println("SCREEN TURNED OFF");

} else {
// this is when onPause() is called when the screen state has not changed
}
super.onPause();
}

@Override
protected void onResume() {
// only when screen turns on
if (!ScreenReceiver.wasScreenOn) {
// this is when onResume() is called due to a screen state change
System.out.println("SCREEN TURNED ON");
} else {
// this is when onResume() is called when the screen state has not changed
}
super.onResume();
}
}




Using both @RequestBody and @RequestParam together in spring mvc3

I am using spring-mvc 3.1.0.RELEASE and for some reason, mapping POST with query params and request body does not work.



Here is how my controller method looks:



  @RequestMapping(method = POST, value = "/post-to-me/") 
public void handlePost(
@RequestBody Content content,
@RequestParam("param1") String param1,
@RequestParam("param2") String param2
){
//do stuff
}


However, if I convert all the request params to path params, mapping works. Has anyone run into something similar?



Thanks!



EDIT:
"does not work" == 404 when I try doing, POST /post-to-me?param1=x&param2=y





Using sed to replace all stdout from within .bashrc

I want to conduct a sed operation on all output in my bash shell. Basically I want to put the sed command in .bashrc so it "listens" for certain keywords to do something with them.



For instance I am looking to put something like this in .bashrc:




sed ''/critical/s//$(printf "CRITICAL")/g''




So that anytime the word "critical" pops up, it is changed to "CRITICAL". This might be when I cat a file, am using vi, or am telnetted into another system. What do I need to do to get this to work?





PHP Incrementing a Multi-Dimensional Array

having some issues with getting the output from an array. I've looked around and can't seem to find out why my array isn't assigning an index to each portion of an array. I've looked around and even tried adding a counter variable to the piece of the array but that doesn't seem to create an index. I'm pretty new to PHP so any help that anyone can give me would be appreciated.



foreach($dbh->query('SELECT n_productID, t_productName, t_categoryName FROM v_prodcatintersect') as $row) {
$prodID=$row["n_productID"];
$prodName=$row["t_productName"];
$prodCategor=$row["t_categoryName"];
$products=array(
array(
"prodID" => $prodID,
"prodName" => $prodName,
"prodCategor" => $prodCategor
),
print_r($products);
}
for($i = 0, $size = sizeof($products); $i < $size; ++$i){
echo "The product ID is ".$products[$i]["prodID"];
echo " The product name is ".$products[$i]["prodName"];
echo " Product Category ".$products[$i]["prodCategor"];
}


Right now the output from the array (from the print_r) is "Array ( [0] => Array ( [prodID] => 1 [prodName] => iPhone 4 [prodCategor] => Smartphones ) ) Array ( [0] => Array ( [prodID] => 2 [prodName] => Droid 3 [prodCategor] => Smartphones ) )". And the echo's only print the second item out of two since they both have the same index. Appreciate any help with creating an index here. Thanks.





jquery simple ajax load without loading its wrapper DIV

I have a content (#content) at external file (test.html) to load into another DIV (#result) at index.html:



test.html:



<div id="content>This text should not be loaded with its DIV</div>


jquery:



$('#result').load('test.html #content');


index.html result, unexpected:



<div id="result><div id="content>This text should not be loaded with its DIV</div></div>


index.html result, expected:



<div id="result>This text should not be loaded with its DIV</div>


How do you load only the actual content/ text of the #content without loading its wrapper (#content)?
The reason is to simply avoid unneeded divities which also may conflict with other styled DIVs by mistake.



Any hint is very much appreciated. Thanks





Can i kill console-kit-dae process on ubuntu?

Top Command show 2 process of console-kit-dae, each using 22% of memory.



i would like to know why ? and if i can kill them?



thanks.





Add newly created specific folder to .gitignore in Git

I had a clean working directory and brought in a clone from a Git repo last night.
But now my local server created and contains a stats folder which I want to ignore.



I can't seem to get Git to ignore this folder when I run a git status.



On branch master
Your branch is ahead of 'origin/master' by 1 commit.

Changes to be committed:
(use "git reset HEAD <file>..." to unstage)

new file: app_public/views/pages/privacy.php
new file: app_public/views/pages/terms.php
new file: public_html/stats/ctry_usage_200908.png
new file: public_html/stats/daily_usage_200908.png
new file: public_html/stats/dns_cache.db
new file: public_html/stats/hourly_usage_200908.png
new file: public_html/stats/index.html
new file: public_html/stats/usage.png
new file: public_html/stats/usage_200908.html
new file: public_html/stats/webalizer.current
new file: public_html/stats/webalizer.hist

Changed but not updated:
modified: .gitignore


I added in my .gitignore a few different lines but it still trying to add them:



public_html/stats
public_html/stats/**
public_html/stats/**/*
public_html/stats/*