Monday, 30 September 2013

Cause for not being able to login?

Cause for not being able to login?

Before Ubuntu 12.04 LTS login screen I get this message and was wondering
if this could be the cause for the login screen returning after entering
my password and hitting enter; "The disk drive for /dev/mapper/cryptswap1
is not ready yet or not present."
When I login to my main user account it tries to load something but then
after a time just comes back to the login screen.
I am not able to login with Guest either, same kick back to login screen
after about 20-seconds.
This is a clean install.
When the Login to Guest window disappears I get a black screen with the
following message (after some OKs);
947.796019] nouveau E[ 1007] failed to idle channel 0xcccc0000
[1254.824019] """"" " [ 3136] " " " " """""""" [2417.180016] """"" " [
4086] " " " " """""" [2420.276016] """" " [ 4361] " " " " """"""
[3007.796018] """" " [ 6094] " " " " """"""

Can INSERT (x) VALUES (@x) WHERE NOT EXISTS ( SELECT * FROM WHERE x = @x) cause duplicates?

Can INSERT (x) VALUES (@x) WHERE NOT EXISTS ( SELECT * FROM WHERE x = @x)
cause duplicates?

While browsing SO I found the following Question/Discussion about the
"best" approach for inserting records that don't exist yet. One of the
statements that struck me was one of [Remus Rusanu] stating:
Both variants are incorrect. You will insert pairs of duplicate @value1,
@value2, guaranteed.
Although I do agree about this for the syntax where the check is
'separated' from the INSERT (and no explicit locking/transaction mgmt is
present); I'm having a hard time understanding why and when this would be
true for the other proposed syntax that looks like this
INSERT INTO mytable (x)
SELECT @x WHERE NOT EXISTS (SELECT * FROM mytable WHERE x = @x);
I do NOT want to start (another) what's best/fastest discussion, nor do I
think the syntax can 'replace' a unique index/constraint (or PK) but I
really need to know in what situations this construction could cause
doubles as I've been using this syntax in the past and wonder if it is
unsafe to continue doing so in the future.
What I think that happens is that the INSERT & SELECT are both in the same
(implicit) transaction. The query will take an IX lock on the related
record (key) and not release it until the entire query has finished, thus
only AFTER the record has been inserted. This lock blocks all other
connections from making the same INSERT as they can't get a lock
themselves until after our insert has finished; only then they get the
lock and will start verifying for themselves if the record already exists
or not.
As IMHO the best way to find out is by testing, I've been running the
following code for a while on my laptop:
-- (create table once, run below on many, many connections in parallel)
CREATE TABLE t_test (x int NOT NULL PRIMARY KEY (x))
GO
SET NOCOUNT ON
WHILE 1 = 1
BEGIN
INSERT t_test (x)
SELECT x = DatePart(ms, CURRENT_TIMESTAMP)
WHERE NOT EXISTS ( SELECT *
FROM t_test old
WHERE old.x = DatePart(ms, CURRENT_TIMESTAMP) )
END
So far the only things to note are:
No errors encountered (yet)
CPU is running quite hot =)
table held 300 records quickly (due to 3ms 'precision' of datetime) after
that no actual inserts are happening any more, as expected.

How to capture/store a users answer to something and determine if it's true after a certain peroid of time.

How to capture/store a users answer to something and determine if it's
true after a certain peroid of time.

I'm trying to figure out how I could accomplish something.I'm having a
hard time thinking how to exactly word this so I apologize but lets take
this for example.. Say if you had a site that you could predict the
winners of basketball/football games. When someone is on their account on
the site, how can I capture their prediction and after a certain period of
time (When the game is over) it will update the account and tell me if I
was right or wrong and maybe put some kind of points on their account or
something...
Even if the site was as basic as two teams. Who will win, A or B? When you
choose A or B it's going to be before the game.. You can only choose
before the game begins, so you're not going to know the winner.. So it's
going to save your choice you've made and when the game is over it's going
to tell you if you were right or not. The hardest part I see is the time
delay.. Also what if the game goes into over time?
I'm not sure if Javascript/Jquery or PHP would be the best language for
the job so any suggestions would be helpful. I really appreciate taking
the time and read and answer my question.
Thank you

Android: (if) not working properly

Android: (if) not working properly

