Friday, 27 September 2013

Am I allowing 3 guesses or 2?

Am I allowing 3 guesses or 2?

I am learning Python on Codecademy, and I am supposed to give the user 3
guesses before showing "you lose". I think my code allows 3 entries, but
the website shows "Oops, try again! Did you allow the user 3 guesses, or
did you incorrectly detect a correct guess?" unless the user guesses
correctly within 3 trials. Can someone tell me what's wrong?
from random import randrange
random_number = randrange(1, 10)
count = 0
# Start your game!
guess= int(raw_input("Please type your number here:"))
while count < 2:
if guess==random_number:
print "You win!"
break
else:
guess=int(raw_input("Please guess again:"))
count+=1
else:
print "You lose!"
print random_number

Selecting elements of a page using jQuery

Selecting elements of a page using jQuery

I'm a total jQuery noob. A colleague showed me how to select a form field
on a website using jQuery and I was blown away what it can do. So, instead
of reading the documentation from start to finish, I decided to fiddle
with it and see how far I come. I wanted to see how scripting a website
would work. I chose Trello as test subject.
I'm inside a Board, and now I want to click "Add a card" on a particular
List. I can't figure out the exact jQuery command. This is how a card
looks like. At the beginning you can see how the general list of cards
begins:
<div class="list-area js-list-sortable js-no-higher-edits clearfix
ui-sortable" style="width: 2606px;">
<div class="list" style="width: 220px;">
<div class="list-header clearfix ed">
<div class="list-title non-empty clearfix editable" attr="name">
<h2 class="hide-on-edit current">
Monday
</h2>
<p class="num-cards"></p>
<div class="edit edit-heavy clearfix">
<textarea type="text" class="field
single-line"></textarea>
</div><a href="#" class="icon-sm icon-menu dark-hover
js-open-list-menu"></a>
</div>
</div>
<div class="list-card-area">
<div class="list-gradient-top"></div>
<div class="list-gradient-bottom"></div>
<div class="list-cards fancy-scrollbar clearfix js-sortable
ui-sortable" style="max-height: 378px;"></div>
</div><a class="open-card-composer js-open-card-composer"
href="#">Add a card…</a>
</div>
What I have is this:
$('.js-open-card-composer').parent('.list').find('.list-header').first('.list-title').first(".hide-on-edit:contains('Monday')");
This returns the exact card I'm looking for (actually just the title div
of it), but when I add .click() it doesn't work. Is my approach right
though?
I'm sorry if this questions has been asked already. In this case, it would
be nice to get a link to that question. I couldn't find it.
Thanks for help and suggestions.

Share a string between voids in C#

Share a string between voids in C#

Does anybody knows a way to share a string between voids in C#.
This is the piece of code where I need the get my string:
private void timer1_Tick(object sender, EventArgs e)
{
// The screenshot will be stored in this bitmap.
Bitmap capture = new Bitmap(screenBounds.Width, screenBounds.Height);
// The code below takes the screenshot and
// saves it in "capture" bitmap.
g = Graphics.FromImage(capture);
g.CopyFromScreen(Point.Empty, Point.Empty, screenBounds);
// This code assigns the screenshot
// to the Picturebox so that we can view it
pictureBox1.Image = capture;
}
In here in need the get the 'capture' string:
Bitmap capture = new Bitmap(screenBounds.Width, screenBounds.Height);



And place 'capture' in this part:
private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
{
if (paint)
{
using (Graphics g = Graphics.FromImage(!!!Put Capture in
Here!!!))
{
color = new SolidBrush(Color.Black);
g.FillEllipse(color, e.X, e.Y, 5, 5);
}
}
}
In here:
using (Graphics g = Graphics.FromImage(!!!Put Capture in Here!!!))

I hope someone can help
PS: If you don't understand the hole thing, I'm 14 and from the
netherlands, So i'm not the best English writer :-).

Display:table expands the height of the div. Solutions?

Display:table expands the height of the div. Solutions?

I have this html sequence that displays 2 bars. Because inside the first
div I display an inline list, I want to use display:table because it looks
nicer in this way. The problem is that it extends the div, making it
bigger with 20px (and moves the other div lower).
<div class="top-bar></div>
<div class="tail-bar></div>
.top-bar{
width: 520px;
height: 50px;
dispaly: table;
background-color: #FFFFFF;
}
EDIT: I added a JSFiddle http://jsfiddle.net/eCYUT/2/
It is the version without display:table tag

Can't find how to define if id exist in $(this)

Can't find how to define if id exist in $(this)

In many fieldset, with a next button i try to find if there is "#required"
id input, and then, if it's empty, return false (stay in this fieldset)
else go on actions ...
if ($(this).attr('required').length == 0) {
alert ('oui');
if (!$(this).attr('required'))
return false;
}
else
alert ('non');
But $(this).attr('required').length is undefined because no id found.
need help, thanks for all.

Thursday, 26 September 2013

Dymanic Query is not working with cursor in SqlServer 2008 Stored Procedure

Dymanic Query is not working with cursor in SqlServer 2008 Stored Procedure

I am building a stored procedure in Sql Server 2008. Stored Procedure has
two arguments which are the column names of a table. In stored procedure I
used dynamic query for fetching data of these two columns with the help of
Cursor.
Code:
Create PROCEDURE TestSP
(
@firstAttribute nvarchar(max),
@secondAttribute nvarchar(max)
)
AS
DECLARE @x FLOAT
DECLARE @y INT
DECLARE @query nvarchar(max)
DECLARE @cursor_query nvarchar(max)
DECLARE @result_Cursor as cursor
BEGIN
SET @query = 'Select '+ @firstAttribute+','+@secondAttribute+' from
TBL_TEST_DATA_NEW'
SET @cursor_query =' set @cursor = cursor for ' + @query +' open @cursor;'
PRINT 'CURSOR_QUERY'+@cursor_query
exec sys.sp_executesql
@cursor_query
,N'@cursor cursor output'
,@result_Cursor output
FETCH NEXT FROM result_Cursor INTO @x, @y
But when I am executing this SP it is giving me following error
Msg 16916, Level 16, State 1, Procedure TestSP, Line 33
A cursor with the name 'result_Cursor' does not exist.
Execute Command :
Exec TestSP "Column_1","Column_2"
Can someone tell me why I am getting this error
Please Help..
Thanks

Thursday, 19 September 2013

ZF2 How do i hide message error after wrong routes

ZF2 How do i hide message error after wrong routes

I want to return a 404 error after a wrong route instead of de php Fatal
Error long message.
Fatal error: Uncaught exception 'Zend\View\Exception\RuntimeException'
with message 'No RouteMatch instance provided' i
How can i do it?

Adding key value to RavenDB document based on another document's values (For all documents in large collection)

Adding key value to RavenDB document based on another document's values
(For all documents in large collection)

I am new to RavenDB and could really use some help.
I have a collection of ~20M documents, and I need to add a key to each
document. The challenge is that the value of the key needs to be derived
from another document.
For instance, given the following document:
{
"Name" : "001A"
"Date" : "09-09-2013T00:00:00.0000000"
"Related" : [
"002B",
"003B"
]
}
The goal is to add a key that holds the dates for the related documents,
i.e. 002B and 003B, by looking up the related documents in the collection
and returning their date. E.g.:
{
"Name" : "001A"
"Date" : "09-09-2013T00:00:00.0000000"
"Related" : [
"002B",
"003B"
]
"RelatedDates" : [
"08-10-2013T00:00:00.0000000",
"08-15-2013T00:00:00.0000000"
]
}
I realize that I'm trying to treat the collection somewhat like a
relational database, but this is the form that my data is in to begin
with. I would prefer not to put everything into a relational dataset first
in order to structure the data for RavenDB.
I first tried doing this on the client side, by paging through the
collection and updating the records. However, I quickly reach the maximum
number of request for the session.
I then tried patching on the server side with JavaScript, but I'm not sure
if this is possible.
At this point I would greatly appreciate some strategic guidance on the
right way to approach this problem, as well as, more tactical guidance on
how to implement it.

Function with array returning 0 Visual Basic

Function with array returning 0 Visual Basic

I'm quite new at using arrays and functions in Visual Basic and I cant
seem to figure this out, my problem is that whenever I call the function
"Fibo" it returns 0 no matter the value of "n". I'm sure the error is
pretty basic...
Any pointer would be really appreciated!
Public Function fibo(n As Integer) As Integer
Dim arrayFib(n + 1) As Integer 'declare array to hold fibonacci
arrayFib(0) = 0 'idem
arrayFib(1) = 1 'declare start value
Dim i As Integer = 2 'start position
While i <= n
arrayFib(i) = arrayFib(i - 1) + arrayFib(i - 2)
i = 1 + i
Return arrayFib(i)

JavaScript: Check to see if object exists

JavaScript: Check to see if object exists

I have a function to return if a variable/object is set or not:
function isset() {
var a = arguments, l = a.length;
if (l === 0) { console.log("Error: isset() is empty"); }
for (var i=0; i<l; i++) {
try {
if (typeof a[i] === "object") {
var j=0;
for (var obj in a[i]) { j++; }
if (j>0) { return true; }
else { return false; }
}
else if (a[i] === undefined || a[i] === null) { return false; }
}
catch(e) {
if (e.name === "ReferenceError") { return false; }
}
}
return true;
}
For example, this works:
var foo;
isset(foo); // Returns false
foo = "bar";
isset(foo); // Returns true
foo = {};
isset(foo); // Returns false
isset(foo.bar); // Returns false
foo = { bar: "test" };
isset(foo); // Returns true
isset(foo.bar); // Returns true
Here is the problem... if foo is never set to begin with, this happens:
// foo has not been defined yet
isset(foo); // Returns "ReferenceError: foo is not defined"
I thought I could use try/catch/finally to return false if error.name ===
"ReferenceError" but it isn't working. Where am I going wrong?

How to click on element using other related element?

How to click on element using other related element?