I am trying to set one message in toast. My idea is when the GPS is turn
on and the Latitude and Longitude is not "0" then to receive message like
this "gps is connected to satellites". But it's look this method is not
working. If I say to if- GPS turn off or the Latitude and Longitude is
equals to "0" then everything work properly. Just whyyy! I dont't get it.
Here is the code
Thanks in advance.
LocationListener Loclist = new LocationListener(){
@Override
public void onLocationChanged(Location lc){
// TODO Auto-generated method stub
//not working but with right logic
//GPS is turn on and the Latitude and Longitude is not "0"
if(lc != null && lastLat != 0 && lastLon != 0){
Context context = getApplicationContext();
CharSequence text = "GPS is connected to satellites.";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
//working but with wrong logic
//GPS turn off or the Latitude and Longitude is equals to "0"
if(lc == null || lastLat == 0 && lastLon == 0){
Context context = getApplicationContext();
CharSequence text = "GPS is connected to satellites.";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}

Sunday, 29 September 2013

String.Split Method optimize way in vb.net

String.Split Method optimize way in vb.net

I have a string xxx1-0.1/1 yyy,ccc1,1. I used split and substring. All i
want to get is the 0.1/1 only. Is there any optimize way to do this?
Thank you in advance!

How To Make Page To Interact With Background Page?

How To Make Page To Interact With Background Page?

My Chrome extension has a background page that execute script on current tab.
The script change elements on current tab by adding code to existing
elements to call function 'myFunction' defined at background page when
'onClick' events occur. The problem is that exception is thrown that
'myFunction' is not defined on current tab.
what is the best way to enable this interaction? to enable current page to
go to function defined on background page?
Thanks in advance!

What does the %= operator do?

What does the %= operator do?

What does the %= operator do, as shown in this example:
if (a > b)
{
a %= b;
}
What are its uses and is it commonly used?

iggrid page size drop down list showed and disappeared, it cannot be selected on IE10 and IE11

iggrid page size drop down list showed and disappeared, it cannot be
selected on IE10 and IE11

The iggrid shows up correctly. But it cannot be changed page size because
the drop down list showed after mouse click and disappeared when mouse
move to select.
I am using iggrid 13.1.20131.2217.
My feature code :
.Features( features =>
{
features.Sorting().Type(OpType.Local);
features.Paging().Type(OpType.Local).Inherit(true).PageSize(10);
features.Selection().Mode(SelectionMode.Row);
features.Filtering();
features.ColumnMoving().Mode(MovingMode.Deferred).AddMovingDropdown(true).MoveType(MovingType.Render);
})
IE shows error when mouse move over button and text box of page size change:
SCRIPT28: Out of stack space
File: infragistics.ui.editors.js, Line: 3307, Column: 13
Thanks in advance
Wilson

Saturday, 28 September 2013

nhibernate one-to-one mapping and not-null="false"?

nhibernate one-to-one mapping and not-null="false"?

How to create one-to-one relation using NHibernate where other side could
be a NULL? For example, I have a Banner entity that has a relation to
Image entity like this:
<class name="Banner" table="Banner">
<id name="Id" type="Int64" unsaved-value="0">
<generator class="native" />
</id>
<many-to-one name="Image" unique="true" column="ImageId"
not-null="false"/>
<!-- check: In the example this property was without inverse attribute
-->
<set name ="BannerSlideSet" fetch="subselect" inverse="true">
<key column="Banner_ID" foreign-key="FK_Banner_BannerSlide"
not-null="false" />
<one-to-many class="BannerSlide"/>
</set>
</class>
So, Image can be null for a Banner entity. I create one banner entity with
no image without any issues. In DB I have
--------------
ID | ImageId
--------------
1 | NULL
After that, I'm trying to create second Banner instance with no Image as
well and get the following error:
NHibernate.Exceptions.GenericADOException: could not insert:
[Domain.Entities.Banner][SQL: INSERT INTO Banner (ImageId) VALUES (?);
select SCOPE_IDENTITY()] ---> System.Data.SqlClient.SqlException:
Violation of UNIQUE KEY constraint 'UQ_Banner_7516F70DE6141471'. Cannot
insert duplicate key in object 'dbo.Banner'. The duplicate key value is
().
I guess, it happens because I have unique constraint on one-to-many
relation between banner and image entities and several Banner instances
can't have several NULL values in ImageId field. Question: how I would
achieve one-to-nullableone relation with in NHinerbate?
Thanks!

Pandas dataframe: drop columns whose name contains a specific string

Pandas dataframe: drop columns whose name contains a specific string

I have a pandas dataframe with the following column names:
Result1, Test1, Result2, Test2, Result3, Test3, etc...
I want to drop all the columns whose name contains the word "Test". The
numbers of such columns is not static but depends on a previous function.
How can I do that?
Thanks!

How to hide the "submit" button once a form is sent successfully?

How to hide the "submit" button once a form is sent successfully?

I'd like to hide the "submit" button of my form when the form is sent
successfully. I tried to add $('#submit').hide(2000); just after
$('.success').fadeIn(1000); but without success. Thanks
HTML:
<div class="block-right"> <h1>Formulaire de contact</h1>
<!-- CONTACT FORM-->
<div class="contact-form">
<form id="contactfrm" method="post" class="clearfix">
<div class="clearfix">
<input id="name" name="name" placeholder="Name"
type="text" value="">
<input id="email" name="email" placeholder="Email"
type="email" value="">
</div>
<textarea id="message" name="message"
placeholder="Message"></textarea>
<input type="submit" value="Envoyer" name="submit">
<p class="success" style="display:none">Your message has been sent
successfully.</p>
<p class="error" style="display:none">E-mail must be valid and message
must be longer than 100 characters.</p>
</form>
</div><!-- /.contact-form -->
</div> <!-- End DIV block-right -->
JS:
// Contact Form
$(document).ready(function(){
$("#contactfrm").submit(function(e){
e.preventDefault();
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var dataString = 'name=' + name + '&email=' + email + '&message=' +
message;
function isValidEmail(emailAddress) {
var pattern = new
RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
if (isValidEmail(email) && (message.length > 10) && (name.length > 1)){
$.ajax({
type: "POST",
url: "sendmessage.php",
data: dataString,
success: function(){
$('.success').fadeIn(1000);
}
});
} else{
$('.error').fadeIn(1000);
}
return false;
});
});

I am unable to see my website on Facebook Fanpage - URGENT

I am unable to see my website on Facebook Fanpage - URGENT

I have searched a lot over the internet but no success. So the problem I
have is I have added the website to facebook fanpage Tab but when I go to
facebook fanpage and click on the tab the page shown is blank. Here is the
facebook fanpage website tab link -
https://www.facebook.com/drdulitskymethod/app_640172482681632 (this is
blank). So can anyone please help me in resolving this issue. I need to
get this done as soon as possible.
Thanks

Friday, 27 September 2013

Joining tables in SQL. Linking by column in the from clause

Joining tables in SQL. Linking by column in the from clause

Linking multiple tables,
Is there a chance I will output a different result if I call the column
names to be linked in a different order in the FROM clause?
For example:
SELECT *
FROM tbl1
JOIN tbl2 on tbl1.colX = tbl2.colX
JOIN tbl3 on tbl2.colY = tbl3.colY
To be clear, in the next block I call tbl2.colX whereas above I called
tbl1.colX
SELECT *
FROM tbl1
JOIN tbl2 on tbl2.colX = tbl1.colX
JOIN tbl3 on tbl2.colY = tbl3.colY

Simple JS function using text inputs and parseInt, returns NaN

Simple JS function using text inputs and parseInt, returns NaN

Can anyone help me figure out why I keep getting a NaN result?
function showShares() {
var tot = document.getElementById('total').innerHTML;
var pri = document.getElementById('price').innerHTML;
var per = document.getElementById('percent').innerHTML;
var shar = parseInt(tot, 10) * parseInt(per, 10) / parseInt(pri, 10);
document.getElementById("shares").innerHTML=Math.round(shar);
}



<td><text id="price"><%= StockQuote::Stock.quote(current_user.fund1).last
%></text></td>
<td><text id="shares"></text></td>
<td><text id="percent">.50</text></td>



<p class="alignright1"><input type="text" id="total" size="8"></input>
<br><a href onclick="showShares()">here</a>



The stock quote is returning an integer in the cell ie. 25.38. it returns
the same NaN if I remove the embedded ruby and place a simple integer ie.
50. The same is true if I replace the input with a number.
Thank You

Integrating existing C code to Go. Convert unsigned char poiner result to []byte

Integrating existing C code to Go. Convert unsigned char poiner result to
[]byte

Here is a simple example:
package main
//#include <stdio.h>
//#include <strings.h>
//#include <stdlib.h>
/*
typedef struct {
unsigned char *data;
unsigned int data_len;
} Result;
Result *foo() {
Result *r = malloc(sizeof(Result));
r->data = (unsigned char *)malloc(10);
r->data_len = 10;
memset(r->data, 0, 10);
r->data = (unsigned char *)strdup("xxx123");
r->data_len = 6;
return r;
}
*/
import "C"
import (
"fmt"
// "unsafe"
)
func main() {
result := C.foo()
fmt.Printf("%v, %v, %v\n", result.data, string(*(result.data)),
result.data_len)
}
As a result i've got something like this
0x203970, x, 6
pointer to data, first character of data and the size. But how can i get
the actual data value, preferably as a []byte type to use it in go code?
In other words - how to convert unsigned char * to []byte?

Rotating a Linked List C

Rotating a Linked List C

I am currently solving sum problems of list and function and i came across
this question i.e rotate a linked list by k anti clockwise. Here is the
code for same
void rotate_k(struct list *node,int k)
{
int count=0;
struct list *knode,*ptr=node;
while(ptr!=NULL && count < k)
{
ptr=ptr->next;
count++;
}
knode=ptr;
while(ptr->next!=NULL)
{
ptr=ptr->next;
}
ptr->next =node;
node=knode->next;
knode->next=NULL;
}
Lets say if input is 1->2->3->4->5->6 and k=4.
The output should be 5->6->1->2->3->4 but the code gives the output
1->2->3->4->5 . Help needed :)

Switch handle multidimensional array. Unexpected result

Switch handle multidimensional array. Unexpected result

so I have a javascript function that pushes a multidimensional array value
to a parameter like so:
function mouseHandle(x,y){
for(var i=0; i<buttonPos.length; i++){
if(x>buttonPos[i][0] && x<buttonPos[i][2]){
if(y>buttonPos[i][1] && y<buttonPos[i][3]){
eventButton(buttonPos[i][4]);
};
};
};
};
This pushed buttonPos[i][4] to the eventButton function which is:
function eventButton(d){
switch(d){
case 0: // STARTBUTTON
alert("Button");
break;
default:
alert("NoButton");
};
};
The array is set in the drawButton function as so:
function drawButton(x,y,width,height,string,event){
xCenterButton=x+(width/2);
yCenterButton=y+(height/2);
ctx.fillStyle="rgba(242,255,195,1)";
ctx.fillRect(x,y,width,height);
ctx.rect(x,y,width,height);
ctx.fillStyle="rgba(0,0,0,1)";
ctx.stroke();
ctx.font="25px Arial";
fontSize = getFontSize();
centerNum = fontSize/4;
ctx.fillStyle="rgba(0,0,0,1)";
ctx.textAlign="center";
ctx.fillText(string,xCenterButton,yCenterButton+centerNum);
buttonPos.push([[x],[y],[x+width],[y+height],[event]]);
};
I then call that function in the menuStart function as so:
function menuStart(){
drawButton(getCenterX(100),getCenterY(50),100,50,"Start",0);
};
So the mouseHandle function DOES give the eventButton function a parameter
of 0 as expected (I alerted the 'd' parameter within the default case).
However it's as if the switch statement doesn't recognise the 0 as it uses
the default case and alerts 'NoButton'.
Any idea why this is not working?

strange phenomenon when use QFile with character ~

strange phenomenon when use QFile with character ~

i want to create a file in /home/username/ so i write some codes like this
#define CONFIG_FILE_PATH "~/.config/xmlfile
QFile file(CONFIG_FILE_PATH);
if (!file.open(QFile:ReadOnly | QFile::Text))
{
if (!file.open(QFile::WriteOnly | QFile::Text))
{
//print error message
}
else
{
//dosomething
file.close();
}
}
but when i run the program, i cannot find "xmlfile" i tried
sudo find / -name *xmlfile*
but found nothing and the program do not show any error messages.
is there some rules with the character ~ when using QFile?
Thanks in advance.

Thursday, 26 September 2013

test that a superclass method gets called from a subclass in ruby with Test::Unit and shoulda

test that a superclass method gets called from a subclass in ruby with
Test::Unit and shoulda

So, I've got a superclass (We'll call SuperClass) and two sub-classes from
it (say SubClassA and SubClassB)
Now SuperClass has a method called my_method which SubClassA has an
override for. But SubClassB does not.
I've tested that the version on the superclass works, and that the
overrideden version on SubClassA works... but I'd also like to add a unit
test that checks that SubClassB calls the version on the superclass.
I could just copy/paste the test from the superclass... or I could write a
test-module that's called from both... but if it's working tin the
superclass - all I really need to do is check that the superclass
my_method gets successfully called when I call it on the subclas...
but how do I test that?
This is what I tried:
should "call superclass version of my_method from the sub_class" do
@sub_class = SubClassB.new({})
rval = :whatever
SuperClass.any_instance.expects(:my_method).returns(rval)
assert_equal rval, @sub_class.my_method(:anything)
end
what that gives me is this error:
unexpected invocation: #<AnyInstance:SubClassA>.nat_record(:anything)
unsatisfied expectations:
- expected exactly once, not yet invoked:
#<AnyInstance:SuperClass>.my_method(any_parameters)
test: call superclass version of my_method from the sub_class.
(SubClassATest)
It looks like it has decided that the my_method has been called on an
instance of SubClassA (which it has) and that it therefore has not been
called on the SuperClass instance.
Is there a better way to check it calls the superclass method?

Thursday, 19 September 2013

Javascript Calculator with variables

Javascript Calculator with variables

I am looking for a javacript calculator whereby you can input your annual
spending on various departments (i.e. Restaurants, Movies, Toys &
Electronics), multiply all those totals by a percentage to reveal the
total for each line item and then total all the line items to show your
annual savings (assuming 0.5% is considered the savings percentage).
I have researched left, right, up, down, in and out - unable to find a JS
script that has these capabilities.
Any help would be greatly appreciated!

Updating with Postgresql

Updating with Postgresql

For the life of me, i've been working with this for so long, i've done
many updates that have worked, but for some reason, it won't work with
this bit of code:
If anyone can see anything wrong with it, please help me out. I'm a little
stuck:
if (isset($_POST['membership'])){
$accTypeID = getAccTypeID($db, $_POST['membership']);
$res = pg_query("SELECT * FROM accounts where username='"
.$_SESSION['username']. "'");
$rec = pg_fetch_row($res);
if($res > 0){
pg_query("UPDATE accounts SET paymentdate ='" .date("Y-m-d"). "',
accounttype_id=$accTypeID
WHERE username='" .$_SESSION['username']. "'");
$p->addContent('Purchasing has succeeded.');
}
}
I run this with my website and it says it works, but when i check my
database, nothing has been updated and my console produces this error:
pg_query(): Query failed: ERROR: syntax error at or near "WHERE"\nLINE 3:
WHERE username='anuj'

TFS 2010 - Building out Nuget using TFS results in TFS error: Package restore is disabled by default. To give consent, open the

TFS 2010 - Building out Nuget using TFS results in TFS error: Package
restore is disabled by default. To give consent, open the

I downloaded a standard copy of the Nuget web app and plan to use it in
our corporate environment. We use TFS 2010 to facilitate the builds from
our local machine. When I queue a new build on TFS for Nuget, the build
fails with the error:
Package restore is disabled by default. To give consent, open the Visual
Studio Options dialog, click on Package Manager node and check 'Allow
NuGet to download missing packages during build.' You can also give
consent by setting the environment variable 'EnableNuGetPackageRestore' to
'true'.
QUESTION: do I need to do what it says above on the TFS build server, or
on my local machine in Visual Studio? How can I resolve this issue? If
this is in fact an issue on the TFS build server, and the build server
doesn't allow to download missing packages, do I need to just download
those packages and check them into Source Control?
Here's the log file that resulted from the build, which also contains the
errors:
Build started 9/19/2013 12:19:08 PM. 1>Project
"F:\Builds\2\Nuget\NuGetGallery\Sources\NuGetGallery.sln" on node 1
(default targets). 1>ValidateSolutionConfiguration: Building solution
configuration "Release|Any CPU". 1>Project
"F:\Builds\2\Nuget\NuGetGallery\Sources\NuGetGallery.sln" (1) is building
"F:\Builds\2\Nuget\NuGetGallery\Sources\Website\Website.csproj" (2) on
node 1 (default targets). 2>RestorePackages:
"F:\Builds\2\Nuget\NuGetGallery\Sources.nuget\nuget.exe" install
"F:\Builds\2\Nuget\NuGetGallery\Sources\Website\packages.config" -o
"F:\Builds\2\Nuget\NuGetGallery\Sources\packages" 1>Project
"F:\Builds\2\Nuget\NuGetGallery\Sources\NuGetGallery.sln" (1) is building
"F:\Builds\2\Nuget\NuGetGallery\Sources\Facts\Facts.csproj" (3) on node 2
(default targets). 3>RestorePackages:
"F:\Builds\2\Nuget\NuGetGallery\Sources.nuget\nuget.exe" install
"F:\Builds\2\Nuget\NuGetGallery\Sources\Facts\packages.config" -o
"F:\Builds\2\Nuget\NuGetGallery\Sources\packages"
2>F:\Builds\2\Nuget\NuGetGallery\Sources.nuget\NuGet.targets(6,9): error :
Package restore is disabled by default. To give consent, open the Visual
Studio Options dialog, click on Package Manager node and check 'Allow
NuGet to download missing packages during build.' You can also give
consent by setting the environment variable 'EnableNuGetPackageRestore' to
'true'. [F:\Builds\2\Nuget\NuGetGallery\Sources\Website\Website.csproj]
2>F:\Builds\2\Nuget\NuGetGallery\Sources.nuget\NuGet.targets(6,9): error
MSB3073: The command
""F:\Builds\2\Nuget\NuGetGallery\Sources.nuget\nuget.exe" install
"F:\Builds\2\Nuget\NuGetGallery\Sources\Website\packages.config" -o
"F:\Builds\2\Nuget\NuGetGallery\Sources\packages"" exited with code 1.
[F:\Builds\2\Nuget\NuGetGallery\Sources\Website\Website.csproj] 2>Done
Building Project
"F:\Builds\2\Nuget\NuGetGallery\Sources\Website\Website.csproj" (default
targets) -- FAILED.
3>F:\Builds\2\Nuget\NuGetGallery\Sources.nuget\NuGet.targets(6,9): error :
Package restore is disabled by default. To give consent, open the Visual
Studio Options dialog, click on Package Manager node and check 'Allow
NuGet to download missing packages during build.' You can also give
consent by setting the environment variable 'EnableNuGetPackageRestore' to
'true'. [F:\Builds\2\Nuget\NuGetGallery\Sources\Facts\Facts.csproj]
3>F:\Builds\2\Nuget\NuGetGallery\Sources.nuget\NuGet.targets(6,9): error
MSB3073: The command
""F:\Builds\2\Nuget\NuGetGallery\Sources.nuget\nuget.exe" install
"F:\Builds\2\Nuget\NuGetGallery\Sources\Facts\packages.config" -o
"F:\Builds\2\Nuget\NuGetGallery\Sources\packages"" exited with code 1.
[F:\Builds\2\Nuget\NuGetGallery\Sources\Facts\Facts.csproj] 3>Done
Building Project
"F:\Builds\2\Nuget\NuGetGallery\Sources\Facts\Facts.csproj" (default
targets) -- FAILED. 1>Done Building Project
"F:\Builds\2\Nuget\NuGetGallery\Sources\NuGetGallery.sln" (default
targets) -- FAILED.
Build FAILED.
"F:\Builds\2\Nuget\NuGetGallery\Sources\NuGetGallery.sln" (default
target) (1) ->
"F:\Builds\2\Nuget\NuGetGallery\Sources\Website\Website.csproj"
(default target) (2) ->
(RestorePackages target) ->
F:\Builds\2\Nuget\NuGetGallery\Sources\.nuget\NuGet.targets(6,9):
error : Package restore is disabled by default. To give consent, open the
Visual Studio Options dialog, click on Package Manager node and check
'Allow NuGet to download missing packages during build.' You can also give
consent by setting the environment variable 'EnableNuGetPackageRestore' to
'true'. [F:\Builds\2\Nuget\NuGetGallery\Sources\Website\Website.csproj]
F:\Builds\2\Nuget\NuGetGallery\Sources.nuget\NuGet.targets(6,9): error
MSB3073: The command
""F:\Builds\2\Nuget\NuGetGallery\Sources.nuget\nuget.exe" install
"F:\Builds\2\Nuget\NuGetGallery\Sources\Website\packages.config" -o
"F:\Builds\2\Nuget\NuGetGallery\Sources\packages"" exited with code 1.
[F:\Builds\2\Nuget\NuGetGallery\Sources\Website\Website.csproj]
"F:\Builds\2\Nuget\NuGetGallery\Sources\NuGetGallery.sln" (default
target) (1) ->
"F:\Builds\2\Nuget\NuGetGallery\Sources\Facts\Facts.csproj" (default
target) (3) ->
F:\Builds\2\Nuget\NuGetGallery\Sources\.nuget\NuGet.targets(6,9):
error : Package restore is disabled by default. To give consent, open the
Visual Studio Options dialog, click on Package Manager node and check
'Allow NuGet to download missing packages during build.' You can also give
consent by setting the environment variable 'EnableNuGetPackageRestore' to
'true'. [F:\Builds\2\Nuget\NuGetGallery\Sources\Facts\Facts.csproj]
F:\Builds\2\Nuget\NuGetGallery\Sources.nuget\NuGet.targets(6,9): error
MSB3073: The command
""F:\Builds\2\Nuget\NuGetGallery\Sources.nuget\nuget.exe" install
"F:\Builds\2\Nuget\NuGetGallery\Sources\Facts\packages.config" -o
"F:\Builds\2\Nuget\NuGetGallery\Sources\packages"" exited with code 1.
[F:\Builds\2\Nuget\NuGetGallery\Sources\Facts\Facts.csproj]
0 Warning(s)
4 Error(s)
Time Elapsed 00:00:00.82

Strange behaviour, assigning undefined variable by refrence

Strange behaviour, assigning undefined variable by refrence

I am just exploring how Symbol Tables and Variable Containers work
together with references. And I found out that
<?php
$a = & $b;
?>
doesn't throw a Notice saying "Undefined variable: b in...", while
<?php
$a = $b;
?>
does.
Why?

Can you scrape data from a website with R

Can you scrape data from a website with R

Can you scrape data from:
http://www.ngx.com/?page_id=561
and
http://ets.aeso.ca/ets_web/docroot/Market/Reports/HistoricalReportsStart.html
with R?
I have tried to see if I could use RCurl/XML libraries in R but have not
had any success.

Accessing nested object in LinkedHashMap

Accessing nested object in LinkedHashMap

I'm trying to access an object in a LinkedHashMap, but get an
InvocationTargetException when I try to do it. The LinkedHashMap is the
result of a conversion from Json to a series of Java objects. The object
'List' contains every other element:
public class List{
private Clouds clouds;
private Number dt;
private String dt_txt;
private Main main;
private Rain rain;
private Sys sys;
private List weather;
private Wind wind;
}
The class also contains getters and setter. When I do the following:
for(LinkedHashMap l : ArrayList<LinkedHashMap> result.getList()) {
Number dt = (Number) l.get("dt");
}
I can access the variable dt, and it actually returns a value. However
when I try to access any other property like the 'Main' property like
this:
Main main = (Main) l.get("main");
I'll get an InvocationTargetException. Any thoughts, tips or tricks?
Edit:
Stacktrace:
09-19 14:37:59.448: E/AndroidRuntime(11192): FATAL EXCEPTION: main
09-19 14:37:59.448: E/AndroidRuntime(11192):
java.lang.ClassCastException:
com.google.gson.internal.LinkedHashTreeMap cannot be cast to
com.censored.weather.Main
09-19 14:37:59.448: E/AndroidRuntime(11192): at
com.censored.censored.VenloAppDelegate$GetWeatherTask.onPostExecute(VenloAppDelegate.java:305)
09-19 14:37:59.448: E/AndroidRuntime(11192): at
com.censored.censored.VenloAppDelegate$GetWeatherTask.onPostExecute(VenloAppDelegate.java:1)
09-19 14:37:59.448: E/AndroidRuntime(11192): at
android.os.AsyncTask.finish(AsyncTask.java:631)
09-19 14:37:59.448: E/AndroidRuntime(11192): at
android.os.AsyncTask.access$600(AsyncTask.java:177)
09-19 14:37:59.448: E/AndroidRuntime(11192): at
android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:644)
09-19 14:37:59.448: E/AndroidRuntime(11192): at
android.os.Handler.dispatchMessage(Handler.java:99)
09-19 14:37:59.448: E/AndroidRuntime(11192): at
android.os.Looper.loop(Looper.java:153)
09-19 14:37:59.448: E/AndroidRuntime(11192): at
android.app.ActivityThread.main(ActivityThread.java:5297)
09-19 14:37:59.448: E/AndroidRuntime(11192): at
java.lang.reflect.Method.invokeNative(Native Method)
09-19 14:37:59.448: E/AndroidRuntime(11192): at
java.lang.reflect.Method.invoke(Method.java:511)
09-19 14:37:59.448: E/AndroidRuntime(11192): at
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:833)
09-19 14:37:59.448: E/AndroidRuntime(11192): at
com.android.internal.os.ZygoteInit.main(ZygoteInit.java:600)

Install Node.js

Install Node.js

I'm completely new to node.js. By reading the documentation and tutorials,
I managed to download and install node.js on my windows.
How do I test it and make it work?
The file test.js is saved in the same directory as node.exe and contains:
console.log('Hello World');
Openning the command-line I typed:
$ node test.js
But nothing hapenns, just:
...

How can I compare objects using instanceof but Interface types (not passing exact class name.)

How can I compare objects using instanceof but Interface types (not
passing exact class name.)

public interface Component{}
public class AppMnger {
public void doWork(){
SomeComponent comp = new SomeComponent ();
AddComponentToList(comp);
}
public void AddComponentToList(Component compo){
componentList.add(compo);
}
/* Give me the component I want. */
public Component getComponent(Component comp){
for (Component component : getComponentList()) {
if (component instanceof comp) {
return component;
}
}
}
private ArrayList<Component> componentList = new ArrayList<Component>();
}
public class SomeComponent implements component {
public void MyMethod() {
appMnger.getComponent(this);
}
public void setAppMnger(AppMnger appm){
this.AppMnger = appm;
}
private AppMnger appm ;
}
In Above code AppMnger is having a list of components. Components are
communicating each other. So if one component want to know another
component instance it call the AppMnger getComponent(comp) method. But I
get an error when I use instanceof operator. I don't want each component
to want compare the list but I want to delegate that task to AppMnger
because he is the one who knows about components it created. Amy thought?

Wednesday, 18 September 2013

How do I install SOIL (Simple OpenGL Image Loader)?

How do I install SOIL (Simple OpenGL Image Loader)?

The SOIL website doesn't have any installation instructions. The file I
downloaded has no readme. I failed to find anything with Google.
I doubt g++ is going to check every directory on my computer to see if it
can find it. Is there a specific folder I'm supposed to put it in? Is
there a script I'm supposed to run?
I'm using Ubuntu.

What is the purpose of function scale_rt_power?

What is the purpose of function scale_rt_power?

Does anyone has a document about the kernel power saving scheduling and
what is the function of scale_rt_power?
Thank you,

C#, Print contents of a Panel

C#, Print contents of a Panel