<ul class="ui-treenode-children">
<li aria-selected="true" aria-checked="true" aria-expanded="true"
id="frmScrForm:multiLevelTree:0_0" data-rowkey="0_0" class="ui-treenode
ui-treenode-parent folder" role="treeitem">
<span class="ui-treenode-content ui-tree-selectable"
aria-expanded="false" aria-selected="false" aria-checked="false">
<span class="ui-tree-toggler ui-icon ui-icon-triangle-1-s"></span>
<div class="ui-chkbox ui-widget tree_node_folder_expand">
<div class="ui-chkbox-box ui-widget ui-corner-all
ui-state-default">
<span class="ui-chkbox-icon ui-icon ui-icon-check"></span>
</div>
</div>
<span class="ui-treenode-icon ui-icon
tree_node_folder_collaps"></span>
<span class="ui-treenode-label ui-corner-all">
<span class="tree_node_folder_text" style="background-color:
transparent;">Company</span>
</span>
</span>
<ul class="ui-treenode-children" style="">
</ul>
</li>
</ul>
I am using selenium (selenium IDE) to test a tree, I want to click on the
check box according to the text (or value) next to it.
This is the HTML code for one node in the tree, how can I use selenium to
click at check box next to the text (company)??

Is there an Excel web viewer library/api?

Is there an Excel web viewer library/api?

I've researched this but keep coming across ambiguous info whether or not
it will suit my task. I'm sure there must be a solution out there. Don't
want to end up reinventing the wheel.
My task I have an Excel document with either type xls or xlsx hosted on
the server. I want to serve that Excel document up in the user's browser.
Ideally this should be a c# solution but if there is a better library
available using something like PHP, I'd consider switching.
Thought it might be possible to automate Google Docs into serving up the
document but alas I cannot find anywhere that says it can do this.
There are plenty of online excel viewers which water down my Google
searches, how are they doing it?
Any pointers in the right direction would be appreciated.

Jquery mobile popup dialog menu scroll up when Keyboard is visible in phonegap

Jquery mobile popup dialog menu scroll up when Keyboard is visible in
phonegap

m creating an app in which i want a popup dialog box with some text field
to be entered so i took an example from the jquery mobile site and just
inserted 4 input text to insert landline no with country and area
code.When i run it on the emulator is opens an popup dialog but when user
tyr to insert something on the text box it scrolls above so i used this
code in the script to disable page scroll as given below after this the
problem is user is able to insert data on only 2 text box because rest of
the text box are hidden beside the keyboard. What i want is page should
not scroll on its own when user keyboard is open and user should be able
to scroll the popup dialod to insert the data. here is the code that i had
return:
<a href="#popupDialog" data-rel="popup" data-position-to="window"
data-role="button" data-inline="true" data-transition="pop"
data-icon="delete" data-theme="b">Delete page...</a>
<div data-role="popup" id="popupDialog" data-overlay-theme="a"
data-theme="c" data-dismissible="false"
style="max-width:400px;" class="ui-corner-all" >
<div data-role="header" data-theme="a" class="ui-corner-top">
<h1>Delete Page?</h1>
</div>
<div data-role="content" data-theme="d"
class="ui-corner-bottom ui-content">
<h3 class="ui-title">Are you sure you want to delete
this page?</h3>
<p>This action cannot be undone.</p>
<input type='number' id='area code' placeholder='Area
code'>
<input type='number' id='country code'
placeholder='Country code'>
<input type='number' id='numder' placeholder='Number'>
<input type='button' id='open' data-rel='back'
value='OK'>
</div>
</div>
here is the javascript to disable the page scroll:
$(document).on('popupafteropen', '[data-role="popup"]' ,function(
event, ui ) {
$('body').css('overflow','hidden');
}).on('popupafterclose', '[data-role="popup"]' ,function(
event, ui ) {
$('body').css('overflow','auto');
});
Thanks in advance

Which Context to use with MediaPlayer.create() in android?

Which Context to use with MediaPlayer.create() in android?

Which context i should use with MediaPlayer.create() ? I am using
Activity.this with all my MediaPlayer objects.But i think it is giving me
null pointer exception. Can context be a reason for force close in android
or anything else ?
Here "com.bhavin.panara.kbc" is package name. And 108th line is
mediaplayer.start().
Here is my log cat report.
java.lang.RuntimeException: Unable to start activity
ComponentInfo{com.bhavin.panara.kbc/com.bhavin.panara.kbc.PlayScreen}:
java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1999)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2026)
at android.app.ActivityThread.access$600(ActivityThread.java:127)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1174)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4506)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:809)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:576)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NullPointerException
at com.bhavin.panara.kbc.PlayScreen.onCreate(PlayScreen.java:108)
at android.app.Activity.performCreate(Activity.java:4479)
at
android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1050)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1963)
... 11 more

Wednesday, 18 September 2013

Simple print name program in C

Simple print name program in C

Could someone please write me a simple program that asks user to enter
name as a string and then prints something like "Hello (name goes here),
how are you?"
I'm just starting with C and would like a simple reference. Thanks!

Publishing apps on the app store

Publishing apps on the app store

Just a quick question regarding publishing apps. If the app is a mini game
based off an anime can you still publish it if its free? I am making a
small mini game based of of roosterteeths RWBY Red trailer if I were to
publish this would it be rejected as being based off of something owned by
someone else?

Fire Gridview RowUpdating Event without an Update/Save Button

Fire Gridview RowUpdating Event without an Update/Save Button

I have a gridview and I would like to Autosave the fields without using a
save or an update button. How do I fire the RowUpdating Event without
using a button? Or is there a better way of implementing this? Thanks for
your help.
<div id="form_BCFLP" class="fm_Medium5" runat="server"
visible="true">
<asp:GridView ID="GV_BCFLP" runat="server"
AutoGenerateColumns="False" DataKeyNames="Id,Name"
GridLines="none" Visible="true"
OnRowUpdating="GV_BCFLP_RowUpdating" EnableViewState="true"
AutoPostback="true">
<Columns>
<asp:BoundField DataField="Name"
ItemStyle-HorizontalAlign="left"
ItemStyle-CssClass="lblSize_LargeBlack"></asp:BoundField>
<asp:TemplateField ItemStyle-HorizontalAlign="left">
<ItemTemplate>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
</div>
protected void GV_BCFLP_RowUpdating(object sender, GridViewUpdateEventArgs e)
{
//I call my webservice here to update data
}

function triggers on click

function triggers on click

How do I trigger this function:
<script>
function change(x) {
var target = document.getElementById("target");
if (y == "imgA") {target.className = "cast1";}
else if (y == "imgB") {target.className = "cast2";}
else if (y == "imgC") {target.className = "cast3";}
else if (y == "imgD") {target.className = "cast4";}
else {target.className = "chart";}
}
function changeReset() {
var target = document.getElementById("target");
target.className = "chart";
}
</script>
To only happen when this button is pressed?
<div class='nfooter' style="position:float;"><a id="c_question"
href="#"><img src="../name_footer/_name.png" /></a></div>

How to put n intent on a gridview to lauch another activity in android?

How to put n intent on a gridview to lauch another activity in android?

I doing a grid view for my android layout but I don't know how to put an
intent on the grid view. is there any way where I can put an intent to
launch another activity? I been trying for few days already but i cant
seem to figure out how to do it.
public class PregnancyStages extends Activity implements
OnItemClickListener {
private GridView photoGrid;
private int mPhotoSize, mPhotoSpacing;
private ImageAdapter imageAdapter;
// Some items to add to the GRID
private static final String[] CONTENT = new String[] { "Pregnancy Stages",
"Complications", "Diet And Fitness", "Myths And Facts",
"FAQ's", "Helplines" };
private static final int[] ICONS = new int[] { R.drawable.baby1,
R.drawable.baby2,
R.drawable.baby3, R.drawable.baby4, R.drawable.baby5,
R.drawable.baby6 };
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// get the photo size and spacing
mPhotoSize = getResources().getDimensionPixelSize(R.dimen.photo_size);
mPhotoSpacing =
getResources().getDimensionPixelSize(R.dimen.photo_spacing);
// initialize image adapter
imageAdapter = new ImageAdapter();
photoGrid = (GridView) findViewById(R.id.albumGrid);
// set image adapter to the GridView
photoGrid.setAdapter(imageAdapter);
// get the view tree observer of the grid and set the height and
numcols dynamically
photoGrid.getViewTreeObserver().addOnGlobalLayoutListener(new
ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
if (imageAdapter.getNumColumns() == 0) {
final int numColumns = (int)
Math.floor(photoGrid.getWidth() / (mPhotoSize +
mPhotoSpacing));
if (numColumns > 0) {
final int columnWidth = (photoGrid.getWidth() /
numColumns) - mPhotoSpacing;
imageAdapter.setNumColumns(numColumns);
imageAdapter.setItemHeight(columnWidth);
}
}
}
});
}
// ///////// ImageAdapter class /////////////////
public class ImageAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private int mItemHeight = 0;
private int mNumColumns = 0;
private RelativeLayout.LayoutParams mImageViewLayoutParams;
public ImageAdapter() {
mInflater = (LayoutInflater)
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mImageViewLayoutParams = new
RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT);
}
public int getCount() {
return CONTENT.length;
}
// set numcols
public void setNumColumns(int numColumns) {
mNumColumns = numColumns;
}
public int getNumColumns() {
return mNumColumns;
}
// set photo item height
public void setItemHeight(int height) {
if (height == mItemHeight) {
return;
}
mItemHeight = height;
mImageViewLayoutParams = new
RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,
mItemHeight);
notifyDataSetChanged();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
if (view == null)
view = mInflater.inflate(R.layout.photo_item, null);
ImageView cover = (ImageView) view.findViewById(R.id.cover);
TextView title = (TextView) view.findViewById(R.id.title);
cover.setLayoutParams(mImageViewLayoutParams);
// Check the height matches our calculated column width
if (cover.getLayoutParams().height != mItemHeight) {
cover.setLayoutParams(mImageViewLayoutParams);
}
cover.setImageResource(ICONS[position % ICONS.length]);
title.setText(CONTENT[position % CONTENT.length]);
return view;
}
}
@Override
public void onItemClick(AdapterView<?> parent, View v, int position, long
id) {
// TODO Auto-generated method stub
Intent myIntent = null;
if(position == 0){
myIntent = new Intent(v.getContext(), PregnancyStagesGrid1.class);
}
if(position == 1){
myIntent = new Intent(v.getContext(), PregnancyStagesGrid2.class);
}
startActivity(myIntent);
}}
anyone know where can i put this source code?
GridView gridview = (GridView) findViewById (R.id.albumGrid);
gridview.setAdapter (new ImageAdapter());
gridview.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View v, int
position, long id) {
// TODO Auto-generated method stub
Intent myIntent = null;
if(position == 0){
myIntent = new Intent(v.getContext(),
PregnancyStagesGrid1.class);
}
if(position == 1){
myIntent = new Intent(v.getContext(),
PregnancyStagesGrid2.class);
}
startActivity(myIntent);
}
});
}

How do I remove a GIT remote that has a "blank" name?