In C#, I have a panel on a form, the contents of which I want to print.
Currently I can't view in print preview or print the contents, but the
border does.
protected override void OnPaint(PaintEventArgs e)
{
base.OnPaint(e);
panel1.CreateGraphics().DrawLines(new Pen(Color.Black),
new Point[]{new Point(10,10),new Point(50,50)});
}
private void PrintPanel(Panel pnl)
{
PrintDialog myPrintDialog = new PrintDialog();
PrinterSettings values;
values = myPrintDialog.PrinterSettings;
myPrintDialog.Document = printDocument1;
printDocument1.PrintController = new StandardPrintController();
printDocument1.PrintPage += new
System.Drawing.Printing.PrintPageEventHandler(printDocument1_PrintPage);
printPreviewDialog1.Document = printDocument1;
printPreviewDialog1.ShowDialog();
//printDocument1.Print();
printDocument1.Dispose();
}
void printDocument1_PrintPage(object sender, PrintPageEventArgs e)
{
Bitmap bmp = new Bitmap(panel1.Width, panel1.Height);
panel1.DrawToBitmap(bmp, new Rectangle(0, 0, panel1.Width, panel1.Height));
e.Graphics.DrawImage(bmp, panel1.Width, panel1.Height);
}

Java : use String[] or char[] ? [on hold]

Java : use String[] or char[] ? [on hold]

What are common scenarios when you would use a char[] and not a String[]
object? I know the textbook difference, I'm more interested in practical
use cases.

How do I use $rootScope in Angular to store variables?

How do I use $rootScope in Angular to store variables?

How do I use $rootScope to store variables in a controller I want to later
access in another controller? For example:
angular.module('myApp').controller('myCtrl', function($scope) {
var a = //something in the scope
//put it in the root scope
});
angular.module('myApp').controller('myCtrl2', function($scope) {
var b = //get var a from root scope somehow
//use var b
});
How would I do this?

HTML elements positon changes on browser resize

HTML elements positon changes on browser resize

when i resize my browser window all HTML elements positioning is changing.
I tried a lot for finding solution for it but i cann't.
Is their any trick in CSS to show same alignment for the elements when
browser is resized?

Getting Selection Start Index and Length from WPF RichTextBox

Getting Selection Start Index and Length from WPF RichTextBox

I've looked around and can find plenty of articles for how to set the
selection on RichTextBoxes but nothing on how to get the start index and
length of the selection. I see the TextSelection class has Start and End
properties but I have no idea how to just get the clear text index from
these.

how can I detect whether the android phone in Silent mode using air

how can I detect whether the android phone in Silent mode using air

I have seen this post how can I detect whether the android phone in Silent
mode programatically can any one please tell me whether there is any ane
to access the device ringing state whether the device is in
silent/vibration mode. I want to access the device seilent/vibration mode
in air mobile app.

Android WebDriver. XMLHttpRequest cannot load 'URL'. Origin 'URL' is not allowed by Access- Control-Allow-Origin. at null:1

Android WebDriver. XMLHttpRequest cannot load 'URL'. Origin 'URL' is not
allowed by Access- Control-Allow-Origin. at null:1

I am running my automated tests on Nexus 10 (Adndroid 4.2) using Selenium
WebDriver and Java. The error I face with is:
XMLHttpRequest cannot load 'URL'. Origin 'URL' is not allowed by Access-
Control-Allow-Origin. at null:1
This error doesn't occur for FireFox, Chrome, IE 10. But it always occur
for WebDriver on Android. Due to it Log in to the system is unavailable.
WebDriver is able to click, sendKeys and etc.
So the question is: Is any workaround exists to avoid this issue? May be
some settings which I should change for WebDriver? May be some one faced
with something like this before. I appreciate any suggestions.
I've tried apk 2.21.0 and 2.32.0.

jQuery mobile: Slider Widget

jQuery mobile: Slider Widget

I made a slider calculator with Jquery UI and then noticed it doesnt work
on touch devices, so I start over with Jquery Mobile.
For some reason I can update the value of the slider with the buttons, but
the slider itself won't move.
$("#plus1").on("mousedown", function () {
$('#slider-vertical').val(Number($('#slider-vertical').val())+25)
});
Please check: http://jsfiddle.net/MJ5WT/

Tuesday, 17 September 2013

touchstart event never be triggered on Android Chrome at the first time of page loading

touchstart event never be triggered on Android Chrome at the first time of
page loading

On Android Chrome, when you create a new tab and access to a page with the
content below, your touches to #touch div have never triggered touchstart
events. Once you reload the page, you can trigger the event. Why? and How
can I avoid this situation?
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>touch start on Android</title>
<style type="text/css">
#touch, #click {
position: relative;
left: 100px;
top: 100px;
width: 200px;
height: 200px;
border: solid 1px black;
}
</style>
</head>
<body>
<div id="touch">Touch</div>
<div id="click">Click</div>
<script type="text/javascript">
document.getElementById('touch').addEventListener('touchstart', function
() {
alert('touch');
}, false);
document.getElementById('click').addEventListener('click', function () {
alert('click');
}, false);
</script>
</body>
</html>
My environment is,
Nexus 7 (2013)
Android 4.30 build number JSS15Q
Chrome 29.0.1547.72 (WebKit version 537.36(@156722), JavaScript version V8
3.19.18.21)

How to group bash command into one function?

How to group bash command into one function?

Here is what I am trying to achieve. I want to run a sequence of commands
on that file, so for example
ls * | xargs (cat - | calculateforfile)
I want to run (cat | calculateforthisfile) on each of the file separately.
So basically, how to group a list of commands as if it is one single
function?

mismatch in member variables in C# class

mismatch in member variables in C# class

I am new to C#, and writing a piece of code to do some exercises. What
surprises me is that I can use undefined member variables in a C# class as
if they had been defined. Below is my code. In class Person, I only
defined "myName" and "myAge," but I can use the member variables "Name"
and "Age" without any issue. The code can be compiled and the executable
can be run. Can someone tell me why I can use "Name" and "Age" without
defining them? Many thanks,
C# code
====================================== using System;
namespace prj01
{
class Person
{
private string myName = "N/A";
private int myAge = 0;
public string Name
{
get
{
return myName;
}
set
{
myName = value;
}
}
public int Age
{
get
{
return myAge;
}
set
{
myAge = value;
}
}
public override string ToString()
{
return "Name = " + Name + ", Age = " + Age;
}
}
class Program
{
static void Main(string[] args)
{
// property
Console.WriteLine("Simple Properties");
Person person01 = new Person();
Console.WriteLine("Person details - {0}", person01);
person01.Name = "Joe"; // Why can I use "Name"?
person01.Age = 99; // Why is "Age" accessible and usable?
Console.WriteLine("Person details - {0}", person01);
Console.ReadLine();
}
}
}
======================================

How to escape HTML entities inside array in Ruby on Rails?

How to escape HTML entities inside array in Ruby on Rails?

I am trying to populate a select box with options from an array and escape
those options so currency symbols lile € get displayed rather than &euro;.
How can this be done in Ruby on Rails?
This is my function:
def options
array = []
array << ["&dollar;", "some value"]
array << ["&euro;", "some value"]
end
And this is the form:
<%= f.select(:format, f.object.options) %>
I tried things like array.html_safe but unfortunately it's not working.
Thanks for any help.

confused about android example code

confused about android example code

I'm looking over some code on the android developer's site and have a
quick question about the example show here -
http://developer.android.com/guide/components/fragments.html
In particular, I'm looking at this piece of code -
public static class DetailsActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getResources().getConfiguration().orientation
== Configuration.ORIENTATION_LANDSCAPE) {
// If the screen is now in landscape mode, we can show the
// dialog in-line with the list so we don't need this activity.
finish();
return;
}
if (savedInstanceState == null) {
// During initial setup, plug in the details fragment.
DetailsFragment details = new DetailsFragment();
details.setArguments(getIntent().getExtras());
getFragmentManager().beginTransaction().add(android.R.id.content,
details).commit();
}
}
What is the point of the second if statement -
if (savedInstanceState == null) {
I can't find any situation where this if statement wouldn't be true. I've
tested this code by adding an else statement and setting a breakpoint in
it. I could not get to that breakpoint no matter I tried. So why even
bother with an if statement? Why not leave it out all together?

IsMobileDevice returns False for Android (On some servers)

IsMobileDevice returns False for Android (On some servers)

I am developing a website using MVC 4 that has both Desktop and Mobile
views. I have created a DisplayModeProvider entry in my Global.asax that
allows iPhone's or Android mobiles.
I would like the user to be able to switch between Mobile and Desktop at
the click of a button. So I created a view that changes between Desktop
and Mobile as follows...
@If (ViewContext.HttpContext.GetOverriddenBrowser().IsMobileDevice) Then
@Html.ActionLink("Desktop View", "SwitchView", "Navigation", New With
{.Mobile = False, .ReturnUrl = Request.Url.PathAndQuery}, New With
{.rel = "external", .data_role = "button", .data_inline = "true"})
Else
@<a href="@Url.Action("SwitchView", "Navigation", New With {.Mobile =
True, .ReturnUrl = Request.Url.PathAndQuery})">Mobile View</a>
End If
... and this is the action...
Public Function SwitchView(Mobile As Boolean, ReturnUrl As String) As
RedirectResult
If Request.Browser.IsMobileDevice = Mobile Then
HttpContext.ClearOverriddenBrowser()
Else
HttpContext.SetOverriddenBrowser(If(Mobile,
BrowserOverride.Mobile, BrowserOverride.Desktop))
End If
Return Redirect(ReturnUrl)
End Function
This works perfectly on iPhone's.
But now I am testing with an Samsung Galaxy S3 (Android). On a Windows 7
IIS this works perfectly. However, when I run the same website on a 2003
Server IIS it does not work.
I think this is because the browser files
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Config\Browsers are
outdated, therefore IsMobileDevice returns False for Androids.
Questions:-
Is it possible to modify the code above to make Android's work? I am not
sure what I would change in the Action to allow this to work.
Alternatively, is it possible at project level to modify the browser files
so that Android's would return True for IsMobileDevice on a 2003 Server? I
don't want to update the browser definition files on the machine itself
because we distribute our website to dozens of different customers and a
project level solution would be preferred.

Sunday, 15 September 2013

Delete the uploded image file using ajax code

Delete the uploded image file using ajax code

I want to delete the images that are uploded one by one in php.
I used the following code for displaying the images.On clicking the delete
button the image gets deleted from the upload folder.
Code
ImageLap.tpl.php
foreach($mainfile as $files)
{
echo '<img src="'.$files.'" width="100" height="65">';
echo '<input type="hidden" value="'.$files.'"
name="delete_file" />';
echo '<input type="submit" value="Delete image" />';
}
ImageLap.php
if (array_key_exists('delete_file', $_POST))
{
$filename = $_POST['delete_file'];
if (file_exists($filename))
{
unlink($filename);
echo 'File '.$filename.' has been deleted';
}
}
This code is working well.But the page has to be refreshed on each file
deletion. I need a help to delete the files without refreshing the page.I
heard that ajax is used for this.But I don't have knowledge in ajax
Please do help me to implement ajax in this code.

non static variable cannot be referenced from static context?

non static variable cannot be referenced from static context?

I'm new to java and I have been exploring the different variable types.
Right now I am trying to determine is printed when I add 1 to a byte
variable of value 127 (the maximum value for a byte var). This is what my
code looks like:
public class vars {
byte b = 127;
byte c = 1;
public static void main(String[] args) {
System.out.println(b + c);
}
}
and on my System.out.println line I get the error message that my
non-static variables, b and c, cannot be referenced from a static context.
How should I fix this? Is there a better way to do this project in
general?
Thanks

Why do I see NSAutoresizingMaskLayoutConstraint when all UI Elements are set to setTranslatesAutoresizingMaskIntoConstraints = NO

Why do I see NSAutoresizingMaskLayoutConstraint when all UI Elements are
set to setTranslatesAutoresizingMaskIntoConstraints = NO

I am trying to debug a UI Layout and all the elements I have added in the
code are labelled with [self.element
setTranslatesAutoresizingMaskIntoConstraints:NO]; The only thing that is
set in XIB file is the background color of the view (one of many views in
a tabbed viewController.
When I look at the NSLog I am seeing the following:
*<UIWindow:0xc352370> - AMBIGUOUS LAYOUT
| *<UILayoutContainerView:0xc3651b0>
| | *<UINavigationTransitionView:0xc355b40>
| | | *<UIViewControllerWrapperView:0xbd3e250>
| | | | *<UILayoutContainerView:0xbd3da60>
| | | | | *<UITransitionView:0xbd46ed0>
| | | | | | *<UIViewControllerWrapperView:0xc09a450>
| | | | | | | *<UIView:0xbd51f40>
| | | | | | | | *<_UILayoutGuide:0xbd51fa0> - AMBIGUOUS
LAYOUT
| | | | | | | | *<_UILayoutGuide:0xbd50a10> - AMBIGUOUS
LAYOUT
| | | | | | | | *<UIButton:0xc064170> - AMBIGUOUS LAYOUT
| | | | | | | | | *<UIButtonLabel:0xc09d640>
| | | | | | | | *<UILabel:0xc073990> - AMBIGUOUS LAYOUT
| | | | | | | | *<UIButton:0xc0576a0> - AMBIGUOUS LAYOUT
| | | | | | | | | *<UIButtonLabel:0xc095290>
| | | | | | | | *<UIButton:0xc096640> - AMBIGUOUS LAYOUT
| | | | | | | | | <UIButtonLabel:0xc096820>
| | | | | | | | *<UIButton:0xc098b70> - AMBIGUOUS LAYOUT
| | | | | | | | | <UIButtonLabel:0xc098cb0>
| | | | | | | | *<UIButton:0xc09a4c0> - AMBIGUOUS LAYOUT
| | | | | | | | | <UIButtonLabel:0xc09a6d0>
| | | | | | | | *<UILabel:0xc09c9d0> - AMBIGUOUS LAYOUT
| | | | | | | | *<UILabel:0xc09cc60> - AMBIGUOUS LAYOUT
| | | | | | | | *<UIButton:0xc09ce00> - AMBIGUOUS LAYOUT
| | | | | | | | | <UIButtonLabel:0xc09d010>
| | | | | | | | *<UILabel:0xc0a25f0> - AMBIGUOUS LAYOUT
| | | | | | | | *<UIButton:0xc0a2800> - AMBIGUOUS LAYOUT
| | | | | | | | | <UIButtonLabel:0xc0a2a10>
| | | | | | | | *<UILabel:0xc0a5720> - AMBIGUOUS LAYOUT
| | | | | <UITabBar:0xc356c00>
| | | | | | <_UITabBarBackgroundView:0xbe28cc0>
| | | | | | | <_UIBackdropView:0xbe29100>
| | | | | | | | <_UIBackdropEffectView:0xbe296e0>
| | | | | | | | <UIView:0xbe29780>
| | | | | | <UITabBarButton:0xbd42000>
| | | | | | | <UITabBarSwappableImageView:0xbd41050>
| | | | | | | <UITabBarButtonLabel:0xbd43320>
| | | | | | <UITabBarButton:0xbd462e0>
| | | | | | | <UITabBarSwappableImageView:0xbd45d60>
| | | | | | | <UITabBarButtonLabel:0xbd45c70>
| | | | | | <UITabBarButton:0xbd47770>
| | | | | | | <UITabBarSwappableImageView:0xbd48a90>
| | | | | | | <UITabBarButtonLabel:0xbd486c0>
| | | | | | <UITabBarButton:0xbd4c0c0>
| | | | | | | <UITabBarSwappableImageView:0xbd4c220>
| | | | | | | <UITabBarButtonLabel:0xbd4aea0>
| | | | | | <UIImageView:0xbe29ed0>
| | <UINavigationBar:0xc06c4a0>
| | | <_UINavigationBarBackground:0xc05e720>
| | | | <_UIBackdropView:0xc357d70>
| | | | | <_UIBackdropEffectView:0xc3639a0>
| | | | | <UIView:0xc355470>
| | | | <UIImageView:0xc071980>
| | | <UINavigationItemView:0xc074c80>
| | | | <UILabel:0xc083730>
| | | <_UINavigationBarBackIndicatorView:0xc36edb0>
po [
(lldb) po [0xbd51fa0 constraintsAffectingLayoutForAxis:0]
<__NSArrayM 0xbd39190>(
)
(lldb) po [0xbd50a10 constraintsAffectingLayoutForAxis:0]
<__NSArrayM 0x1121f8f0>(
)
(lldb) po [0xc064170 constraintsAffectingLayoutForAxis:0]
<__NSArrayM 0xc0a14e0>(
<NSLayoutConstraint:0xc093aa0 H:|-(NSSpace(20))-[UIButton:0xc064170]
(Names: '|':UIView:0xbd51f40 )>,
<NSLayoutConstraint:0xc093b30 UIButton:0xc064170.width ==
UIButton:0xc0576a0.width>,
<NSLayoutConstraint:0xc093be0
H:[UIButton:0xc064170]-(20)-[UILabel:0xc073990]>,
<NSLayoutConstraint:0xc093c10 UILabel:0xc073990.width ==
UIButton:0xc0576a0.width>,
<NSLayoutConstraint:0xc096530
H:[UILabel:0xc073990]-(20)-[UIButton:0xc0576a0]>,
<NSLayoutConstraint:0xc096590 H:[UIButton:0xc0576a0]-(NSSpace(20))-|
(Names: '|':UIView:0xbd51f40 )>,
<NSAutoresizingMaskLayoutConstraint:0xc0af130 h=--& v=--&
H:[UIView:0xbd51f40(768)]>
)
(lldb) po [0xc09a4c0 constraintsAffectingLayoutForAxis:0]
<__NSArrayM 0xc36a0a0>(
<NSLayoutConstraint:0xc09c9a0 H:|-(<=0)-[UIButton:0xc09a4c0] (Names:
'|':UIView:0xbd51f40 )>,
<NSContentSizeLayoutConstraint:0xc0ad530 H:[UIButton:0xc09a4c0(110)]
Hug:250 CompressionResistance:750>
As you can see from po commands, I am getting
NSAutoresizingMasktLayoutContraints. I thought this shouldn't happen?
How can I ensure that I don't get this?

GridView with ListActivity instead of ListView

GridView with ListActivity instead of ListView

I have an app that pulls data from a database and puts it into a listview
via a ListActivity as well as a Cursor Loader.
The code is below:
public class PersonRecord extends ListActivity implements
LoaderManager.LoaderCallbacks<Cursor> {
private Uri addUri;
private TextView nameOfPerson, creditOfPerson;
private SimpleCursorAdapter adapter;
private String nameOfThePersonString;
// Used for menu deleting of a record
private static final int DELETE_ID = Menu.FIRST + 1;
// List for Listview
private ListView lv;
private static final String AUTHORITY =
"com.fthatnoise.borrow.me.contentprovider";
// ---------------------------------------------------
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.person_record);
this.getListView().setDividerHeight(2);
init(); // Initialize parameters and GUI
// Gets the name of the person that was sent from the Borrower List
// class
Bundle extras = getIntent().getExtras();
// Toast.makeText(this, nameOfThePersonString, Toast.LENGTH_SHORT)
// .show();
if (extras != null) {
addUri = extras
.getParcelable(BorrowMeContentProvider.CONTENT_ITEM_TYPE);
// Try-catch when the records are finished, this prevents the program
// from crashing (Pulling 0 from database)
try{
fillData(addUri);
} catch (Exception e)
{
Toast.makeText(this, "There are no more records for this
person", Toast.LENGTH_SHORT)
.show();
}
}
// Registers a content menu to the ListView
registerForContextMenu(getListView());
}
// ---------------------------------------------------
// Adding content menu to allow for the deletion of stored entries under
peoples names
@Override public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case (DELETE_ID):
// Gets the content for the assigned content menu - in this case the
listview
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
// Find the entry for the item currently clicked on
Uri uri = Uri.parse(BorrowMeContentProvider.CONTENT_URI +
"/" + info.id);
getContentResolver().delete(uri, null, null);
// Reload the list with new data based on the name sent over
// from the person credit screen
/*
* Removed filldata for now, seems to work without it even
though it crashes
* When removed it works fine but fails to refresh person record
* causes an error if all records are removed and person still
shows up in
* the record screen.
*/
try {
} catch (Exception e){
Toast.makeText(this, "There are no more records for this
person", Toast.LENGTH_SHORT)
.show();
}
return true;
}
return super.onContextItemSelected(item);
}
// ---------------------------------------------------
// Create Content Menu
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
// TODO Auto-generated method stub
super.onCreateContextMenu(menu, v, menuInfo);
//showDialog(DIALOG_SAB_PRIORITY_ID);
menu.add(0, DELETE_ID, 0, "Delete Record");
}
// ---------------------------------------------------
private void init() {
nameOfPerson = (TextView) findViewById(R.id.person_name);
creditOfPerson = (TextView) findViewById(R.id.person_credit);
}
// ---------------------------------------------------
// Loads record that was sent based on the ID
private void fillData(Uri uri) {
// Loads up the name of the person
String[] projection = { BorrowMeTable.COLUMN_NAME }; // Pulls only the
// name so far
Cursor databaseCursor = getContentResolver().query(uri, projection,
null, null, null);
if (databaseCursor != null) {
databaseCursor.moveToFirst();
nameOfThePersonString = databaseCursor.getString(databaseCursor
.getColumnIndexOrThrow(BorrowMeTable.COLUMN_NAME));
nameOfPerson.setText(nameOfThePersonString);
}
// Makes a raw query to the database in order to pull credit score for
// person being looked at.
ContentProviderClient client = getContentResolver()
.acquireContentProviderClient(AUTHORITY);
SQLiteDatabase dbHandle = ((BorrowMeContentProvider) client
.getLocalContentProvider()).getDbHandle();
Cursor cursor = dbHandle.rawQuery("SELECT sum("
+ BorrowMeTable.COLUMN_CREDIT_SCORE
+ ") AS creditcardtotal FROM " + BorrowMeTable.DATABASE_TABLE
+ " WHERE " + BorrowMeTable.COLUMN_NAME + "= \""
+ nameOfThePersonString + "\"", null);
cursor.moveToFirst();
int total = cursor.getInt(0);
cursor.close();
cursor.deactivate();
client.release(); // End of Credit Pull
// This is the formula to calc credit score.
// Everyone starts with 7, then it adds based on borrowed and returned
items.
int defaultScore = 7;
int cnt = 0;
cnt = defaultScore + total;
// This is the start of the credit evaluation system.
// Based on what the final numbers are, this will assign them a credit
score.
if (cnt >= 5 && cnt <= 6){
creditOfPerson.setText(cnt + " - Average");
creditOfPerson.setTypeface(null, Typeface.NORMAL);
}else if (cnt >= 7 && cnt <= 8){
creditOfPerson.setText(cnt + " - Good");
creditOfPerson.setTextColor(Color.MAGENTA);
creditOfPerson.setTypeface(null, Typeface.NORMAL);
}else if (cnt >= 2 && cnt <= 4){
creditOfPerson.setText(cnt + " - Bad");
creditOfPerson.setTextColor(Color.RED);
creditOfPerson.setTypeface(null, Typeface.NORMAL);
}else if (cnt >= 9){
creditOfPerson.setText(cnt + " - Fantastic");
creditOfPerson.setTextColor(Color.GREEN);
creditOfPerson.setTypeface(null, Typeface.NORMAL);
}else if (cnt <1){
// Stops showing the score if it drops below 1
creditOfPerson.setText("1 - Terrible");
creditOfPerson.setTextColor(Color.RED);
creditOfPerson.setTypeface(null, Typeface.BOLD);
}else if (cnt >= 10){
// Stops showing the score if it raises above 10
creditOfPerson.setText("10 - Wicked Awesome");
creditOfPerson.setTextColor(Color.GREEN);
creditOfPerson.setTypeface(null, Typeface.BOLD);
}
// End of credit score pull
// Loads the data for the rows of all items this person has borrowed
String[] from = new String[] { BorrowMeTable.COLUMN_ITEM,
BorrowMeTable.COLUMN_DATE, BorrowMeTable.COLUMN_BORROW_FLAG,
BorrowMeTable.COLUMN_RETURN_DATE,
BorrowMeTable.COLUMN_RETURN_FLAG, BorrowMeTable.COLUMN_IMAGE};
int[] to = new int[] { R.id.items_for_the_person_record,
R.id.borrowed_on_the_date, R.id.returned_on_the_date,
R.id.returned_on_the_day, R.id.returned_cond,
R.id.pic_of_item};
//getLoaderManager().initLoader(0, null, this); // This is where it
was originally
adapter = new SimpleCursorAdapter(this, R.layout.rows_people_records,
null, from, to, 0);
// The viewbinder that allows the adapter to display BLOB images
adapter.setViewBinder(new MyViewBinder());
setListAdapter(adapter);
// Here is where I attempt to load the custom view binder to load the
blob data
getLoaderManager().initLoader(0, null, this); // I have commented out
above and placed it here
}
// ---------------------------------------------------
@Override
public Loader<Cursor> onCreateLoader(int arg0, Bundle arg1) {
String mSelection = BorrowMeTable.COLUMN_NAME + "=?"; // SQL request
String[] selectionArgs = { nameOfThePersonString }; // The actual
// argument
String[] projection = { BorrowMeTable.COLUMN_ID,
BorrowMeTable.COLUMN_ITEM, BorrowMeTable.COLUMN_DATE,
BorrowMeTable.COLUMN_BORROW_FLAG,
BorrowMeTable.COLUMN_RETURN_DATE,
BorrowMeTable.COLUMN_RETURN_FLAG, BorrowMeTable.COLUMN_IMAGE};
CursorLoader cursorLoader = new CursorLoader(this,
BorrowMeContentProvider.CONTENT_URI, projection, mSelection,
selectionArgs, null);
return cursorLoader;
}
// ---------------------------------------------------
@Override
public void onLoadFinished(Loader<Cursor> arg0, Cursor arg1) {
adapter.swapCursor(arg1);
}
// ---------------------------------------------------
@Override
public void onLoaderReset(Loader<Cursor> arg0) {
adapter.swapCursor(null);
}
}
I would like to know if this can be done easily reusing the same code of
if i'll have to redo a bunch. I've looked at tutorials but i've seen
nothing that answers my question fully.
Thanks!