How do I remove a GIT remote that has a "blank" name?

Somehow during my SSH configuration (for GitHub), Tortoise Git has created
a remote configuration with a "blank" name.
Neither Tortoise nor Git command line will allow me to remove it because
Git requires a name to be passed for the remote configuration.
Has anyone run into this before and what is the solution?

Error in Python plugin

Error in Python plugin

I'm following a tutorial for developing a plugin for gqis, but I'm stuck
in a error, when trying to insert a text in a textbox window. The code is
as demonstrated here
Class vector_selectbypointdialog.py:
from PyQt4 import QtCore, QtGui
from ui_vector_selectbypoint import Ui_vector_selectbypoint
# create the dialog for zoom to point
class vector_selectbypointDialog(QtGui.QDialog):
def __init__(self):
QtGui.QDialog.__init__(self)
# Set up the user interface from Designer.
self.ui = Ui_vector_selectbypoint()
self.ui.setupUi(self)
def setTextBrowser(self, output):
self.ui.txtFeedback.setText(output)
def clearTextBrowser(self):
self.ui.txtFeedback.clear()
Class vector_selectbypoint.py:
under init create the object like this:
# create our GUI dialog
self.dlg = vector_selectbypointDialog()
And the method that handles to insert the text:
handleMouseDown(self, point, button):
self.dlg.clearTextBrowser()
self.dlg.setTextBrowser( str(point.x()) + " , " +str(point.y()) )
The error is:
handleMouseDown self.dlg.clearTextBrowser() AttributeError:
'vector_selectbypointdialog' object has no attribute 'clearTextBrowser'

How get class description from bytecode?

How get class description from bytecode?

Get description not load class, I want some library that can read '.class'
file and return some object, that hold method names and string parameters
for it. Some library that can work as Intellij Idea when it does not load
the source it simply list public methods with full path parameters to it.
Is such tool avaible for free?

JavaFx: how to make Script files with extention .fx

JavaFx: how to make Script files with extention .fx

I am new to Java Fx and I am using netbeans7.3.1 for Java FX .. here there
are .java files and .fxml files that can be created
I was wondering where would we right fx script.. so after searching i came
to knew that JavaFX script can be written in .fx file can anyone tell me
how to make these files as in netbeans i have not founded any way to make
one
can anyone tell how to make these files

Tuesday, 17 September 2013

Android apps always part of the OS source?

Android apps always part of the OS source?

I am trying to customize the Email app that's at packages/apps/Email in
the android source. However, I noticed that it has a dependency on the
OS/SDK that it's part of and is not really separate.
For ex., if I pick up the Email app from the latest master, it will run
only on 4.3 android devices, and not on 4.0.x. The app uses certain
features of device admin that are there only in 4.3 and is not written to
work on the previous versions.
And if I take the app from 4.0.x android source then I am missing the
latest and the greatest of the Email app that's in master.
Is there a reason why the apps are not maintained independently of the OS,
and built to be backward compatible?
Thanks.

C++ passing an array of classes

C++ passing an array of classes