Why do I need a TestDriver when using Java?

Why do I need a TestDriver when using Java?

Today, I had my first Java lecture at the university and I heard a lot
about HelloWorld and a TestDriver. I somehow get the concept that the
TestDriver is the class that starts you program. But what is the advantage
of having a TestDriver? Why can't I just write a main method in my
HelloWorld class and start it from there?

Do something in jquery if element has exact property & value

Do something in jquery if element has exact property & value

I want to do something in jquery if my element has a given property & value.
This is what I'm trying that doesn't work:
if ($('.myElement').css('opacity','1')){
console.log('test');
}
What is the correct syntax for this?

Debug an specific Symfony2 bundle method

Debug an specific Symfony2 bundle method

I need to know if a specific bundle in Symfony 2.3 is been called when a
form is persisted, or better yet, see all the methods called before an
error message.
I'm using the Debug Component of Symfony2:
http://symfony.com/doc/current/components/debug.html, but I'm not seeing
the bundle listed, so I guess is not been executed, but I need to be sure
about it 'cause the bundle configuration is fine. All the unit tests of
that bundle pass ok, so the bundle is not the problem.
The bundle in question is VichUploaderBundle.
Thanks in advance.

Saturday, 14 September 2013

For loop iteration issue

For loop iteration issue

Hey so i have tried many variations of this code including using a scanf
function and every time it increments by 2 points instead of one. Here is
the code.
#include <stdio.h>
int main(void)
{
double nc;
for(nc = 0; getchar() != EOF; ++nc)
printf("%.0f\n", nc);
}
This is the output i get. the input i used was qwerty, and the outputs are
numbers 0-11 instead of 0-5 as expected.
q 0 1 w 2 3 e 4 5 r 6 7 t 8 9 y 10 11
one thought i has was that when i press enter, it is counted as a value
for getchar along with the character i enter and this causes the loop to
run through 2 iterations? can further explain this concept or provide
links to more information about it for me, thanks.

Ruby on Rails: form_for is not showing content inside

Ruby on Rails: form_for is not showing content inside

I'm trying to create a form so I can update user's content information,
but my form is not showing up.
My form in views/admin/dashboard/index.html.erb:
<% form_for @admin do |f| %>
... form content...
<% end %>
this is my controller in controllers/admin/dashboard_controller.rb
class Admin::DashboardController < ApplicationController
def index
@users = User.all
@admin = User.new
end
end
this is my model: models/admin.rb
class Admin < ActiveRecord::Base
belongs_to :user
end
Then in my users model: models/user.rb
class User < ActiveRecord::Base
has_many :admins
end

How to choose a specific paperclip image to be a "profile pic" for an object

How to choose a specific paperclip image to be a "profile pic" for an object