Can anybody help me with the syntax of passing an array of classes to
another class. The syntax of passing an array of classes to another class
has got me beaten. class line tries to be initialised by an array of
points, but the prototype does not match.
#include <iostream>
using namespace std;
class point {
public:
point() {}
point(int x, int y) : X(x), Y(y) {}
void setXY(int x, int y) { X = x; Y = y; }
int getX() { return X; }
int getY() { return Y; }
private:
int X, Y;
};
class line {
public:
line(point *points, int); // Problem line.
private:
point *coords;
int numpoints;
};
int main() {
point points[3];
points[0].setXY(3, 5);
points[1].setXY(7, 9);
points[2].setXY(1, 6);
line l(points, 3); // Problem line.
return 0;
}
Error message: cygdrive/c/Tmp/cc4mAXRG.o:a.cpp:(.text+0xa7): undefined
reference to `line::line(point*, int)'

Properly passing the transaction variables of Succesful PAYPAL back to site (without clicking the Return to site link)

Properly passing the transaction variables of Succesful PAYPAL back to
site (without clicking the Return to site link)

I've been searching for an answer and the IPN transaction variables are ok
on PayPal side however the transaction variables themselves do not post
back to my site.
<form method="post" id="Form1">
<input type="hidden" name="cmd" value="_xclick">
<input type="hidden" name="business" value="rxx.xxx@xxxx.com">
<input type="hidden" name="item_name" value="Auto Return Check">
<input type="hidden" name="item_number" value="1234">
<input type="hidden" name="amount" value=".64">
<input type="hidden" name="no_shipping" value="1">
<input type="hidden" name="rm" value="2">
<input type="hidden" name="showHostedThankyouPage" value="false">
<input type='hidden' name='notify_url'
value='http://xxxuser.somee.com/pdthandler.aspx' />
And my pdthandler.aspx which acts like notify_url (because IPN history are
all succesful/verified) looks like this (which I copied elsewhere)



string authToken, txToken, query, strResponse;
authToken = WebConfigurationManager.AppSettings["PDTToken"];
//read in txn token from querystring
txToken = Request.QueryString.Get("tx");
query = string.Format("cmd=_notify-synch&tx={0}&at={1}",
txToken, authToken);
// Create the request back
string url = WebConfigurationManager.AppSettings["PayPalSubmitUrl"];
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
// Set values for the request back
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = query.Length;
// Write the request back IPN strings
StreamWriter stOut = new StreamWriter(req.GetRequestStream(),
System.Text.Encoding.ASCII);
stOut.Write(query);
stOut.Close();
// Do the request to PayPal and get the response
StreamReader stIn = new StreamReader(req.GetResponse().GetResponseStream());
strResponse = stIn.ReadToEnd();
stIn.Close();
// sanity check
Label2.Text = strResponse;
char fslash = (char) 47;
if (strResponse.StartsWith("SUCCESS"))
{
if ((String.IsNullOrEmpty(txToken)) || txToken == "")
txToken = "success";
str_ = "?PayPalTransactionID=" + txToken + "&OrderID=" +
HttpContext.Current.Session["OrderID"] + "";
str_ = "http://returntomysite.com/Heresyourorder.aspx" + str_;
//I've tried redirect does not work as well :'(
//Response.Redirect(str_);
str_1 = "<script src=\"http://code.jquery.com/jquery-1.9.0.js\"><" +
fslash + "script>";
str_1 += "<script>" +
"$(document).ready(function () { " +
" var url = '"+str_+"'; " +
" $(location).attr('href', url); " +
" }); " +
"<" + fslash + "script>";
//Response.Write("<" + Convert.ToChar(2F) + "script>");
Response.Write(str_1);
}
else
{
Label1.Text = "Oooops, something went wrong...";
}



Now there's no problem with PayPal the IPN history seems ok but the
problem is either one of the redirects below does not take me back to my
site.
I've tried auto-return URL and that only works with Paypal account not
credit card payments.
And for everyone's reference I tried
4. http://forums.asp.net/t/1764224.aspx
5. https://github.com/paypal/pdt-code-samples/blob/master/PDT-aspnet.txt
6.
https://www.paypal-community.com/t5/How-to-use-PayPal-Archive/return-the-transaction-id-back-to-my-website/td-p/34542
How it works: * If the buyer pays with a PayPal account, they are
automatically taken back to the site.
If the buyer pays with the Credit Card Option, they are taken to the
receipt page where PayPal gives them the chance to print out a receipt.
This is a legal requirement. After that, the buyer must click on the
"Return to Merchant" link in order to return to the site.
Any help and I will be grateful I think it has been weeks that I can't
solve this. Thank you very much. God bless all

Javascript string match on static string with special characters

Javascript string match on static string with special characters

I am performing search on html document using javascript. For that I am
using javascript's match function. Below line is to return all
searchString matchings.
var searchResults = document.body.innerText.match(RegExp(searchString,'gi'));
The problem is, if the searhString contains special characters, i.e, (, &,
<, etc, it's not working.
Example string "hello("
Please help me.

Undefined index error is thrown although the array clearly has an index

Undefined index error is thrown although the array clearly has an index

I am getting an undefined index error although that I am certain that my
array has values any idea why ?
PHP:
$categories = array();
foreach ($arr as $h) {
$categories[] = trim($h['category']);
}
$uniquecategories = array_unique($categories);
sort($uniquecategories);
print_r ($uniquecategories);
$smarty->assign('uniquecategories',$uniquecategories);
$list['items']=$smarty->fetch('../templates/popupMyItems.tpl',$h);
print_r ($list['items']);
OUTPUT OF print_r ($uniquecategories);
Array ( [0] => CAT1 [1] => CAT2 [2] => CAT3 [3] => CAT4 [4] => CATOTHER
[5] => Everything Else
TPL:
{foreach
from=$uniquecategories item=category name=cat}
{if $smarty.foreach.cat.first} {include
file="../templates/list-myItems.tpl"
category="{$category|replace:' ':''}" active="true"}
{else} {include
file="list-myItems.tpl" category="{$category|replace:' ':''}"
active="false"} {/if}
{/foreach}
ERROR THROWN:
<b>Notice</b>: Undefined index: uniquecategories in <b>C:\Program Files
(x86)\Apache Software
Foundation\Apache2.2\htdocs\ex\main\actions\templates_c\07c3452c9173e47b89ab427877861e26b839928c.file.popupMyItems.tpl.php</b>
on line <b>40</b><br />
<br />
NOTE: I shouldn't have to pass $h on the smarty->fetch
$list['items']=$smarty->fetch('../templates/popupMyItems.tpl',$h); but if
I dont pass a var the whole think breaks.
So If I do
$list['items']=$smarty->fetch('../templates/popupMyItems.tpl');
error</b>: Uncaught exception 'SmartyException' with message 'Unable to
load template file 'list-myItems.tpl' in '../templates/popupMyItems.tpl''
in C:\Program Files (x86)\Apache Software
Foundation\Apache2.2\htdocs\ex\libs\sysplugins\smarty_internal_templatebase.php:127
Stack trace: #0 C:\Program Files (x86)\Apache Software
Foundation\Apache2.2\htdocs\ex\libs\sysplugins\smarty_internal_template.php(286):
Smarty_Internal_TemplateBase-&gt;fetch(NULL, NULL, NULL, NULL, false,
false, true) #1 C:\Program Files (x86)\Apache Software
Foundation\Apache2.2\htdocs\ex\main\actions\templates_c

Newbie really needs help w/ creating database application for the first time [on hold]

Newbie really needs help w/ creating database application for the first
time [on hold]

I work as a coop student and I need some serious help so I sincerely
appreciate everyone's input.
Basically my manager has told me to create an application which takes text
files, processes them and creates a report which the user can change
tolerances on what columns or fields they want to view. For example, if
10000 files (each file represents company/client audit info) are input
into the application for 1 year, the user should be able to filter and
compare files from separte months based on column headings in the files
such as "% population" and "field".
Background info on why this app needs to be created: 1000s of files
containing client audit info is fed into our servers daily. These files
contain several columns in regards to client financial info. Someone needs
to go through each of these files and just check if there is any
irregularities in the data. An example of the irregularities could include
info in a column containing number of docs to go from 100 000 docs in 1
year to 10 docs the next.
The problem is that no one has the time to sit down and check
irregularities in 1000 files. Thus, it would be great if there was an
application which goes through each file, reports any irregularities AND
have a good user interface where the auditor can compare stats for files
based on filters such as column headings and monthly.
I'm new to database programming so I have the following questions: 1) What
language should I use to make this app? We have access to XML, SQL, VB,
Visual Studio **2) Any General Tips for making this app? 3) Did anyone do
something similar to this before? 4) General logic behind this
application? 5) Flowchart help 6) Any link to helpful resources for an app
of this context**
Thanks!!

Sunday, 15 September 2013

Runtime of SubArray equalling a sum

Runtime of SubArray equalling a sum

Recently I came across this C code to find the integers in an array
equalling a sum.
int subArraySum(int arr[], int n, int sum)
{
/* Initialize curr_sum as value of first element
and starting point as 0 */
int curr_sum = arr[0], start = 0, i;
/* Add elements one by one to curr_sum and if the curr_sum exceeds the
sum, then remove starting element */
for (i = 1; i <= n; i++)
{
// If curr_sum exceeds the sum, then remove the starting elements
while (curr_sum > sum && start < i-1)
{
curr_sum = curr_sum - arr[start];
start++;
}
// If curr_sum becomes equal to sum, then return true
if (curr_sum == sum)
{
printf ("Sum found between indexes %d and %d", start, i-1);
return 1;
}
// Add this element to curr_sum
if (i < n)
curr_sum = curr_sum + arr[i];
}
// If we reach here, then no subarray
printf("No subarray found");
return 0;
}
My questions the run time of this algorithm is given as O(n) which can be
proved by counting the number of operations performed on every element of
arr[] in worst case. As far I can see it looks like a O(n^2) algorithm.
May be I missed to learn something but can anybody explain how this is
O(n), if at all this is O(n).

Nitrous.io for Mac does not sync .git?

Nitrous.io for Mac does not sync .git?

I am trying out Nitrous.io -- it is a very nice tool. I am also using
Nitrous' Mac application which syncs box content to a local directory --
except I have noticed that it doesn't sync the .git directory. I assume
this is intentional(?). Is there a list someplace that describes what is
and what is not synced?

Why can't we pass strings as template arguments? [on hold]

Why can't we pass strings as template arguments? [on hold]

I know we can define templates using constants. For instance:
template<int N>
struct FixedArray {
double values[N];
int size() { return N; } // Could be static
};
int main(int, char**) {
FixedArray<10> arr;
arr.values[0] = 3.14;
cout << "first element=" << arr.values[0] << endl;
cout << "size=" << arr.size() << endl;
return 0;
}
This specific example lets us define an array with a constant size.
But why can't we pass strings as template arguments in C++?
The following slide is suppose to explain it but I'm not getting where the
problem is.
If someone can point it out to me and explain it I'd appreciate it. Thanks

Using $_GET with Jquery

Using $_GET with Jquery

I currently have the following code on my website:
$(document).ready(function() {
$("#contact").on("click", function(e)
{
e.preventDefault();
$("#contactform").toggle('fast');
});
});
I would like to have an if(isset($_GET['email')); trigger this function as
well, so have it open on page load if the $_GET variable is set.
I'm rather new with Jquery and not sure if this is possible, I also have
another somewhat related question, I'm not sure if I should make a new
question for this as I'm fairly new to stackoverflow as well, but here it
is.
Say I have two of these:
$(document).ready(function() {
$("#contact").on("click", function(e)
{
e.preventDefault();
$("#contactform").toggle('fast');
});
});
$(document).ready(function() {
$("#archivestop").on("click", function(e)
{
e.preventDefault();
$("#archives").toggle('fast');
});
});
I want one to close if the other one is opened, how would I go about this?
Thanks!

DBCP Multi-threaded connection pool is slower than single-threaded

DBCP Multi-threaded connection pool is slower than single-threaded

For some reason, even when using BoneCP and other libraries, the
multi-threaded benchmark is running slower than the single threaded one.
I assumed that, because there were more connections, the multi-threaded
version will have a lot shorter duration on it however the code (below)
seems to say otherwise.
I am using the DBCP library (I've also tried BoneCP, same result) with the
MySQL Connector/J driver.
Does this driver not support multi-threaded connections or am I doing this
wrong?
You can view the code that I have tested here.

Find total no of items in a cell?

Find total no of items in a cell?

How can i find out total no.of items in a particular cell ?
a table like
eno ename
1 hari,giri,sathish
2 naresh,suresh
3 sathish
i want out put like this
eno ename
1 3
2 2
3 1
how can it achieve?

How to fetch specific number of lines from webpage using cURL using C

How to fetch specific number of lines from webpage using cURL using C

I am a newbie in cURL and trying to implement some application, which
could allow user to fetch specific data from an HTML page (dynamic) and
save it to .txt
Application is c/c++ based and so far i am able to fetch the whole contant
of HTML page.
This is the code i am refering:-
#include "stdafx.h"
#pragma comment(lib, "curllib_static.lib")
#include "curl/curl.h"
#pragma comment(lib, "wldap32.lib")
#pragma comment(lib, "ws2_32.lib")
#pragma comment(lib, "winmm.lib")
#pragma comment(lib, "ssleay32.lib")
#pragma comment(lib, "openldap.lib")
#pragma comment(lib, "libeay32.lib")
void get_page(const char* url, const char* file_name)
{
CURL* easyhandle = curl_easy_init();
// time = 100;
curl_easy_setopt( easyhandle, CURLOPT_URL, url ) ;
curl_easy_setopt (easyhandle, CURLOPT_CONNECTTIMEOUT, .29);
FILE* file = fopen( "my.txt", "a+");
curl_easy_setopt( easyhandle, CURLOPT_WRITEDATA, file) ;
// curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_easy_perform( easyhandle );
curl_easy_cleanup( easyhandle );
fclose(file);
}
int main()
{
get_page( "http:couldbeanything.com", "style.css" ) ;
return 0;
}
So, this code fetches whole page and i just want to fetch some specific
number of lines using it (for example - 5)
I searched and came across something called "PHP dom parser" and is there
some way to implement this fetching in C/C++ ??
Thanks in advance

What is difference between and in maven plugin (jbehave example)

What is difference between and in maven plugin (jbehave example)

As in title - here is piece of code.
I can have < scope > as well as < phase >
Jbehave documentation doesn't say much about it
(http://jbehave.org/reference/stable/maven-goals.html)
<execution>
<id>run-stories</id>
<phase>test</phase>
<configuration>
<!--<scope>test</scope>-->
<includes>
<include>**/*Stories*.java</include>
</includes>
</configuration>
<goals>
<goal>run-stories-as-embeddables</goal>
</goals>
</execution>

Saturday, 14 September 2013

Vertical scroll only showing up in IE, not Chrome/FF

Vertical scroll only showing up in IE, not Chrome/FF

I'm working on this site right now:
http://outdoorstorage.net/test/outdoor_storage/index.php
For some reason IE is adding white space at the bottom of every page that
doesn't already exceed the Y direction overflow.
Does anyone know what might be the problem?
I'm sorry if I missed a similar topic, I wasn't able to find much.

Understanding a bit about resolution resolver - libgdx

Understanding a bit about resolution resolver - libgdx

i have been reading most of the questions and trying to understand the
solution but im still confused on how to make it work.
i made 3 atlases for different resolutions and currently im on a roadblock
in these codes :
Resolution[] resolutions = {new Resolution(320, 480, ".320480"), new
Resolution(480, 800, ".480800"),
new Resolution(480, 856, ".480854")};
// do i need to make folders with resolution like 320480/foo.jpg or make
an image named like foo.jpg.320480 *correct me if im wrong... im really
confused here so please bear with me
// what does this code do?
Texture.setAssetManager(ass_manager);
really needed for me to lean to make the screen not look ugly.
much appreciated, Dvd

CSS: Hide a div - Why it's not working?

CSS: Hide a div - Why it's not working?

I'm trying to use jquery-cookie to deal with the recent EU cookie laws.
Everything is working good, however I'd like to display different cookie
"warning" messages according to different devices.
<div id="cookiepopup" class="mobile_no">
<p>Questo sito utilizza i cookie, per garantire una migliore
esperienza di navigazione. Continuando, ne accetti l'utilizzo.<br
/>
This website uses cookies to improve your user experience. By
continuing to browse the site you are agreeing to our use of
cookies.<br />
<a href="/foo" target="_blank"><b>(Dettagli / Details)</b></a>
<input type="submit" class="cookieclose" value="Accetto /
Continue" /></p>
</div>
<div id="cookiepopup" class="mobile_yes">
<p>Questo sito utilizza i cookie. Continuando, ne accetti l'utilizzo.
This website uses cookies. By continuing to browse the site you
are agreeing to our use of cookies.<br />
<a href="/foo" target="_blank"><b>(Dettagli / Details)</b></a>
<input type="submit" class="cookieclose" value="Accetto /
Continue" /></p>
</div>
In style.css:
.mobile_yes{ display:none } <--- normal behaviour
.mobile_no{ display:none } <---- it goes under a specific css media query
for smartphones
Speaking in general terms and without considering the css media queries, I
can't hide any of the divs. Whatever I do, .mobile_no div is always
showed.
/* COOKIE POPUP */
#cookiepopup {
display:none;
background: #eee; border-top:1px solid #ddd; color:#555;
bottom: 0;
padding: 5px 2% 10px;
position: fixed;
width: 96%;
z-index: 10;
font-size:0.8em;
}
#cookiepopup p {
width:90%; margin:0 auto; max-width: 970px;
}
.mobile_no{ display:none }
Demo at http://www.flapane.com/test/test.php
I'm sure I'm missing something. Any help would be much appreciated.

Best $30 or under Lavalier Microphone

Best $30 or under Lavalier Microphone

Best $30 Lavalier microphone. I was looking at pairing the lav with a Zoom
H1 and my T4i. I was thinking about the ATR-3350 but I was not sure
because of the on/off switch and the fact that it is mono only. Any
suggestions?

Insertion sorting linked list

Insertion sorting linked list

Need to sort with insertions without swapping values(only pointers can be
changed). For every element ListElem from list: remove it from list
without deleting, and then scan list from beginning, and insert ListElem
to the right place. Help pls.
struct nod{
int num;
nod *next;
}
void InsertionSort(nod *head){
return;
}

A comparison between between Aho-Corasick algorithm and Rabin-Karp algorithm

A comparison between between Aho-Corasick algorithm and Rabin-Karp algorithm

I am working on multiple patterns search matching algorithms and I found
that two algorithms are the strongest candidates, namely Aho-Corasick and
Rabin-Karp in terms of running time. However, there are few things still
foggy. I could not find any comprehensive explicit comparison between the
two algorithms. Besides, what I need to know is which one is more suitable
for parallel computing and multiple patterns search. What is the time
complexity of each one of them and which one required less hardware
resources.

Merging two Images of which is able to drag. Is there any Sample Source for that?

Merging two Images of which is able to drag. Is there any Sample Source
for that?

I have an ImageView that has a background image in it. Than I want to add
a small image that I want to paste inside the background image. So, the
small image must be draggable, and ok and cancel buttons should pop up
before saving.
Is there any sample source I can reference?

Friday, 13 September 2013

Can we use native code as plugin in Rhomobile?

Can we use native code as plugin in Rhomobile?

I need to run a java code for Android inside Rhomobile app. Is there any
way i can call the java code. I have seen some of the plugins to interact
with native codes for Android.
I tried searching and i did get to this url
http://docs.rhomobile.com/rhoconnect/plugin-intro. But i guess this is not
for Rhomobile if i'm not wrong.
I have a library file for my requirement. Is there any way i can use it ?

Recommended flow for using Google Wallet with complex custom digital goods

Recommended flow for using Google Wallet with complex custom digital goods

I'm trying to set up a google wallet payment process for users to purchase
an entry into a tournament. In order to do this, the user has to fill out
a bunch of information about themselves (name, league player number,
contact phone number, etc), and there are some other pieces of data that
are implicit, such as a unique identifier for the tournament they're
entering.
It seems like there are two ways to accomplish this in Google Wallet, and
I'm wondering if I'm missing another, better workflow and/or if one of
these two ways is preferred.
Possibility #1
When the user clicks the wallet button, I serialize the form and submit it
to my server using ajax. If the form is properly filled out, the server
encodes everything about the form into the sellerData field of the JWT,
and returns the JWT asynchronously. I then pass this JWT to wallet,
expecting to receive it in my postback handler.
The postback handler then constructs the entry using the information from
the JWT sellerData field and records it in the database.
This possibility is intuitive to me, and I've implemented it, but I'm
running up against the 200 character limit for the sellerData field, since
it contains multiple peoples' names, phone numbers, and various other form
elements. There's just no room. I don't have a workaround for this, and
would welcome thoughts.
This approach has the advantage that nothing is created in my database
until payment is successful, but I don't know how to work around the
difficulties with representing the entire form in the JWT to get it to the
postback handler somehow.
Possibility #2
The user just submits the entry form using the normal web-form submission
process, which creates something in the database. Database objects newly
created in this way are marked as "unpaid", and are therefore incomplete.
Once the user successfully creates their entry in the database, they are
then presented with a second page at which they can pay. This works better
because I can now just put the database key for the object they just
created into the sellerData field, and not worry about the size limit.
It does have the unfortunate side-effect of having these half-completed
objects in the database, as well as running the risk of users not quite
understanding the two-step register-and-then-pay process, and forgetting
to pay. I'd have to be quite careful and proactive about making sure that
users realize that A) it's okay to submit the form with no payment
information, and B) that submitting the first form doesn't mean that
they're done.
Thoughts?

javascript oop. Constructor vs prototyping

javascript oop. Constructor vs prototyping

I can understand what is the difference in creating and object as a
constructor and creating an object in a literal notation and when is
better to use each definition, but I can not understand the difference
between the following two cases:
function Obj(){
this.foo = function(){...}
}
function Obj(){}
Obj.prototype.foo = function(){...}
Both are doing the same thing. Both will be instantiated using the same
var objNew = new obj();
So what is the difference and when to use each concept?

How can I safely handle POST parameters in an HTTP Handler using C#?

How can I safely handle POST parameters in an HTTP Handler using C#?

I'm working on an ASP.Net C# application (my first!) that contains an HTTP
Handler within it. My application works with several parameters that are
passed in via the URL. My question(s) is as follows:
My applications entry point is via the HTTP Handler. When I enter my
ProcessRequest method, I am assigning the values of the URL parameters to
variables so that I may do something with the data. Question: Is this
safe, even if I am not setting the value to anything when I call the URL?
Example: I call host/handler1.ashx instead of
host/handler1.ashx?something=foo
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
string something = context.Request["something"];
context.Response.Write("Hello World: " + something);
}
When calling the above method using the plain URL with no parameters, it
executes just fine, but the string something is just blank/null.
Additional questions: What happens to the variable something in the case
that I do not explicitly initialize it via the URL? I understand that it
is null, but can this lead to problems?
Is it dangerous or not safe to call the plain URL (i.e. should I always
call it with parameter values specified)?
What is the best way to call a "clean" ashx URL to start the application
but not risk problems?
The application will do a series of subsequent GET redirects as it
accumulates values and passes them back to the app via the query string.
Should I do a POST or GET upon initial call of the application?
Sorry for asking the same question multiple ways, but I'm a bit confused
on the topic and this is my first time writing an app like this. Any
patience and advice you could provide on how to safely handle and
initialize parameters is greatly appreciated!

Need to remove white space between two tags with Regex

Need to remove white space between two tags with Regex

I have a bit of XML that I would like to strip the outer white space from.
As a preface: The output is not well formed xml, it's a propritary spec I
am relegated to dealing with.
The sample is:
<mattext>
<span>A</span>
<span>more text</span>
</mattext>
What I need is:
<mattext><span>A</span>
<span>more text</span></mattext>
Where all white space between the opening <mattext> and the first bit of
inner content is gone, and the same for the closing </mattext>.
I've tried:
var output = Regex.Replace(input, @"<mattext>*<", "<mattext>",
RegexOptions.Multiline);
But I'm not having any luck. Can anyone advise?
Thanks!

Thursday, 12 September 2013

Why does toString function of a HashMap prints itself with a different order?

Why does toString function of a HashMap prints itself with a different order?

I have this very simple piece of code, and I was just trying to play a bit
with different kind of objects inside a Map.
//There's a bit of spanish, sorry about that
//just think 'persona1' as an object with
//a string and an int
Map mapa = new HashMap();
mapa.put('c', 12850);
mapa.put(38.6, 386540);
mapa.put("Andrés", 238761);
mapa.put(14, "Valor de 14");
mapa.put("p1", persona1);
mapa.put("Andrea", 34500);
System.out.println(mapa.toString());
And then I expect from console something like:
{c=12850, 38.6=386540, Andrés=238761, 14=Valor de 14, p1={nombre: Andres
Perea, edad: 10}, Andrea=34500}
But susprisingly for me I got same data in different order:
{38.6=386540, Andrés=238761, c=12850, p1={nombre: Andres Perea, edad: 10},
Andrea=34500, 14=Valor de 14}
It doesn't matter if I try other kind of objects, even just Strings or
numeric types, it always does the same, it makes a different
without-apparently-any-sense order.
Can someone give me a hint why this happens? Or may be something too
obvious I'm missing?
I'm in Java 1.7 and Eclipse Juno.

gestureRecognizer shouldReceiveTouch persisting in deallocated view causing crash

gestureRecognizer shouldReceiveTouch persisting in deallocated view
causing crash

I have a fairly simple UITableView that pushes a new view on the stack.
The new view has a gestureRecognizer that is initizalied like this
@synthesize swipeGestureLeft;
- (void)viewDidLoad
{
swipeGestureLeft = [[UISwipeGestureRecognizer alloc]
initWithTarget:self action:@selector(toggleViewLeft)];
swipeGestureLeft.numberOfTouchesRequired = 1;
swipeGestureLeft.delegate=self;
swipeGestureLeft.direction = (UISwipeGestureRecognizerDirectionLeft);
[self.view addGestureRecognizer:swipeGestureLeft];
}
I also call the delegate method
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer
shouldReceiveTouch:(UITouch *)touch {
if (viewShown==1) {
return NO;
}
return YES;
}
and in the dealloc method I have
- (void)dealloc {
NSLog(@"I AM IN DEALLOC");
swipeGestureLeft.delegate=nil;
[self.view removeGestureRecognizer:swipeGestureLeft];
swipeGestureLeft=nil;
}
in my .h file I have
@interface MyViewController : UIViewController <UIGestureRecognizerDelegate>
now when I hit back to go back to my table view, the view gets deallocated
(which I can see becasue the NSLog fires) now when I try and swipe down on
my table view the app crashes with:
[MyViewController gestureRecognizer:shouldReceiveTouch:]: message sent to
deallocated instance
How do I ensure the delegate method is not called after the view has
deallocated.

Python if loop with multiple variables

Python if loop with multiple variables

The code im trying to create is to print a wavelength such as radio waves
or microwaves based on the wavelength value input.
userInput = input("Enter wavelength (m) value: ")
waveValue= float(userInput)
if waveValue >10*-1 :
print("Radio Waves")
elif waveValue >10*-1<10*-3 :
print("Microwaves")
Any hints on how I can get the second if statement to work. Every input I
put in just outputs radio waves because my arguments does not work
properly.

C# Monitor.Wait/Pulse not visible?

C# Monitor.Wait/Pulse not visible?

According to the MSDN, the Wait/Pulse/PulseAll methods are static members
of the System.Threading.Monitor class. However, when I attempt to access
these operations, Visual Studio's intellisense dose not show these
operations (only the Enter, TryEnter, and Exit operations). When I attempt
to compile my application using these operations, I get the
"System.Threading.Monitor does not contain a definition for ..." error.
Can anyone tell me why these operations not available? Are there any
dependencies (other than the mscorlib reference) to use these operations?
note: I'm using .Net 4

How do you create an enumerator wrapper class?

How do you create an enumerator wrapper class?

I have this function:
def file_parser (filename)
Enumerator.new do |yielder|
File.open(filename, "r:ISO-8859-1") do |file|
csv = CSV.new(file, :col_sep => "\t", :headers => true, :quote_char
=> "\x07")
csv.each do |row|
yielder.yield map_fields(clean_data(row.to_hash))
end
end
end
end
I can use it like this:
parser = file_parser("data.tab")
parser.each do { |data| #do profitable things with data }
Instead, I'd like to put it in its own class and use it like this:
parser = FancyParser.new("data.tab")
parser.each do { |data| #do profitable things with data }
I've tried some things I didn't expect to work, like just returning the
enumerator out of initialize(), and self = file_parser().
I've also tried super do |yielder|.
For some reason, the way to do this is not coming to me.

Prevent scrolling past a certain point

Prevent scrolling past a certain point

I am trying to make a scrolling carousel, unlike other carousels this one
doesn't jump from slide to slide but only allows the user to slowly move
through them horizontally at a rate of 50px.
http://codepen.io/anon/pen/pyLfz
Problem is when clicking next, once the number 6 box comes into full view
the script should not allow the user to go any further, same for when the
number 1 box is in full view and prev link is clicked, the user should not
be allowed to scroll back anymore.
Right now I can't figure out how to do that.
HTML:
<div class="carousel">
<div class="slide">
<article class="pod">1</article>
<article class="pod">2</article>
<article class="pod">3</article>
<article class="pod">4</article>
<article class="pod">5</article>
<article class="pod">6</article>
</div>
</div>
<a href="#" class="prev">Prev</a>
<a href="#" class="next">Next</a>
CSS:
.carousel {
position: relative;
border: 1px solid red;
width: 250px;
height: 100px;
overflow: hidden;
}
.carousel .slide {
overflow: hidden;
position: absolute;
width: 600px;
}
.carousel .slide .pod {
width: 100px;
height: 100px;
line-height: 100px;
text-align: center;
background: blue;
box-shadow: 0 0 18px white;
color: #fff;
float: left;
}
jQuery:
$('.next').on('click', function() {
$('.slide').animate({
left: '-=50'
});
});
$('.prev').on('click', function() {
$('.slide').animate({
left: '+=50'
});
});

iOS : Post on twitter without open dialogue using twitter.framework

iOS : Post on twitter without open dialogue using twitter.framework

I am trying to posting a tweet on twitter using iOS twitter.framework ,
somehow its not showing me any error when post request gets done, however
its not posting anything on twitter!
Here's my code for
-(void)twitPost
{
ACAccountStore *account = [[ACAccountStore alloc] init];
ACAccountType *accountType = [account
accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierTwitter];
NSArray *arrayOfAccounts = [account accountsWithAccountType:accountType];
if (!arrayOfAccounts)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"No
Twitter Account" message:@"There are no Twitter accounts
configured. You can add or create a Twitter account in the main
Settings section of your phone device." delegate:nil
cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
[alert show];
[alert release];
return;
}
// Request access from the user to access their Twitter account
[account requestAccessToAccountsWithType:accountType
withCompletionHandler:^(BOOL granted, NSError *error)
{
// Did user allow us access?
if (granted == YES)
{
// Populate array with all available Twitter accounts
NSArray *arrayOfAccounts = [account
accountsWithAccountType:accountType];
if ([arrayOfAccounts count] > 0)
{
// Keep it simple, use the first account available
ACAccount *acct = [arrayOfAccounts objectAtIndex:0];
TWRequest *postRequest = [[TWRequest alloc]
initWithURL:[NSURL
URLWithString:@"https://upload.twitter.com/1/statuses/update.json"]
parameters:[NSDictionary dictionaryWithObject:@"This is a
sample message!" forKey:@"status"]
requestMethod:TWRequestMethodPOST];
[postRequest setAccount:acct];
// Perform the request created above and create a handler
block to handle the response.
[postRequest performRequestWithHandler:^(NSData
*responseData, NSHTTPURLResponse *urlResponse, NSError
*error)
{
if(error)
{
NSLog(@"Twitter Request failed with error:
%@",[error localizedDescription]);
}else{
NSLog(@"Twitter response, HTTP response: %i",
[urlResponse statusCode]);
NSLog(@"Message %@",[NSHTTPURLResponse
localizedStringForStatusCode:[urlResponse
statusCode]]);
}
}];
}
}
}];
}
Inside the block, I am not getting any error, but I got to print this,
2013-09-12 19:51:40.103 MyApp[8380:21603] Twitter response, HTTP response:
410
2013-09-12 19:51:44.053 MyApp[8380:21603] Message no longer exists
It's not logged any error message!
Note,
1) I'd already configured a twitter account in the settings.
What's wrong? I am missing something?

JavaFX: Best practice to implement glasspane-like mouse/touch event receiver which forwards events to underlying controls

JavaFX: Best practice to implement glasspane-like mouse/touch event
receiver which forwards events to underlying controls

My challenge is following situation:
I want to add an invisible (opacity 0) pane over the whole application,
which receives all mouse and touch events. When an event occurs it resets
some kind of activity timer.
My first approach (without such pane) was adding listeners to the root
pane, which worked pretty well. But... the buttons consume all events, so
the timer does not get reset.
In my opinion, the glasspane solution would be a much more nicer solution,
but I can't find a solution to forward received mouse and touch events to
the underlying controls.
In short: the pane intercepts a mouse event (trigger to reset timer), and
the underlying button gets clicked.
Any ideas please?

Wednesday, 11 September 2013

Handling multiple values in subquery

Handling multiple values in subquery

I have two tables one of which holds employee information and the other
that holds dependents information. I want to create a query which
retrieves all the first names of each employees children and combine them
into one field of the results.
I know how to create a subquery that returns a single result as a field in
another query but not having any luck figuring this one out. Any
suggestions would be greatly appreciated.
Tables: tblPersonnel, tblFamilyData linked by [ID] primary [sponsorID]
foriegn
Desired output: EmployeeName | Address | KidName1, KidName2, KidName3

Separate a double into it's sign, exponent and mantissa

Separate a double into it's sign, exponent and mantissa

I've read a few topics that do already broken down doubles and "puts it
together" but I am trying to break it into it's base components. So far I
have the bit nailed down:
breakDouble( double d ){
long L = *(long*) &d;
sign;
long mask = 0x8000000000000000L;
if( (L & mask) == mask ){
sign = 1;
} else {
fps.sign = 0;
}
...
}
But I'm pretty stumped as to how to get the exponent and the mantissa. I
got away with forcing the double into a long because only the leading bit
mattered so truncation didn't play a role. However, with the other parts I
don't think that will work and I know you can't do bitwise operators on
floats so I'm stuck.
Thoughts?



edit: of course as soon as I post this I find this, but I'm not sure how
different floats and doubles are in this case.



Edit 2(sorry working as I go): I read that post I linked in edit 1 and it
seems to me that I can perform the operations they are doing on my double
the same way, with masks for the exponent being:
mask = 0x7FF0000000000000L;
and for the mantissa:
mask = 0xFFFFFFFFFFFFFL;
Is this correct?

Eclipse: Problems View: Warnings: Eclipse Not Seeing JSTL libraries

Eclipse: Problems View: Warnings: Eclipse Not Seeing JSTL libraries

I'm using Eclpise 3.72 on Windows 7, with a legacy webapp.
In "Problems View" I am getting a lot of warnings about JSTL tags being
unknown, like this one:
Unknown tag (c:if)
Everything in the webapp compiles and runs beautifully.
I have the JSTL jars in my war/WEB-INF/lib
I have these tags in my header.jsp:
<%@ page language = "java" session = "true" import = "java.util.*,
java.text.*" %>
<%@ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix = "f" uri="http://www.springframework.org/tags/form"%>
I'm guessing Eclipse thinks those tags are unknown, because they are only
in the header.jsp which is included at the top of the other JSPs.
Is there anyway to get rid of those "unknown tag warnings" without
shutting off the JSP warnings?
Thanks.

Overriding Ordering[Int] in Scala

Overriding Ordering[Int] in Scala

I'm trying to sort an array of integers with a custom ordering.
E.g.
quickSort[Int](indices)(Ordering.by[Int, Double](value(_)))
Basically, I'm trying to sort indices of rows by the values of a
particular column. I end up with a stackoverflow error when I run this on
a fairly large data. If I use a more direct approach (e.g. sorting Tuple),
this is not a problem.
Is there a problem if you try to extend the default Ordering[Int]?

Referencing a module in the same file as it's declaration

Referencing a module in the same file as it's declaration

I have the following issue:
The TypeScript declarations for the Pixi library exist but seem to be
broken. Firstly, they start with
declare module PIXI
instead of
declare module "PIXI"
I'm not sure if this is wrong but all the other delcarations (for node,
socket.io, etc.) seem to use strings for names. When I change it to a
string it works but encounters an error later. Outside of that PIXI module
there this:
declare function requestAnimFrame( animate: PIXI.IBasicCallback );
Now because I changed PIXI to a string (I assume), it says that the
variable PIXI doesn't contain a type named IBasicCallback. The module does
export that type, but it's just not available outside of it. Outside of
the declaration file, in my code, I can use PIXI.IBasicCallback just fine,
but inside the same file it's not recognized.
What can I do to fix this?

How to get address pointer of a member function

How to get address pointer of a member function

In the following code, it seems that I can't get the correct address of
the second function.
Link to Ideone : http://ideone.com/r07UZc
#include
<stdio.h>
class A
{
public:
__attribute__((noinline)) int func1();
__attribute__((noinline)) int func2();
};
int A::func1()
{
return 1;
}
int A::func2()
{
return 2;
}
int main()
{
printf("%p %p\n", &A::func1, &A::func2);
return 0;
}
The printed values are : 0x80484d0 (nil)
The first address seem to be correct but not the second. Why ?

how to image path insert in myql?

how to image path insert in myql?

I'd like to include in my MySQL table a path to an image. The image path
gets into the table by inserting the value of a "file" textfield (one of
those Browse kind of deals). So the value that gets entered is something
like: image001.jpg. But I can't seem to use that value to put an image
into a html page. if it goes into the table fine, why can't I get it out?
I upload an image but I don't know where it's gone. Because there's no
value entered in image field when I checked it through PhpMyadmin.
Table schema
CREATE TABLE employee_details
(
emp_image varchar(255),
employee_name varchar(50),
employee_address varchar(50),
employee_designation varchar(50),
employee_salary int(),
);
Query
$sql="
INSERT INTO employee_detail(
emp_image,
employee_name,
employee_address,
employee_contact,
employee_designation,
employee_salary
)
VALUES(
'$_POST[emp_image]',
'$_POST[employee_name]',
'$_POST[employee_address]',
'$_POST[employee_contact]',
'$_POST[employee_designation]',
'$_POST[employee_salary]'
)";

add images to UIBarButtonItem of toolbar in ios

add images to UIBarButtonItem of toolbar in ios

I have a UIBarButtonItem that does not take the picture
I have a toolbar with a button UIBarButtonItem above, connected via
IBOutlet. The image that I put you do not see. My code
@interface ViewController : {
IBOutlet UIToolbar *toolBar;
IBOutlet UIBarButtonItem * myBackButton;
IBOutlet UIBarButtonItem * myReloadButton;
IBOutlet UIBarButtonItem * myHomeButton;
IBOutlet UIBarButtonItem * myListButton;
IBOutlet UIBarButtonItem * myCalendarbutton;//the problem is this
}
the button is connect by IB but does not take the picture.
this is the image

this is the IB

Tuesday, 10 September 2013

Most efficient way to store and search a large collection of objects in Java

Most efficient way to store and search a large collection of objects in Java

I am currently working on a program which allows a user to search through
a very large collection (~100,000 objects) of trading cards and select
cards of their choice to add to a deck file.
My question is, what is the most efficient way to store these objects for
optimal search time? I need to be able to search each object for multiple
possible values( card information fields such as name, type, rules text,
etc) which match the given search string input and return all cards which
match the search string.
Any suggestions will be appreciated.

TabHost in Android Application

TabHost in Android Application

I am new in Android developments and I am trying to design a nice looking
ui with an TabHost component and with a GridView. I have tired to try try
and gem message like "Unfortunately, System UI has stopped".
My code in main_activity.xml is below
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
xmlns:app="http://schemas.android.com/apk/res/mya.mycode.myprogramname">
<android.support.v7.widget.GridLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<TabHost
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent"
app:layout_column="0"
app:layout_gravity="left|top"
app:layout_row="0" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TabWidget>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/tab1"
android:layout_width="match_parent"
android:layout_height="match_parent">
</LinearLayout>
<LinearLayout
android:id="@+id/tab2"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</LinearLayout>
<LinearLayout
android:id="@+id/tab3"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</android.support.v7.widget.GridLayout>
</LinearLayout>
And my java code in the file MainActivity.java is
package mya.mycode.myprogramname;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.my_options_menu, menu);
return true;
}
}
Can someone help? thanks

Expand a list of cases in a subclass

Expand a list of cases in a subclass

Most probably what I want to do cannot be done, but hopefully something
similar is possible.
What I would like to do is having a match-case statement in a method in a
class A, creating a subclass B and keeping all the cases that are not
overwritten by my subclass, so that before the final case _ in the
subclass all the cases of the superclass A are attempted.
AFAIK this is very far from being possible (but please correct me if
wrong), but something similar is not that far from being possible.
A maybe possible option would be to have a map of cases and functions in
the superclass and expanding that map in each subclass. The cases should
be of the type [T1] => Bool, the functions should be of the type [T1] =>
[T2], where T2 is the return type of the method we are expanding in the
subclass. Then a loop should be run until one case returns true and its
function is executed.
The problem is that I am uncertain about how to define those cases ([T1]
=> Bool). Having a match for each one of them may be very inefficient.
This may also be deeply non-idiomatic and some other way to implement this
could be preferable.

Mongoose find with reference to object

Mongoose find with reference to object

I have a find inside a loop:
for(var idx in items){
var item = items[idx];
Model.find({'_id': item.id}, function(err, matches){
console.log(item); // Points to the last item in items instead of
// expected item, since find is asynchronous
});
}
As you see, since find is asynchronous I can't get a solid reference to
the item var.
I could go ahead and manually look for it again in the items array by the
matched object inside the callback but that just doesn't seems like an
effective approach.
If there would be any way to "attach" an object to the call so I could get
it back with the callback that would be awesome.
Any ideas ?

Struts2 jquery tabbedpanel

Struts2 jquery tabbedpanel

I have thee tabs in sj:tabbedpanel. I want to know which tab is activated
and set values in value of a hidden field accordingly.
<sj:tabbedpanel id="localtabs" >
<sj:tab id="connected" target="tone" label="Connected" />
<sj:tab id="disconnected" target="ttwo" label="Not Connected"/>
<sj:tab id="distribution" target="tthree" label="Distributed"/>
<div id="tone">tone</div>
<div id="ttwo">ttwo</div>
<div id="tthree">tthree</div>
</sj:tabbedpanel>
Now I want to set value of hidden input field according to activated tab
0,1 or2 for tabs tone, ttwo and tthree.
<input type="hidden" name="activeTab" value="0" id ="activeTab"/>
I tried
$("#connected").click(function(){
alert("Connected");
$("#activeTab").val(0);
});
$("#disconnected").click(function(){
alert("Not Connected");
$("#activeTab").val(1);
});
$("#distribution").click(function(){
alert("distribution");
$("#activeTab").val(3);
});
but its not working. Thanks in advance.

how to deploy website with edmx

how to deploy website with edmx

i have just only added Edmx file inside App_code folder and it's mapped
with database(sqlexpress).I am not using ADO.Net context DB generator. my
website is working successfully in local pc but when website is hosted in
IIS7 then my website is not running and it's not able to connect
database.please let me know how to set connection string so that my
connection string identify sdl,msdl,msl.please guid me if i missed
anything.or it would be better if you have sample website which is hosted
in iis.

Are these examples of Polymorphism?

Are these examples of Polymorphism?

After browsed some questions about Polymorphism, it seems that
Polymorphism is a general idea in Java, just to make an Object to behave
as if it were an instance of another class, thus the code is more
independent of the concrete class. Given this idea, are the two method
calls in the following main() usages of Polymorphism ?
abstract class A
{
void f() { System.out.println("A.f()"); }
abstract void g();
}
class B extends A
{
void g() { System.out.println("B.g()"); }
}
public class Test
{
public static void main(String[] args)
{
A a = new B();
a.f(); // Is this an usage of Polymorphism ?
a.g(); // ...
}
}
The output is :
A.f();
B.g();

Monday, 9 September 2013

How to load progress dialog inside a webview when we navigate from a url to other in android?

How to load progress dialog inside a webview when we navigate from a url
to other in android?

I would like to know how to invoke progress dialog inside a webview when
we we navigate to new url from a url.Kindly provide me an example or
snippet on how to achieve this.Thank a lot.

iOS7, Rate the app link does not work

iOS7, Rate the app link does not work

It does work on iOS6 and earlier iOS devices for my app. I have a link
"itms-apps://ax.itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?type=Purple+Software&id=%@"
to rate the app. This works on my earlier iOS devices. When I update the
same app in iOS7 device, this link does not work anymore. I shows app
store page but not my app review page.

Performance of SQL query

Performance of SQL query

I have to query a table with few millons of rows and I want to do it the
most optimized.
Lets supose that we want to controll the access to a movie theater with
multiples screening rooms and save it like this: AccessRecord (TicketId,
TicketCreationTimestamp, TheaterId, ShowId, MovieId, SeatId,
CheckInTimestamp)
To simplify, the 'Id' columns of the data type 'bigint' and the
'Timestamp' are 'datetime'. The tickets are sold at any time and the
people access to the theater randomly. And the primary key (so also
unique) is TicketId.
I want to get for each Movie and Theater and Show (time) the AccessRecord
info of the first and last person who accessed to the theater to see a
mov. If two checkins happen at the same time, i just need 1, any of them.
My solution would be to concatenate the PK and the grouped column in a
subquery to get the row:
select
AccessRecord.*
from
AccessRecord
inner join(
select
MAX(CONVERT(nvarchar(25),CheckInTimestamp, 121) +
CONVERT(varchar(25), tickets)) as MaxKey,
MIN(CONVERT(nvarchar(25),CheckInTimestamp, 121) +
CONVERT(varchar(25), tickets)) as MinKey
from
AccessRecord
group by
MovieId,
TheaterId,
ShowId
) as MaxAccess
on CONVERT(nvarchar(25),CheckInTimestamp, 121) + CONVERT(varchar(25),
tickets) = MaxKey
or CONVERT(nvarchar(25),CheckInTimestamp, 121) + CONVERT(varchar(25),
tickets) = MinKey
The conversion 121 is to the cannonical expression of datatime resluting
like this: aaaa-mm-dd hh:mi:ss.mmm(24h), so ordered as string data type it
will give the same result as it is ordered as a datetime.
As you can see this join is not very optimized, any ideas?

Display tool tip in disabled control

Display tool tip in disabled control

I know this was already asked here: C#: Problem displaying tooltip over a
disabled control
But it doesn't work for me. I have a TabControl control, with a TabPage in
it. In the TabPage, I have a TableLayoutPanel. My disabled controls are
inside that panel.
The problem is that the event does not fire when the mouse is over the
disabled control. I tried the code in the MouseMove of the Form, the
TabControl, the TabPage, the TableLayoutPanel and the disabled controls
themselves, but none of them are working. Is there another solution?

Android connection refuses sometimes (Not all times)

Android connection refuses sometimes (Not all times)

I wrote a WiFi-Direct Code connection and created a connection between
them, then I created a ServerSocket on the first side and a Socket on the
client side and started sending data between them, the first time I start
the application it works Successfully, but when I close the Application
and start it again it gives me an exception that says "Connection Refused
ECONNREFUSED" here is my code in the Server side:
package com.example.serverwifidirect;
import java.io.InputStream;
import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import android.annotation.SuppressLint;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class BroadcastServer extends BroadcastReceiver
{
@SuppressLint("NewApi")
private WifiP2pManager mManager;
private Channel mChannel;
private Server mActivity;
static boolean temp=false;
Socket client=null;
static boolean isRunning = false;
ServerSocket serverSocket = null;
InetSocketAddress inet;
private void closeConnections()
{
try
{
if(client!=null || serverSocket!=null)
{
if(client!=null)
{
if(client.isInputShutdown()|| client.isOutputShutdown())
{
log("x1");
client.close();
}
if(client.isConnected())
{
log("x2");
client.close();
log("x2.1");
//client.bind(null);
log("x2.2");
}
if(client.isBound())
{
log("x3");
client.close();
}
client=null;
}
}
}
catch(Exception e)
{
log("Error :'(");
e.printStackTrace();
}
}
@SuppressLint("NewApi")
public BroadcastServer(WifiP2pManager manager, Channel channel, Server
activity)
{
super();
this.mManager = manager;
this.mChannel = channel;
this.mActivity = activity;
try
{
serverSocket = new ServerSocket(8870);
serverSocket.setReuseAddress(true);
}
catch(Exception e)
{
}
}
@SuppressLint("NewApi")
@Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action))
{
int state =
intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED)
{}
else
{}
}
else if(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action))
{
mManager.requestPeers(mChannel, new PeerListListener()
{
@Override
public void onPeersAvailable(WifiP2pDeviceList list)
{
}
});
} else if
(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action))
{
Bundle b = intent.getExtras();
NetworkInfo info =
(NetworkInfo)b.get(WifiP2pManager.EXTRA_NETWORK_INFO);
if(info.isFailover())
{
temp=false;
}
else if(info.isConnected())
{
temp=true;
log("c1");
new Thread(new Runnable(){
public void run()
{
try
{
client =serverSocket.accept();
InputStream input=null;
input = client.getInputStream();
log("q3");
while(BroadcastServer.temp)
{
final int n = input.read();
if(n==100)
{
closeConnections();
mManager.cancelConnect(mChannel, new
ActionListener() {
@Override
public void onSuccess()
{
log("done");
mManager.removeGroup(mChannel,
new ActionListener()
{
@Override
public void onSuccess()
{
log("group removed");
}
@Override
public void onFailure(int
reason)
{
log("fail!!!!!");
}
});
}
@Override
public void onFailure(int reason) {
log("fail");
mManager.removeGroup(mChannel,
new ActionListener()
{
@Override
public void onSuccess()
{
log("group removed");
}
@Override
public void onFailure(int
reason)
{
log("fail!!!!!");
}
});
}
});
}
log("q4");
if(n==-1)
{
log("n = -1");
break;
}
log("n= "+n);
mActivity.runOnUiThread(new Runnable()
{
public void run()
{
Toast.makeText(mActivity.getBaseContext(),
"--"+n,
Toast.LENGTH_SHORT).show();
}
});
}
log("After loop");
}
catch(Exception e)
{
}
}
});
mActivity.runOnUiThread(new Runnable(){
public void run()
{
//Toast.makeText(mActivity, "Connected to
WiFi-Direct!", Toast.LENGTH_SHORT).show();
}
});
log("c2");
}
else if(info.isConnectedOrConnecting())
{
temp=false;
}
else if(!info.isConnected())
{
temp=false;
try
{
if(client!=null || serverSocket!=null)
{
if(client!=null)
{
if(client.isInputShutdown()||
client.isOutputShutdown())
{
log("x1");
client.close();
}
if(client.isConnected())
{
log("x2");
client.close();
log("x2.1");
//client.bind(null);
log("x2.2");
}
if(client.isBound())
{
log("x3");
client.close();
}
client=null;
}
}
}
catch(Exception e)
{
log("Error :'(");
e.printStackTrace();
}
mManager.clearLocalServices(mChannel, new ActionListener()
{
@Override
public void onSuccess()
{
log("success");
}
@Override
public void onFailure(int reason)
{
}
});
}
}
else if
(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action))
{
log("Device change Action!");
}
}
public static void log(String shusmu)
{
Log.d("status", shusmu);
}
}
this code is in the Server side, and the following code is in the Client
side:
package com.example.wifidirect;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.os.Bundle;
import android.util.Log;
import android.widget.Button;
@SuppressLint("NewApi")
public class WiFiDirectBroadcastReceiver extends BroadcastReceiver
{
static WifiP2pDevice connectedDevice = null;
boolean found=false;
boolean connected = false;
private WifiP2pManager mManager;
private Channel mChannel;
Button find = null;
Activity mActivity = null;
@SuppressLint("NewApi")
public WiFiDirectBroadcastReceiver(WifiP2pManager manager, Channel
channel, WifiDirect activity)
{
super();
this.mManager = manager;
this.mChannel = channel;
mActivity = activity;
find = (Button)mActivity.findViewById(R.id.discover);
}
@SuppressLint("NewApi")
@Override
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action))
{
int state =
intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED)
{
// Wifi Direct is enabled
} else
{
// Wi-Fi Direct is not enabled
}
}
else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action))
{
mManager.requestPeers(mChannel, new PeerListListener()
{
@Override
public void onPeersAvailable(WifiP2pDeviceList list)
{
WifiP2pDevice d = null;
if(!found)
{
Log.d("status", "2");
Collection<WifiP2pDevice>li = list.getDeviceList();
ArrayList<WifiP2pDevice> arrayList = new
ArrayList<WifiP2pDevice>();
Iterator<WifiP2pDevice>peers = li.iterator();
while(peers.hasNext())
{
WifiP2pDevice device = peers.next();
arrayList.add(device);
}
for(int i=0;i<arrayList.size();i++)
{
log("xxx");
log(arrayList.get(i).deviceName);
if(arrayList.get(i).deviceName.equalsIgnoreCase("Android_144b"))
{
d = arrayList.get(i);
arrayList.clear();
found = true;
break;
}
}
}
if(d!=null)
{
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = d.deviceAddress;
if(!connected)
{
mManager.connect(mChannel, config, new
ActionListener()
{
@Override
public void onSuccess()
{
connected = true;
}
@Override
public void onFailure(int reason)
{
connected=false;
mManager.cancelConnect(mChannel,
new ActionListener()
{
@Override
public void onSuccess()
{
Log.d("status", "success
on cancelConnect()");
}
@Override
public void onFailure(int reason)
{
Log.d("status", "Fail on
cancelConnect()");
}
});
}
});
}
}
}
});
} else if
(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action))
{
Bundle b = intent.getExtras();
NetworkInfo info =
(NetworkInfo)b.get(WifiP2pManager.EXTRA_NETWORK_INFO);
if(info.isFailover())
{
connected=false;
Log.d("status", "connection failure!");
}
else if(info.isConnected())
{
connected=true;
find.setEnabled(false);
Log.d("status", "connection is Connected!");
}
else if(info.isConnectedOrConnecting())
{
connected=false;
log("Connecting !!!");
}
else if(!info.isConnected())
{
if(connected)
{
//closeConnections();
connected=false;
}
find.setEnabled(true);
mManager.removeGroup(mChannel, new ActionListener()
{
@Override
public void onSuccess()
{
log("Success disconnect");
}
@Override
public void onFailure(int arg0)
{
log("Fail disconnect");
}
});
}
}
else if
(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action))
{}
}
public static void log(String shusmu)
{
Log.d("status", shusmu);
}
}
And this is the class Connection
package com.example.wifidirect;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.annotation.SuppressLint;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
@SuppressLint("NewApi")
public class Connection
{
boolean found = false;
OutputStream out=null;
Socket socket = null;
boolean connected =false;
WiFiDirectBroadcastReceiver mReceiver=null;
WifiDirect instance=null;
@SuppressLint("NewApi")
Channel mChannel=null;
WifiP2pManager mManager=null;
public void sendMessage(int msg)
{
try
{
out.write(msg);
}
catch(Exception e)
{
e.printStackTrace();
}
}
public Connection(WiFiDirectBroadcastReceiver mReceiver,WifiDirect
instance,Channel mChannel,WifiP2pManager mManager) throws
UnknownHostException, IOException
{
this.instance=instance;
this.mReceiver=mReceiver;
this.mChannel=mChannel;
this.mManager= mManager;
socket = null;
Button send = (Button)instance.findViewById(R.id.send);
send.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View arg0)
{
try
{
log("z1");
if(socket==null)
{
log("z2");
Thread t = new Thread(new Runnable()
{
public void run()
{
try
{
log("z3");
socket= new Socket("192.168.49.1",8870);
socket.setReuseAddress(true);
log("z4");
out = socket.getOutputStream();
connected = true;
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
t.setDaemon(false);
t.start();
}
new Thread(new Runnable()
{
public void run()
{
log("trying to Send !");
while(!connected);
sendMessage(10);
log(" Data sent !");
}
}).start();
}
catch(Exception e)
{
log("exception_1");
e.printStackTrace();
log("exception_2");
log(e.getMessage());
}
}
});
}
public void closeConnections()
{
try
{
if(out!=null)
{
out.close();
out=null;
}
if(socket!=null)
{
socket.shutdownInput();
socket.shutdownOutput();
if(socket.isInputShutdown()|| socket.isOutputShutdown())
{
socket.close();
}
if(!socket.isClosed())socket.close();
}
if(socket.isConnected())
{
socket.close();
}
socket=null;
}
catch(Exception e)
{
Log.d("status", "error :( ");
e.printStackTrace();
}
}
public void connect()
{
mManager.discoverPeers(mChannel, new ActionListener()
{
@Override
public void onSuccess()
{
Log.d("status", "1");
}
@Override
public void onFailure(int reason)
{
mManager.cancelConnect(mChannel, new ActionListener() {
@Override
public void onSuccess()
{
Log.d("status", "success cancel connect");
connect();
}
@Override
public void onFailure(int reason)
{
Log.d("status", "failed cancel connect");
}
});
}
});
}
public static void log(String shusmu)
{
Log.d("status", shusmu);
}
}
finally this is my main Activity class
package com.example.wifidirect;
import java.io.IOException;
import java.net.UnknownHostException;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.WifiManager;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.Channel;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class WifiDirect extends Activity
{
WifiP2pManager mManager;
Channel mChannel;
WiFiDirectBroadcastReceiver mReceiver;
PeerListListener listener = null;
IntentFilter mIntentFilter;
String host;
Connection con=null;
PeerListListener myPeerListListener;
@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.wifi_direct);
StrictMode.enableDefaults();
WifiManager wifiManager =
(WifiManager)this.getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
mManager = (WifiP2pManager)
getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mReceiver = new WiFiDirectBroadcastReceiver(mManager, mChannel,
this);
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
try {
con = new Connection(mReceiver,this,mChannel,mManager);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
final Button discover = (Button)findViewById(R.id.discover);
discover.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
con.connect();
}
});
}
@Override
protected void onResume()
{
super.onResume();
registerReceiver(mReceiver, mIntentFilter);
}
@Override
protected void onPause() {
super.onPause();
}
@SuppressLint("NewApi")
@Override
protected void onDestroy()
{
super.onDestroy();
con.sendMessage(100);
unregisterReceiver(mReceiver);
}
@SuppressLint("NewApi")
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data)
{
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
String action = data.getAction();
if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action))
{
if (mManager != null)
{
mManager.requestPeers(mChannel, myPeerListListener);
}
}
}
void log(String s)
{
Log.d("status ", s);
}
}