I currently have a Dog model which I have a has many association with my
asset model. My asset model is used for storing paperclip images in S3. I
would like to be able to choose one of the Dog's pictures to be the
"profile pic" for that dog. Right now I'm not sure how to do this.
app/models/dog.rb
class Dog < ActiveRecord::Base
attr_accessible :name, :description, :age, :protection,
:assets_attributes, :dog_titles_attributes, :dog_parents_attributes,
:movies_attributes, :profile_pic
has_many :assets
has_many :movies
has_one :profile_pic
has_many :dog_parents, :dependent => :destroy
has_many :parents, through: :dog_parents
has_many :dog_titles, :dependent => :destroy
has_many :titles, through: :dog_titles
accepts_nested_attributes_for :dog_titles, :allow_destroy => true
accepts_nested_attributes_for :dog_parents, :allow_destroy => true
accepts_nested_attributes_for :assets, :allow_destroy => true
accepts_nested_attributes_for :movies, :allow_destroy => true
validates_associated :assets
validates_uniqueness_of :name, case_sensitive: false
validates_presence_of :name
end
app/models/asset.rb
class Asset < ActiveRecord::Base
attr_accessible :dog_id, :parent_id, :litter_id, :asset, :category,
:caption, :_destroy
belongs_to :dog
belongs_to :parent
belongs_to :litter
has_attached_file :asset, :styles => {
large: "500x500>",
medium: "300x300#",
thumb: "100x100#",
square: '200x200#' }
validates_attachment_size :asset, :less_than => 5.megabytes
validates_attachment_content_type :asset, :content_type =>
['image/jpeg', 'image/png', 'image/jpg']
end
app/controllers/dogs_controller.rb
class DogsController < ApplicationController
before_filter :ensure_active_user, only: [:new, :create, :edit, :update,
:destroy]
def index
@dogs = Dog.find(:all)
end
def show
@dog = Dog.find(params[:id])
end
def new
@dog = Dog.new
@titles = Title.all
@parents = Parent.all
end
def create
@dog = Dog.new(params[:dog])
@titles = Title.all
respond_to do |format|
if @dog.save
format.html { redirect_to action: "index", notice: 'Dog was
successfully created.' }
else
format.html { render action: "new" }
end
end
end
def edit
@dog = Dog.find(params[:id])
@titles = Title.all
@parents = Parent.all
@assets = @dog.assets
end
def update
@dog = Dog.find(params[:id])
respond_to do |format|
if @dog.update_attributes(params[:dog])
format.html { redirect_to action: "index", notice: 'Dog updated.' }
else
format.html { render action: "edit" }
end
end
end
def destroy
dog = Dog.find(params[:id])
respond_to do |format|
if dog.destroy
format.html { redirect_to action: "index", notice: 'Dog updated.' }
else
format.html { redirect_to action: "index", error: "Delete wasn't
successful"}
end
end
end
end
app/views/dogs/edit.html.haml
= simple_form_for @dog, html: { multipart: true } do |f|
= f.input :name, input_html: { style: 'width:400px' }
= f.input :description, input_html: { style: 'width:600px; height:200px' }
= f.input :age, label: "Date of Birth",
input_html: { style: 'width:205px'},
as: :date, start_year: Date.today.year - 20,
end_year: Date.today.year,
order: [:day, :month, :year]
#picture-form-edit
%h4 Pictures
%ul
= f.simple_fields_for :assets do |p|
%li
= render 'asset_fields', :f => p
%p= link_to_add_fields "Add Photo", f, :assets
#movie-form-edit
%h4 Movies
%ul
= f.simple_fields_for :movies do |p|
%li
= render 'movie_fields', :f => p
%p= link_to_add_fields "Add Movie", f, :movies
#achievements-form-edit
%h4 Dog titles and achievements
= f.simple_fields_for :dog_titles do |p|
= render 'dog_title_fields', :f => p
%p= link_to_add_fields "Add Dog Titles", f, :dog_titles
#parents-form-edit
%h4 Parents
= f.simple_fields_for :dog_parents do |p|
= render 'dog_parent_fields', :f => p
%p= link_to_add_fields "Add Dog parents", f, :dog_parents
#submit-form
%p= f.submit "Edit Dog", class: "btn btn-primary"
app/views/dogs/_asset_fields.html.haml
%p.fields
- if f.object.asset?
= image_tag(f.object.asset.url(:thumb))
- else
= f.file_field :asset
= f.hidden_field :_destroy
= link_to_function "remove", "remove_fields(this)"
Additional I have tried adding a collection to my edit.html.haml to let
the user choose from the list of dogs, but this doesn't show images and
rather it just shows the image id.
Example:
%h4 Profile Pic
= f.collection_select :profile_pic, @assets, :id, :asset
What I want to do is let the user pick from the current pictures and
select one as their profile picture. I have been told using check boxes
with javascript would be a good way to do this, but I'm not sure how it
would be implemented. Would I add a check box to my
_asset_fields.html.haml?

deleteRecord does not remove record from hasMany

deleteRecord does not remove record from hasMany

When I call deleteRecord() on some of my hasMany relations, Ember Data
sends a (successful) DELETE request, but the record is not removed from
the view. I am displaying it using the render helper like this:
{{render "modules.list" modules}}
The interesting thing is that Ember Inspector reveals that after
deleteRecord() the corresponding object is <App.Module:ember1182:null> and
its parent is null, too. It's parent, however, still shows the record in
its hasMany (as <App.Module:ember1182:null>) When I reload the page and
then call deleteRecord(), it is removed from the view as expected.
It seems that deleteRecord() does not remove the record from the parent's
hasMany array. Oddly enough this works fine in other parts of my code. One
theory I have is that this has to do with the {render} helper, because
wherever I use that I have the same issue, but I am not sure if that's
what's causing the problem.
I am using the latest build of ember data (commit 2511cb1f77) although I
have had this problem even when I was still on 0.13. I thought upgrading
might solve the issue but it didn't.

best way to rewrite /profiles/1/edit/details towards /me/profile/details?

best way to rewrite /profiles/1/edit/details towards /me/profile/details?

Im trying to namespace several routes under a "me" /me section to have all
user profile/account based stuff under this namespace for more clean
routing.
What would be the best way to approach this? I find that rewriting the
default REST routing ( profiles/1/edit ) gives several issues like forms
not updating.
Routes
get "/me/profile" => "profiles#show", :as => :my_profile
get "/me/profile/:what" => "profiles#edit", :as => :my_profile_edit
post "/me/profile/:what" => "profiles#edit"
ProfilesController
def edit
@profile = current_user.profile
if ["basics", "location", "details", "photos"].member?(params[:what])
render :action => "edit/edit_#{params[:what]}"
else
render :action => "edit/edit_basics"
end
end
def update
@profile = current_user.profile
@profile.form = params[:form]
respond_to do |format|
if @profile.update_attributes!(params[:profile])
format.html { redirect_to :back, :notice => t('notice.saved') }
else
format.html { render action => "/me/profile/" + @profile.form }
end
end
end
If feels like above is going very bad against the REST principle. How
could I achieve the wanted results in a better way?

Retrieving value by like query from ms access database

Retrieving value by like query from ms access database

In the below code I have not got an error, but wanted districtname and
officename to retrieve first 6 characters from the database
So if district name is Lucknow City it only takes out Luckno
strSQL = "Select pincode from pincodes WHERE Districtname = '" & city & "'
AND officename = '" & area &"';

Desktop Application or web application

Desktop Application or web application

I want to make an application for school admission process. Which is the
best way to implement this, desktop application or web application. If i
choose java than is it possible to make desktop application in java. I
don't want to use .net for desktop application. Which is the best
framework for desktop application.

Generate non-repetitive number ever

Generate non-repetitive number ever

I have a SQLServer database and table Invoice (InvoiceID ,InvoiceNumber ,
Amount , Comment) in it , which InvoiceNumber is generated from [InvoiceID
from Invoice + CompanyId in CompanyTable] ,where InvoiceID and CompanyID
are auto increment , I want user to export data in xml file and then
import it when he want , but what if user exported all data and re-install
the program, then imported all data, then import a new record from the
program which InvoiceID and CompanyId are begin from 1 again, so
InvoiceNumber will repeat again , so how to avoid this , I have thought a
lot ,I thought about none-repetitive number for ever , I found out that if
I use timestamp for InvoiceNumber it will never be duplicated , but its
too long for InvoiceNumber and annoying for search, is there any other
solutions?

Friday, 13 September 2013

Reading in data from a file and using it to create a new object

Reading in data from a file and using it to create a new object

I have a class called Name like so.
public Name (String first, String last)
I want to read in a text file that contains names.
John Doe
Jane Doe
Then I want to create a new name object using the first word as the first
parameter and the second word as the second parameter.
How do I do this?

How to store extremely sensitive user data in Windows?

How to store extremely sensitive user data in Windows?

I'm working on desktop application, which generates a certificate to
identify user (let's call him Owner) in the future. I'd like to maximally
restrict access to this certificate, but I don't want Owner to enter
password for certificate.
Basically, I want certificate file be only accessible by elevated members
of Administrators group (better, if not, but I suspect it's not possible
otherwise), and my application, when it is running under Owner's account.
Is there any API in Windows to do this? .NET preferred, but not necessary.

Change GET's values

Change GET's values

I want to change my GET's values in PHP.
For example, I want to change this:
mypage.com/?lang=fr&page=home&...
To this:
mypage.com/?lang=en&page=home&...
I could make it with an str_replace and substr but I'm looking a less
stupid way.
I would like to use $_SERVER['QUERY_STRING'].
Thanks.

canvas scrolling background

canvas scrolling background

i want a scrolling background wherein if i tap, the direction of the
scrolling image changes to left and right if i tap again. I want it to
continue the position of the image when i tap or touch the screen. What my
code does is everytime i tap, the position of the scrolling background
doesnt begin on where it was when i tapped the screen. please help and
thanks in advance
@Override
public void onDraw(Canvas canvas) {
super.onDraw(canvas);
fromRect1 = new Rect(0, 0, bgrW - bgrScroll, bgrH);
toRect1 = new Rect(bgrScroll, 0, bgrW, bgrH);
fromRect2 = new Rect(bgrW - bgrScroll, 0, bgrW, bgrH);
toRect2 = new Rect(0, 0, bgrScroll, bgrH);
if(left == true){
if (!reverseBackroundFirst) {
canvas.drawBitmap(bgr, toRect1, fromRect1, null);
canvas.drawBitmap(bgrReverse, toRect2, fromRect2, null);
}
else{
canvas.drawBitmap(bgr, toRect2, fromRect2, null);
canvas.drawBitmap(bgrReverse, toRect1, fromRect1, null);
}
}else{
if (!reverseBackroundFirst) {
canvas.drawBitmap(bgr, fromRect1, toRect1, null);
canvas.drawBitmap(bgrReverse, fromRect2, toRect2, null);
}
else{
canvas.drawBitmap(bgr, fromRect2, toRect2, null);
canvas.drawBitmap(bgrReverse, fromRect1, toRect1, null);
}
}
if ( (bgrScroll += dBgrY) >= bgrW) {
bgrScroll = 0;
reverseBackroundFirst = !reverseBackroundFirst;
}
}
//***************************************
//************* TOUCH *****************
//***************************************
@Override
public synchronized boolean onTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN: {
left = !left;
invalidate();
break;
}
case MotionEvent.ACTION_MOVE: {
break;
}
case MotionEvent.ACTION_UP:
break;
}
return true;
}

Where to determine the height of a dynamically sized UICollectionViewCell?

Where to determine the height of a dynamically sized UICollectionViewCell?

I'm using UICollectionViewFlowLayout. My cells contain UILabels that
differ in height (number of lines).
It seems that the best way to get the cell height would be in the subclass
of UICollectionViewCell, because that is where I set the layout and have
access to intrinsic size of my views, BUT:
collectionView: layout: sizeForItemAtIndexPath: is called BEFORE the
collectionView: cellForItemAtIndexPath: delegate method, which means that
I need to know the cell height before I have the actual cell.
Everything I came up with so far seems too complicated, like starting with
fixed cell height, referencing actual height and reloading the data again
before the view loads. Is there a better way to do this?

DateTimePicker DialogResult.OK

DateTimePicker DialogResult.OK

I have following code now:
var picker = new DateTimePicker();
var form = new Form();
form.Controls.Add(picker);
var result = form.ShowDialog();
if (result == DialogResult.OK)
{
//Can´t acces this
}
if (result == DialogResult.Cancel)
{
//Do when Form closed
}
When the form appears, there´s only picker on it, no buttons. Now I can
only acces result == DialogResult.Cancel when I close the form. What I
need to do to access branch with result == DialogResult.OK

JPQL query convert to SQL query

JPQL query convert to SQL query

Is it possible to convert JPQL query to SQL and save this query to database?
I want to write JPQL queries when developing program. But whet will deploy
application to server I need compile querys to native SQL depends on DB.

Thursday, 12 September 2013

How to convert conversationIndex read using ews to some sortable string value?

How to convert conversationIndex read using ews to some sortable string
value?

I read that outlook uses conversationindex to show the hierarchy of emails
in a conversation. I am trying to implement the same thing in my
application. For this i am trying to get the conversationIndex to
implement a sorting functionality on the value(or value of particular
field) of conversationIndex. The problem is, i am not being able to
convert conversationindex to some sortable string value??

gmail via oauth SMTPSendFailedException(Authentication Required)

This summary is not available. Please click here to view the post.

How to test endpoints protected by csrf in node.js/express

How to test endpoints protected by csrf in node.js/express

I have implemented csrf (cross-site request forgery) protection in an
express like so:
...
app.use(express.csrf());
app.use(function (req, res, next) {
res.cookie('XSRF-TOKEN', req.csrfToken());
next();
});
...
This works great. Angularjs utilized the csrf token in all requests made
through the $http service. The requests that I make through my angular app
work great.
My problem is testing these api endpoints. I'm using mocha to run my
automated tests and the request module to test my api endpoints. When I
make a request to an endpoint that utilizes csrf (POST, PUT, DELETE, etc.)
using the request module, it fails, even though it correctly utilizes
cookies and such.
Has anybody else come up with a solution to this? Does anyone need more
information?
Example of test:
function testLogin(done) {
request({
method: 'POST',
url: baseUrl + '/api/login',
json: {
email: 'myemail@email.com',
password: 'mypassword'
}
}, function (err, res, body) {
// do stuff to validate returned data
// the server spits back a 'FORBIDDEN' string,
// which obviously will not pass my validation
// criteria
done();
});
}

Debug unhandled exceptions in WPF

Debug unhandled exceptions in WPF

I have a complicated WPF application that is used on some kind of a PA
system. It shows videos time to time and sometimes it does play music and
different text messages on the screen.
Structure is pretty straight forward. There is a server that has 2
methods. SetMessage("String"); and GetMessage("String");
Client once in 5 seconds connects to the server via HTTP binding on WCF
and pulls GetMessage(). Admin app connects to the server and calls
SetMessage().
In the App.xml.cs i have a handlers for CurrentDomain_UnhandledException,
OnDispatcherUnhandledException, TaskScheduler.UnobservedTaskException and
application.Current.DispatcherUnhnandledException. All of them suppose to
do nlog and continue operation.
There is one page in the App that uses Media element to play short videos.
Time to time after video was played I'm getting app crash.
EventType : clr20r3
P1 : Client.exe
P2 : 0.0.2.0
P3 : 5226863e
P3 : mscorlib
P5 : 4.0.0.0
P6 : 4ba1da6f
P7 : 219
P8 : 10
P9 : system.invalidoperaionexception
Now that's all cool. Yet the problems are:
Despite of 4 different exception handlers I'm still geting the exception
I'm not able to debug on the client computer
Error is random but happens after I played the video.
Code to stop and start the video is in Dispatcher.Invoke(new Action).
I might just leave the page and switch to another one before doing stop of
the video.
Looks like I'm just violating some access and trying to change something
in code from another thread.
Funny thing is that I tried to do ILDasm and find that P7:219 and there is
none in the code.
Is there any way to catch that freaking exception?
(I actually spend around 30 mins, trying to find any similar problems
here, but all the solutions already applied in my code)
Thanx for help.

WPF Scrollviewer starting position strange

WPF Scrollviewer starting position strange

i've got a window with 2 tabs each tab contain a Scrollviewer with same
exact properties
<ScrollViewer VerticalScrollBarVisibility="Auto"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
CanContentScroll="False">
<Grid HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
</Grid>
</ScrollViewer>
the difference now :
First Tab :
the grid row 0 contain a <WrapPanel> with couple <StackPanel> inside where
all controls are
the grid row 1 contain a <DataGrid> that fill the rest and has a minimum
height
Second Tab :
the grid row 0 contain a WrapPanel with couple <DockPanel> inside where
all controls are
the grid row 1 contain a <DataGrid> that fill the rest and has a minimum
height
The issue :
when i open the window there is too much control to be viewed all at once
so scroll bar or the <ScrollViewer> appear and this is perfect. BUT for
some awkward reason the second tab the scroll bar is NOT at the top but
like a bit more than 3/4 down the window. I wonder if anyone ha that issue
before and might know what i forgot there ?
what i've tried :
named the <ScrollViewer> in question and call on the form load
MyScroll.ScrollToTop(); didn't work but i guess it's because the control
doesn't exist yet.
I tried adding the GotFocus event to the <TabItem> but this baby get
triggered every time i also click a control within it. I actually found
that funny when i first click a <ComboBox> towards the end of the window.
After trying all that i found that starting on top when the <ScrollViewer>
is fist viewed is what i want and wondering if there is a way to do this
or if i am missing something.
Secondly i actually would like the <ScrollViewer> to scroll back to top
when the person navigate the <TabItem> my little go to top bug made me
realize that i actually like that.
User will rarely use more than 2 Tabs on that window so insanely perfomant
solution not required
Edit : I've found something. if i scroll back up my problematic tab and
then witch o another tab and come back, the scroll return EXACTLY where it
was bugged at.
Note that i have no events anywhere just simple bindings on for selected
value of combobox and text box. o yeah and datasource for the grid but
empty for both tab at this time.
I have 4 windows with the EXACT same formatting and only 1 tab out of 12
do that.
Edit #2 : here the full xaml
<syncfusion:ChromelessWindow
x:Class="prjSelection.Crating.frmCratingWestManufacturers"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:prjSelection.Crating"
Title="West Crating" Height="640" Width="1024"
UseNativeChrome="True"
xmlns:syncfusion="http://schemas.syncfusion.com/wpf"
syncfusion:SkinStorage.VisualStyle="Metro" ShowActivated="True"
WindowStartupLocation="CenterScreen">
<Grid>
<Grid Name="grdOverlay" HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" Background="Transparent"
Panel.ZIndex="99999999" Visibility="Hidden" MinWidth="150"
MinHeight="200">
<Rectangle HorizontalAlignment="Stretch"
VerticalAlignment="Stretch" Fill="White"
Opacity="0.8"></Rectangle>
<StackPanel HorizontalAlignment="Center" VerticalAlignment="Center">
<Label HorizontalAlignment="Stretch"
VerticalAlignment="Center" Content="Running Selection"
FontSize="18" FontWeight="Bold"></Label>
<syncfusion:SfBusyIndicator AnimationType="Gear"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
ViewboxHeight="150" ViewboxWidth="150"
VerticalContentAlignment="Center" />
</StackPanel>
</Grid>
<syncfusion:TabControlExt BorderThickness="0,2,0,0" Name="tab1"
AllowDrop="False" Background="White" EnableLabelEdit="False"
AllowDragDrop="False" CloseButtonType="Hide"
DefaultContextMenuItemVisibility="Hidden"
SelectOnCreatingNewItem="False" ShowTabItemContextMenu="False"
ShowTabListContextMenu="False" SnapsToDevicePixels="True"
TabPanelBackground="White" UseLayoutRounding="False"
TabScrollButtonVisibility="Auto" TabVisualStyle="None"
TabStripPlacement="Top" TabItemSelectedForeground="White"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
HorizontalContentAlignment="Stretch">
<syncfusion:TabItemExt Header="File" Width="150" IconMargin="0" >
<ScrollViewer VerticalScrollBarVisibility="Auto"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
CanContentScroll="False">
<Grid HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<WrapPanel Grid.Row="0" HorizontalAlignment="Stretch"
VerticalAlignment="Top">
<StackPanel>
<GroupBox Header="File Visual Properties"
VerticalContentAlignment="Stretch"
VerticalAlignment="Top"
Name="grpFileVisualProperties">
<WrapPanel Orientation="Horizontal">
<DockPanel Height="25"
LastChildFill="True" Width="220"
Margin="2,2,0,0">
<Label Content="File Color"
Height="25" Name="lblFileColor" />
<ComboBox
DisplayMemberPath="Value"
Height="25" ItemsSource="{Binding
Path=File.Color}"
Name="cboFileColor"
SelectedItem="{Binding
Path=File.SelectedColor,
Mode=TwoWay}" Width="120"
DockPanel.Dock="Right" />
<Label />
</DockPanel>
</WrapPanel>
</GroupBox>
<GroupBox Header="File Relative Properties"
VerticalContentAlignment="Stretch"
VerticalAlignment="Top"
Name="grpFileRelativeProperties">
<WrapPanel Orientation="Horizontal">
<DockPanel Height="25"
LastChildFill="True" Width="280"
Margin="2,2,0,0">
<Label Content="File Type"
Height="25" Name="lblFileType" />
<ComboBox
DisplayMemberPath="Value"
Height="25" ItemsSource="{Binding
Path=File.FileType}"
Name="cboFileType"
SelectedItem="{Binding
Path=File.SelectedFileType,
Mode=TwoWay}" Width="120"
DockPanel.Dock="Right" />
<Label />
</DockPanel>
</WrapPanel>
</GroupBox>
</StackPanel>
</WrapPanel>
<Grid Grid.Row="1" HorizontalAlignment="Stretch"
Name="grid2" VerticalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="10" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Button Content="Run Selection" FontSize="20"
FontStretch="Normal" Height="46"
Name="cmdFileSelection" Padding="0"
Width="198.162" Canvas.Left="793.838"
Canvas.Top="410" VerticalAlignment="Top"
Grid.Column="2" />
<syncfusion:SfDataGrid AllowGrouping="False"
AllowResizingColumns="False" AllowSorting="False"
ColumnSizer="Auto" FontSize="13"
GroupRowSelectionBrush="{x:Null}"
ItemsSource="{Binding Path=File.ResultGrid}"
Name="grdFileData" NavigationMode="Cell"
ShowColumnWhenGrouped="False"
VerticalContentAlignment="Stretch"
Canvas.Left="898.447" Canvas.Top="462"
HorizontalAlignment="Left" Grid.Column="0"
MinHeight="120" MinWidth="120" />
</Grid>
</Grid>
</ScrollViewer>
</syncfusion:TabItemExt>
<syncfusion:TabItemExt Header="Box" Width="150" IconMargin="0">
<ScrollViewer VerticalScrollBarVisibility="Auto"
HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
CanContentScroll="False">
<Grid HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<WrapPanel Grid.Row="0" HorizontalAlignment="Stretch"
Orientation="Horizontal">
<DockPanel Height="25" Width="375" Margin="2,2,0,0">
<Label Content="Height" Name="lblHeight"
Height="25" />
<ComboBox ItemsSource="{Binding
Path=Box.Height}" SelectedItem="{Binding
Path=Box.SelectedHeight, Mode=TwoWay}"
DisplayMemberPath="Value" Name="cboHeight"
Width="200" Height="25" DockPanel.Dock="Right"
/>
<Label />
</DockPanel>
</WrapPanel>
<Grid Grid.Row="1" HorizontalAlignment="Stretch"
VerticalAlignment="Stretch">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1*" />
<ColumnDefinition Width="10" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Button Content="Run Selection" FontSize="20"
FontStretch="Normal" Height="46"
Name="cmdBoxSelection" Padding="0" Width="198.162"
Canvas.Left="793.838" Canvas.Top="410"
VerticalAlignment="Top" Grid.Column="2" />
<syncfusion:SfDataGrid AllowGrouping="False"
AllowResizingColumns="False" AllowSorting="False"
ColumnSizer="Auto" FontSize="13"
GroupRowSelectionBrush="{x:Null}"
ItemsSource="{Binding Path=Box.ResultGrid}"
Name="grdBoxData" NavigationMode="Cell"
ShowColumnWhenGrouped="False"
VerticalContentAlignment="Stretch"
Canvas.Left="898.447" Canvas.Top="462"
HorizontalAlignment="Left" Grid.Column="0"
MinHeight="120" MinWidth="120" />
</Grid>
</Grid>
</ScrollViewer>
</syncfusion:TabItemExt>
</syncfusion:TabControlExt>
</Grid>