Thursday, 3 October 2013

Performing a union in LINQ

Performing a union in LINQ

I'm trying to get the union of these two queries but keep getting the
following error:
'System.Linq.IQueryable<AnonymousType#1>' does not contain a definition
for 'Union' and the best extension method overload
'System.Linq.ParallelEnumerable.Union<TSource>(System.Linq.ParallelQuery<TSource>,
System.Collections.Generic.IEnumerable<TSource>)' has some invalid
arguments
The linq queries look like this:
var g = from p in context.APP_PROD_COMP_tbl
where p.FAM_MFG == fam_mfg
group p by new
{
a_B_G = p.B_G,
a_MFG = p.MFG,
a_PRODUCT_FAM = p.PRODUCT_FAM,
};
var q = from p in context.APP_COMP_tbl
where p.FAM_MFG == fam_mfg
group p by new
{
a_B_G = p.a_B_G,
a_MFG = p.a_MFG,
a_PRODUCT_FAM = p.a_PRODUCT_FAM,
};
var data = q.Union(g);
I've tried using IEnumerable around the queries, but it still didn't work.
Not really sure where I'm going wrong at this point, although admittedly
LINQ isn't something I've had a ton of exposure to.

Wednesday, 2 October 2013

div show / hide horizontal

div show / hide horizontal

i used below source code for show / hide div, how to move horizontal.
demo link: http://papermashup.com/demos/jquery-show-hide-plugin/
(function ($) { $.fn.showHide = function (options) {
//default vars for the plugin
var defaults = {
speed: 1000,
easing: '',
changeText: 0,
showText: 'Show',
hideText: 'Hide'
};
var options = $.extend(defaults, options);
$(this).click(function () {
$('.toggleDiv').slideUp(options.speed, options.easing);
// this var stores which button you've clicked
var toggleClick = $(this);
// this reads the rel attribute of the button to determine which
div id to toggle
var toggleDiv = $(this).attr('rel');
// here we toggle show/hide the correct div at the right speed
and using which easing effect
$(toggleDiv).slideToggle(options.speed, options.easing, function() {
// this only fires once the animation is completed
if(options.changeText==1){
$(toggleDiv).is(":visible") ? toggleClick.text(options.hideText)
: toggleClick.text(options.showText);
}
});
return false;
});
};
})(jQuery);

TaglibSharp doesn't do anything

TaglibSharp doesn't do anything

I have a method to replace something in name of the music's artist id3
tag. I'm using taglibSharp and this is my code:
public static void TagArtistRename(this FileInfo file, string from, string
to, bool UseRegex = true)
{
TagLib.File f = TagLib.File.Create(file.FullName);
for (int i = 0; i < f.Tag.Performers.Count(); i++)
{
if (UseRegex)
{
f.Tag.Performers[i] = Regex.Replace(f.Tag.Performers[i], from,
to);
}
else
{
f.Tag.Performers[i] = f.Tag.Performers[i].Replace(from, to);
}
}
f.Save();
}
and here I call my code:
static void Main(string[] args)
{
string file = Console.ReadLine();
file = file.Replace("\"", "");
new FileInfo(file).TagArtistRename(" (www.Downloadha.com)", "", false);
TagLib.File f = TagLib.File.Create(file);
foreach (var item in f.Tag.Performers)
{
Console.WriteLine(item);
}
Console.ReadLine();
}
the code runs without any exceptions but in console, it'll write the old
artists names and also the file's metadata doesn't change.

Open a new browser for a copied spreadsheet

Open a new browser for a copied spreadsheet

I need to open a new browser after I copied my original spreadsheet, and
add the copied spreadsheet to the new browser, so user can edit the copied
spreadsheet and download or email their edits. I'm able to do the copy
part but not the new browser part
Thanks

Why does new Date() and Date.parse treat ISO-8601 strings different?

Why does new Date() and Date.parse treat ISO-8601 strings different?

I have this test date 2013-09-15T11:09:00 Depending on if I use Date.parse
and new Date the outcome will be different, but the UTC is same
Date.parse("2013-09-15T11:09:00")
Sun Sep 15 2013 11:09:00 GMT+0200 (W. Europe Daylight Time)
new Date("2013-09-15T11:09:00");
Sun Sep 15 2013 13:09:00 GMT+0200 (W. Europe Daylight Time)
If i add UTC both output same time and same UTC, a bug in Emacs standard? :D
new Date("2013-09-15T11:09:00+02:00");
Sun Sep 15 2013 11:09:00 GMT+0200 (W. Europe Daylight Time)
Date.parse("2013-09-15T11:09:00+02:00");
Sun Sep 15 2013 11:09:00 GMT+0200 (W. Europe Daylight Time)

Tuesday, 1 October 2013

Prepared statement security while fetching

Prepared statement security while fetching

I just don't get it. How is a prepared statement more safe than a
non-prepared statement for fetching data. I am not talking about writing
to the database, only fetching data. I cant see how userFname and
userLname is any more safe than userEmail and userPassword. Thanks in
advance.
$stmt = $mysqli->stmt_init();
if ($stmt->prepare("SELECT userFname, userLname FROM users WHERE
userEmail = ? and userPassword = ?")) {
$stmt->bind_param("ss", $userEmail, $userPassword);
$stmt->execute();
$stmt->bind_result($userFname, $userLname);
while ($stmt->fetch()) {
//Remember first name, last name, and email
$_SESSION['Email']=$userEmail;
$_SESSION['Fname']=$userFname;
$_SESSION['Lname']=$userLname;
$stmt->close();
//go to dashboard page
header ("location: dashboard.php");
}
$error2="Email and Password do not match, please try again.";
}

Algorithm for decision tree in continuous time

Algorithm for decision tree in continuous time

I'm attempting to build a fairly simple AI that has an input of 3 discreet
variables and is trying to predict a discreet output. This seems fairly
simple using an entropy calculation if you have a complete data set to
analyze beforehand. However, the program I am writing will be presented
one piece of data at a time and will have to learn to play a game as the
data is presented (eg. Playing a poker game or Rock Paper Scissors). How
would I be able to construct a tree on the fly as the data is received one
row at a time?
Thank you

Questions about netatalk log file

Questions about netatalk log file

Hello I'm using netatalk 3.0.4 on my system to allow for AFP connections.
The log file produced in /var/log/netatalk.log is 469.6GB...! This is
chewing data on my drive and making backups hard to manage.

I can't find any references in the official manual about limiting logs.


My questions
If I delete this file will it break netatalk?
What can I do to limit the log output of netatalk?

Solve congruence equation

Solve congruence equation

Solve the following congruence
$$20x\equiv12 \mod72$$
My work:
$(20, 72) = 12 = d\\ a' = 20/12\\ b' = 12/12 = 1\\ n' = 72/12 = 6$
$(20/12)x\equiv1\mod6$.
and now I'm stuck because of $20/12$.... Is it possible to have a rational
number for $a'$?

Monday, 30 September 2013

Ubuntu 13.04 numlock ignored on laptop

Ubuntu 13.04 numlock ignored on laptop

I have a full keyboard on my laptop with a separate numeric keypad.
The numlock is ignored when I press shift. So I have to set
system settings -> keyboard -> layout settings -> options -> miscellaneous
compatibility options -> shift with numeric keypad keys works as in ms
windows = ticked
I don't have to do this on my desktop though. The numlock behaves as it
should. Any ideas whats going on?

How much has "True North" shifted in the last few years and would this effect aeronautics=?iso-8859-1?Q?=3F_=96_skeptics.stackexchange.com?=

How much has "True North" shifted in the last few years and would this
effect aeronautics? – skeptics.stackexchange.com

I was talking to a contractor at a major U.S. airport, a Project Manager
who told that they were moving the runways due to the shifting of 'True
North'. I have heard that the poles have shifted even …

c# Listbox string with attached int value

c# Listbox string with attached int value

Ok, this is hard to explain, I will try my best to be clear:
I have several hundred "string" items where each one may take you to one
of 13 different forms. Instead of doing something like:
if (string == string) goto form1
hundreds of times I was hoping to do something like the following:
The user could care less which form comes up and does not need to know,
they just click on the string object and it takes them to the correct
form.
I think it would be easy if each string object had an associated INT value
and then I go to the appropriate form instead of doing all of the string
processing and comparison.
I do not see a way to do this with listbox. Is there a different structure
I should use, or a work around to make this work with listbox?
Thanks for any help.

uxNotification. How to destroy a notification window?

uxNotification. How to destroy a notification window?

I use uxNotification plugin in my application. In the sourcecode I
configured it with a property destroyAfterHide set to true and added
additional property closeAction set to destroy. However, after I click on
the close button and do win.destroy() manually, alert(win) still shows an
object, but not undefined or null as expected.

Sunday, 29 September 2013

Rotate Puzzle and find Word

Rotate Puzzle and find Word

So I have a puzzle.
I need to rotate that puzzle 90 degrees and use a command such as:
lr_occurrences(puzzle, word)
in order to scan the rotated puzzle from 'left to right' and see how many
times a certain word comes up in the puzzle from 'left to right'.
and then I have to print out an integer of how many times it did come in
the rotated puzzle from left to right.

Empty results when using $row[$variable] with LEFT JOIN in PHP

Empty results when using $row[$variable] with LEFT JOIN in PHP

I'd like to begin by saying that this is my first question here at stack
and I apologize in advance if this question has been answered before,
however I have been so far unable to find an answer or fix it myself.
I am trying to use the SELECT function in a php file to run a basic
report. I wrote the SQL in PHPMyAdmin and used the convert-to-php button
to do just that. What I get is the following:
SELECT
l.id AS 'ID',
l.type AS 'Type',
l.state AS 'State',
l.won_at AS 'Won',
l.lost_at AS 'Lost',
l.cancelled_at AS 'Cancelled',
l.created_at AS 'Created',
l.source AS 'Source',
u.first_name AS 'Owner First Name',
u.last_name AS 'Owner Last Name'
FROM `leads` AS l
LEFT JOIN `users` AS u ON
(u.`id` = l.`owner_id`)
LEFT JOIN `regions` AS rg ON
(rg.`id` = l.`region`)
WHERE l.`state` IS NOT NULL
[...]";
When I put this into a PHP document it looks like this:
<?php
// Create connection
$con=mysqli_connect("localhost","root","pass","database");
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// And now for the good stuff
$result = mysqli_query($con,"SELECT
l.id AS 'LeadID',
l.type AS 'Type',
l.state AS 'State',
l.won_at AS 'Won',
l.lost_at AS 'Lost',
l.cancelled_at AS 'Cancelled',
l.created_at AS 'Created',
l.source AS 'Source',
u.first_name AS 'First Name',
u.last_name AS 'Last Name'
FROM `leads` AS l
LEFT JOIN `users` AS u ON
(u.`id` = l.`owner_id`)
WHERE l.`state` IS NOT NULL
");
echo "<table border='1'>
<tr>
<th>Test1</th>
<th>Test2</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row["$LeadID"] . "</td>";
echo "<td>" . $row["$l.type"] . "</td>";
echo "</tr>";
}
echo "</table>";
mysqli_close($con);
?>
What seems to be happening is that I am able to create the table with no
issue only when there is only one database being selected, and when I use
LEFT JOIN, I have so far been unable to find a way to change the
$row["$variable"] input to something that will work.
I know that the data is there and I know that the connection works, it's
just the LEFT JOIN that is giving me a bit of trouble.
Any help on this would be greatly appreciated!

Aggregate function creates unwanted vector within data frame

Aggregate function creates unwanted vector within data frame

I've been experiencing a strange problem with creating dataframes within a
function. However, using the same method outside of a data.frame works
fine!
Here is the basic function, I use it to calculate the mean, standard
deviation and standard error for a data set:
aggregateX<- function(formula, dataset){
output<-aggregate(formula, dataset, mean) #calculate mean
sdev<-aggregate(formula, dataset, sd) #calculate sd
output$sd<-sdev[length(sdev)] #place sd in same data.frame
output$se<-output$sd/sqrt(max(as.numeric(dataset$P))) #calculate se
names(output$sd)<-"sd";names(output$se)<-"se" #attatch correct names
return(output)
}
The function works but has a strange method of combining the data.frame as
an output. The first variable (mean) is formatted correctly, but both the
standard deviation and standard error are structured as a vector within
the dataframes first row.
i.e. when you view the output in RStudio it looks something like this
http://imgur.com/C7IaGG6
This wouldn't matter, but ggplot2 runs into some dificulty when trying to
process this unusual data.frame. Any advice on how to form the data.frame
without the strange vector would be much appreciated.
Many thanks.

intellij java execute client and server from same project

intellij java execute client and server from same project

Following on from the answer to: If I am creating a simple client server
application in IntelliJ, how should this work? as I don't have enough
reputation to continue the thread.
When I right-click on the class containing the main() method and select
"run" the public class is added to IntelliJ's run configurations (the
dropdown list to the left of the green arrow on IntelliJ's button bar) and
I can choose "Edit Configurations" from this dropdown to change the
command line arguments. I can run either client or server by putting
"client" or "server" as the argument. How do I run the server and then the
client classes from the same project? Do I need two main() methods, one in
each class?
import java.io.IOException;
public class serversocket {
public static void main(String args[]) throws IOException {
System.out.println(args[0]); //debug
if (args[0] == "client") {
runClient();
} else if (args[0] == "server") {
runServer();
} else {
System.out.println("no arguments.");
}
}
private static void runClient() throws IOException {
System.out.println("Client running..."); //test
}
private static void runServer() throws IOException {
System.out.println("Server running..."); //test
}

Saturday, 28 September 2013

batch file to replace a character in a txt file

batch file to replace a character in a txt file

I have .txt files (1000's) that look similar to the below example. I MUST
do this in a Dos.bat file, no options (it will be called by other .bat
files) (running windows 7 with no option to install or download any other
files or programs). The files can be generally 30k in size. I need to
replace the $'s characters with a carriage return. There will be as many
as 2-3 hundred $'s characters in each file so I cannot parse out the $'s
(unless I am missing something).
It seems so simple, but I have searched diligently trying to do this. I
found an example somewhere, but it appears to be limited to 8k max. files.
(see end of question)
The patterns of commas and words inside the files change with each file.
The only constant is the $ where there should be a new line. Example:
ORIGINAL FILE: $ENTRY,1,423-6823,"FILTER ASSEMBLY,
DAVCO",A,,1,2,,,,,,@FIELD,SUGG_QTY,1$ENTRY,2,423-6939,"FILTER, FUEL -
SPIN-ON",A,,2,3,,,,,,@FIELD,SUGG_QTY,1$ENTRY,3,423-3143,"MOUNT PLATE,
FILTER ASSEMBLY",1,,1,4,,,,,,$ENTRY,4,698-9393,"HOSE ASSEMBLY, #16 X
112""",1,,1,5,,,,,,$ENTRY,5,418-6146,"HOSE ASSEMBLY, #16 X
118""",1,,1,6,,,,,,$ENTRY,6,408-2841,"HOSE ASSEMBLY, #16 X
40""",1,,1,7,,,,,,$ENTRY,7,412-7996,"HOSE ASSEMBLY, #12 X
40""",1,,1,8,,,,,,$ENTRY,8,400-2483,"ELBOW, #16 FJ X 90 deg. X #16 MJ -
SWIVEL",3,,1,9,,,,,,$ENTRY,9,N.P.N.,FILTER MOUNT [FURNISHED WITH
ENGINE],A,,1,10,,,,,,$ENTRY,10,423-6822,"FILTER,
FUEL",A,,1,11,,,,,,@FIELD,SUGG_QTY,2$ENTRY,11,400-2481,"ELBOW, #12 FJ X 90
deg. X #12 MJ - SWIVEL",1,,1,12,,,,,,
and so on, maybe 30-40k in size.
The file should look like this when the $'S are removed and replaced with
a carriage return in txt file (without the extra line between each
line--it would not let me post without that extra line):
ENTRY,1,423-6823,"FILTER ASSEMBLY, DAVCO",A,,1,2,,,,,,@FIELD,SUGG_QTY,1
ENTRY,2,423-6939,"FILTER, FUEL - SPIN-ON",A,,2,3,,,,,,@FIELD,SUGG_QTY,1
ENTRY,3,423-3143,"MOUNT PLATE, FILTER ASSEMBLY",1,,1,4,,,,,,
ENTRY,4,698-9393,"HOSE ASSEMBLY, #16 X 112""",1,,1,5,,,,,,
ENTRY,5,418-6146,"HOSE ASSEMBLY, #16 X 118""",1,,1,6,,,,,,
ENTRY,6,408-2841,"HOSE ASSEMBLY, #16 X 40""",1,,1,7,,,,,,
ENTRY,7,412-7996,"HOSE ASSEMBLY, #12 X 40""",1,,1,8,,,,,,
ENTRY,8,400-2483,"ELBOW, #16 FJ X 90 deg. X #16 MJ - SWIVEL",3,,1,9,,,,,,
ENTRY,9,N.P.N.,FILTER MOUNT [FURNISHED WITH ENGINE],A,,1,10,,,,,,
ENTRY,10,423-6822,"FILTER, FUEL",A,,1,11,,,,,,@FIELD,SUGG_QTY,2
ENTRY,11,400-2481,"ELBOW, #12 FJ X 90 deg. X #12 MJ - SWIVEL",1,,1,12,,,,,,
I can do it on small files with the following code (found this on some
site). it works perfectly, BUT when the file size reaches about 9k it
fails and only returns the first line.
For /f "tokens=1,* delims=$" %%a in (testfile.txt) Do (
Echo.%%a>>out.txt
If not "%%b"=="" Call :change %%b)
GoTo :EOF
:change
For /f "tokens=1,* delims=$" %%a in ("%*") Do (
Echo.%%a>>out.txt
If not "%%b"=="" Call :change %%b)
GoTo :EOF
any help is greatly appreciated.

Android services - Sockets and streaming from one service to another on another phone

Android services - Sockets and streaming from one service to another on
another phone

To put things simply, I'm writing a video chat application that's supposed
to connect say, two Android phones. So far, I've managed to negotiate
interactions between clients, until the point I've reached the part where
I'm supposed to do the streaming of video (and later audio) data between
the clients.
The problem is as follows:
I am trying to implement a service that will, once a person has decided to
contact someone, be started from a ChatActivity, and that will negotiate
streaming between the two clients, making the sockets and the data going
between them completely independent of the events going on within the
ChatActivity, except for the moment the conversation is over, where the
activity is terminated for good, and with it the service.
However, my concern comes from the point that if the service terminates
the sockets mid-conversation, I have the problem of having to renegotiate
streaming between client and client. As is probably obvious, my knowledge
of android services is limited, at best, and any advice on the subject is
welcome
My questions are:
Is it doable to create a service that will, bar unexpected crashes due to
outside influences, keep such a connection active and running regardless
of how many times the activity that displays the video from the streaming
(ChatActivity) is destroyed and created?
Should I be going with a bound service or a started service for this, or
some hybrid of the two?
If I were to somehow create a pair usable stream of video data from the
service, one via internet connection other via camera, would I be able to
send them back to the activity, and keep reconnecting them to the
components, regardless of how many times they get destroyed and created
during the lifecycle?
Despite my efforts, I haven't managed to find any examples of anything
similar, if anyone has come across code that does some similar
socket/service juggling, I'd be most grateful for directions.

How do I stop GitX asking me for my SSH key password?

How do I stop GitX asking me for my SSH key password?

In order to let myself log into two different Heroku accounts I'm using
.git/config
[core]
repositoryformatversion = 0
filemode = true
bare = false
logallrefupdates = true
ignorecase = true
[branch "master"]
[remote "heroku"]
url = git@myrepo:myrepo.git
fetch = +refs/heads/*:refs/remotes/heroku/*
[remote "origin"]
url = git@github.com:peternixey/myrepo.git
fetch = +refs/heads/*:refs/remotes/origin/*
and ~/.ssh/config:
Host myrepo
HostName heroku.com
IdentityFile ~/.ssh/myrepo
IdentitiesOnly yes
GitX doesn't seem to be able to handle this

GitX doesn't seem to be picking up the correct key for the account. It
keeps trying to use id_rsa.pub when the correct key is myrepo.pub. There
is also a passphrase on the RSA key itself.
This is GitX(l) (as in L for Lima) and it's basically unusable in the
current configuration, how can I stop the password demands?

Turning a random choice answer to and if statment

Turning a random choice answer to and if statment

I am creating text based game in python 3.3.2 and I want to after the
attack either misses or hits (chosen randomly)you get a difrent messege
depending on what happens. this is the code so far
print ("A huge spider as large as your fist crawls up your arm. Do you
attack it? Y/N")
attack_spider = input ()
#North/hand in hole/keep it in/attack
if attack_spider == "Y":
attack = ['Miss', 'Miss', 'Miss', 'Miss', 'Hit']
from random import choice
print (choice(attack))
I imaging it goes something like
if attack == 'Miss':
print ("You made the spider angry")
but this does not seen to work. is it possible to do this?

Friday, 27 September 2013

Java JUnit Testing for Method

Java JUnit Testing for Method

I am new at JUnit Testing and curious about how it works. Currently I am
trying to get an unit test to pass.
The test Method is
@Test
public void ensure_equals_method_is_properly_coded ()
{
assertTrue(employees.get(0).equals(employees.get(2)));
assertFalse(employees.get(0).equals(employees.get(1)));
assertFalse(employees.get(0).equals(employees.get(3)));
}
I have an ArrayList already populated with values in it. From what I
understand I am suppose to write a method called equals() to get this test
to pass for my task. My question is how will this method find the method
to test against. I have created an equals() method in a class called
Persons but I don't know if it's even being called when I run the test.
My second question is questioning the logic in my equal() method. So far I
have this.
public boolean equals() {
if (employees.get(0).equals(employees.get(2)))
return true;
return false;
}
This should return true because the first test item asserts that is true.
Is my logic correct on this?

Simple Python loop counter issue

Simple Python loop counter issue

Ok, I am trying to make a simple program to kinda test how well i am
learning things, I have come to a point where it is getting very large as
I want the program to store data in sections (Day1,Day2....ect) so i tried
to assign it to read the current Day count (Num_Days = ) but it doesnt
seem to like this. I made a small test loop to try and test out if i could
do this and have gotten stuck even though the logic looks good to me. I
tried to do some searches but as i dont know what I am trying to do is
even called I havent gotten very far. What I want to do is have the loop
read the Num_Days and give the Days() the count and assign it to that day
through 'n'.
Num_Days = 0
Total = 0
Data = 0
Day1 = 0
Day2 = 0
Day3 = 0
def Start_Work(x):
while Num_Days < 3:
Num_Days += 1
print "This is Day:",Num_Days
n = Num_Days
Total = +20
Day(n) += Total
else:
print "failed"
x = str('start')
I also made a dpaste on it as it is easier for me to look at it that way
then in the full black: http://dpaste.com/1398446/

Compare datatables with unlike primary keys

Compare datatables with unlike primary keys

I have datatables A and B. Table A has columns 1 and 2. Columns 1 and 2
are the primary key. Table B has columns 1, 2, 4. Columns 1 and 4 are the
primary key. I want to update table B so that for every value where B.1 ==
A.1 I want to make it so that B.2 = A.2. Because 2 is not part of the
primary key for table B there may be multiple records where B.1 and B.2
are the same and I want to update 2 for all those rows.
I am stuck at this kind of code:
foreach(DataRow dr in A.Rows){
DataRow Found = B.Rows.Find(dr[1]);
if(Found != null)
Found[2] = dr[2];
}
The major problem I am facing is that because table B has a compound
primary key that is shared by table A. The find is looking for two values
but only one can come from table A.

Excel Macro, read a worksheet, remove lines with no data based off value in a column

Excel Macro, read a worksheet, remove lines with no data based off value
in a column

I'm trying to read a column, which has a numerical value, to indicate
whether or not to search that row to see if there is any data contained
within the specified range of that row. If there is no data contained
within the range, select that row to be deleted. There will be many rows
to be deleted once it has looped through the worksheet.
For example, in column "C" when the value "0" is found, search that row to
see if there is any data contained in the cells, the cell range to search
for empty cells in that row is D:AM. If the cells in the range are empty,
then select that row and delete it. The entire row can be deleted. I need
to do this for the entire worksheet, which can contain up to 20,000 rows.
The problem I'm having is getting the macro to read the row, once the
value 0 is found, to determine if the range of cells(D:AM) are empty. Here
is the code I have thus far:
Option Explicit
Sub DeleteBlankRows()
'declare variables
Dim x, curVal, BlankCount As Integer
Dim found, completed As Boolean
Dim rowCount, rangesCount As Long
Dim allRanges(10000) As Range
'set variables
BlankCount = 0
x = 0
rowCount = 2
rangesCount = -1
notFirst = False
'Select the starting Cell
Range("C2").Select
'Loop to go down Row C and search for value
Do Until completed
rowCount = rowCount + 1
curVal = Range("C" & CStr(rowCount)).Value
'If 0 is found then start the range counter
If curVal = x Then
found = True
rangesCount = rangesCount + 1
'reset the blanks counter
BlankCount = 0
'Populate the array with the correct range to be selected
Set allRanges(rangesCount) = Range("D" & CStr(rowCount) & ":AM" &
CStr(rowCount))
ElseIf (found) Then
'if the cell is blank, increment the counter
If (IsEmpty(Range("I" & CStr(rowCount)).Value)) Then BlankCount =
BlankCount + 1
'if counter is greater then 20, reached end of document, stop
selection
If BlankCount > 20 Then Exit Do
End If
'In the safest-side condition to avoid an infinite loop in case of
not of finding what is intended.
If (rowCount >= 25000) Then Exit Do
Loop
If (rangesCount > 0) Then
'Declare variables
Dim curRange As Variant
Dim allTogether As Range
'Set variables
Set allTogether = allRanges(0)
For Each curRange In allRanges
If (Not curRange Is Nothing) Then Set allTogether =
Union(curRange, allTogether)
Next curRange
'Select the array of data
allTogether.Select
'delete the selection of data
'allTogether.Delete
End If
End Sub
The end of the document is being determined by Column C when it encounters
20 or more blank cells the worksheet has reached its end. Thanks in
advance for your input!

Newbie with Angular- need help configuring NG-Grid Custom Cell Editing

Newbie with Angular- need help configuring NG-Grid Custom Cell Editing

I have created a Plunker here: embed.plnkr.co/M1JHtX/preview or
http://plnkr.co/edit/mwedtS (obviously I'm new to Plnkr as well. :-) )
Hi, I am new to Angular and NG-GRID and while learning Angular is fun and
exciting to me I have been banging my head against these grid problems for
a few days now. I have three problems with this grid which are keeping me
from meeting my requirements.
In the middle column, there is a 40 character limit. When more than 40
characters are present on load the cell is marked as invalid by having a
red background, I was able to achieve this, however, when the user clicks
to edit it to limit the characters to under 40, and they don't, the error
message goes away. I need it to stay until they fix the problem. The
problem is, if they click to modify the cell, the formatting goes away and
the when they click out of the cell without modifying the red validation
is gone although there is still more than 40 characters. Also, how to make
the red background go away after user fixes issue.
A user should not be able to change the third column to VALID if the
Second column is blank. (Row 8 for example has a second column that is
blank and they should be able to modify the third column to Valid in this
case). I am not sure how to achieve this.
After focusing in and out of a cell the input box does not go away. How do
I get the input box to go away after the user leaves the cell?
I'm sure some of these errors are my grid option configurations and others
are probably really simple things I'm missing. Is there someone that can
mentor me so that I can tackle these issues. Our Company has decided to go
with Angular Grid for the project and I'm sure I need to know these basics
before moving on to other grids. Thank you kindly.

Jquery UI accordion working in MVC 4 debug mode but not in the release

Jquery UI accordion working in MVC 4 debug mode but not in the release

I work on an ASP.NET MVC 4 application.
I updated jQuery, jQuery UI and all other nuget packages in my project.
Built it and ran it to see that no problems occured. Everything worked so
I continiued development for several days.
After a while I published the project to a test-server I have to see how
it looked on Ipad, Iphone etc. And then I realized that the jQuery-UI
accordion stopped working.
It renders, but does not respond on click. This goes for all browsers. I
found this strange since the only difference is that the MVC bundeling i
applied in release mode and as far as I understand it either minifies the
jQuery file or chooses the minified version (the latter probably beeing
what is does here since it is added when updating using nuget).
The jQuery version is: 2.0.3
The jQuery-ui version is: 1.10.3
In Chrome console the error reads:
Uncaught TypeError: Cannot read property 'safari' of undefined
OK, so i realize this might be the result of one of my jQuery assemblies
references $.browser that apparently was removed in jQuery 1.9.
However the fact that it works in debug mode (using the non-minified
versions) leads me to think that it might not be that. I could almost
think that it is a problem with the minified versions, but that should not
be possible either.
Anyone knows why this happens and know how to fix it?

jquery if blank append else update

jquery if blank append else update

I have the below code, which is also contained in this fiddle.
<div id="box"><div>click in the box</div></div>
<p>Click a name</p>
<ul>
<li id="id-1">tom</li>
<li id="id-2">jerry</li>
</ul>
<div id="result"></div>
<script>
var id;
var person;
jQuery(document).on("click", "li", function (event) {
id = jQuery(this).attr('id') || '';
person = jQuery(this).text();
$("#box").show();
});
$(function () {
$("#box").click(function (e) {
var d = new Date();
$( "#result" ).append( "<div class='item'>" + person + " last
clicked the box at " + d + "</div>");
});
});
</script>
Currently you click on a persons name, then when you click on the box it
appends the persons name and the time you clicked on the box.
Instead of having this happen repeatedly I want to append the person if
they haven't been clicked before and if they have I want to update there
latest item with the last time they clicked the box.
I am really stuck with how I would go about doing this, something like if
blank append else update? What is the best way to handle something like
this?

Thursday, 26 September 2013

Date Comparison in JavaScript

Date Comparison in JavaScript

I want to compare date in javascript with time I have used below code for
comparison
var pfrmdt = Date.parse(frmdt);
var ptodt = Date.parse(todt);
alert(pfrmdt)
alert(ptodt)
if(pfrmdt <= ptodt)
{
return true;
}
else{
alert(msg);
focusCtrl.value="";
focusCtrl.focus();
}
but its comparing with date only not with time

Wednesday, 25 September 2013

Difference between Primary Key and Unique Index in SQL Server

Difference between Primary Key and Unique Index in SQL Server

My company is currently in the process of rewriting an application that we
recently acquired. We chose to use ASP.net mvc4 to build this system as
well as using the Entity Framework as our ORM. The previous owner of the
company we acquired is very adamant that we use their old database and not
change anything about it so that clients can use our product concurrently
with the old system while we are developing the different modules.
I found out that the old table structures does not have a Primary key,
rather, it uses a Unique Index to serve as their primary key. Now when
using Entity framework I have tried to match their tables in structure but
have been unable to do so as the EF generates a Primary key instead of a
unique index.
When I contacted the previous owner, and explained it, he told me that
"the Unique key in every table is the Primary Key. They are synonyms to
each other."
I am still relatively new to database systems so I am not sure if this is
correct. Can anyone clarify this?
his table when dumped to SQL generates:
-- ----------------------------
-- Indexes structure for table AT_APSRANCD
-- ----------------------------
CREATE UNIQUE INDEX [ac_key] ON [dbo].[AT_APSRANCD]
([AC_Analysis_category] ASC, [AC_ANALYSI_CODE] ASC)
WITH (IGNORE_DUP_KEY = ON)
GO
however my system generates:
-- ----------------------------
-- Primary Key structure for table AT_APSRANCD
-- ----------------------------
ALTER TABLE [dbo].[AT_APSRANCD] ADD PRIMARY KEY ([AC_Analysis_category])
GO

Thursday, 19 September 2013

Android Webview displays different layout

Android Webview displays different layout

My webview shows different layout. Different from when I look at it on a
browser. It was alright before but i don't know what I did but a certain
text is now floating higher.
Here's my code:
package com.sample;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.StrictMode;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;
//import android.net.Uri;
public class MainActivity extends Activity
{
private WebView wv;
private ProgressBar progress;
private static String mycaturl="sample.url.com";
private static String
helpurl="file:///android_asset/otherpages/helppage.htm";
private static String
fbackurl="file:///android_asset/otherpages/feedback.htm";
@SuppressLint("NewApi")
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
StrictMode.ThreadPolicy policy = new
StrictMode.ThreadPolicy.Builder().permitNetwork().build();
StrictMode.setThreadPolicy(policy);
if (reachable(this))
{
Toast.makeText(this, "Reachable", Toast.LENGTH_SHORT).show();
buildwv( savedInstanceState, WebSettings.LOAD_DEFAULT,
mycaturl );
}
else
{
Toast.makeText(this, "Unreachable", Toast.LENGTH_SHORT).show();
eolc( savedInstanceState );
}
}
@SuppressLint({ "SetJavaScriptEnabled" })
public void buildwv(Bundle sis, int load, String url)
{
if(reachable(this))
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_SENSOR);
}
else
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
}
setContentView(R.layout.activity_main);
wv=(WebView) findViewById(R.id.wv);
wv.setWebViewClient( new wvc() );
progress=(ProgressBar) findViewById(R.id.progress);
WebSettings ws = wv.getSettings();
ws.setAppCacheMaxSize( 100 * 1024 * 1024 );
ws.setAppCachePath( this.getCacheDir().getAbsolutePath() );
ws.setAllowFileAccess( true );
ws.setAppCacheEnabled( true );
ws.setJavaScriptEnabled( true );
ws.setCacheMode(load);
//if instance is saved, to catch orientation change
if(sis==null)
{ wv.loadUrl(url); }
}
public void eolc(final Bundle sis)
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
AlertDialog.Builder ad = new AlertDialog.Builder(
MainActivity.this );
ad.setTitle("Unreachable Host");
ad.setMessage("Host is unreachable. Load from cache or exit.");
ad.setIcon(R.drawable.tick);
ad.setCancelable(false);
ad.setPositiveButton( "Load from Cache", new
DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "You chose to load
cache.", Toast.LENGTH_SHORT).show();
buildwv( sis, WebSettings.LOAD_CACHE_ELSE_NETWORK,
mycaturl );
}
});
ad.setNeutralButton( "Help", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "You chose Help.
EOLC", Toast.LENGTH_SHORT).show();
buildwv( sis, WebSettings.LOAD_CACHE_ELSE_NETWORK, helpurl );
}
});
ad.setNegativeButton( "Exit", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(), "You chose to
exit.", Toast.LENGTH_SHORT).show();
finish();
}
});
ad.create();
ad.show();
}
public void alertprep()
{
this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
if(wv.getSettings().getCacheMode()==WebSettings.LOAD_DEFAULT)
{
String a = "Connection Lost";
String b = "Connection to host was lost. Restart and load
cache or exit.";
alert(a,b);
}
else
if(wv.getSettings().getCacheMode()==WebSettings.LOAD_CACHE_ELSE_NETWORK)
{
String a = "Page Not Cached";
String b = "Page you're trying to view is not yet cached.
Please visit help to learn how to cache.";
alert(a,b);
}
}
public void alert(String a,String b)
{
AlertDialog.Builder ad = new AlertDialog.Builder(
MainActivity.this );
ad.setTitle(a);
ad.setMessage(b);
ad.setIcon(R.drawable.tick);
ad.setCancelable(false);
ad.setPositiveButton( "Restart", new
DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog,int which)
{
Toast.makeText(getApplicationContext(), "You chose to
restart and load cache.", Toast.LENGTH_SHORT).show();
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(
getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_NEW_TASK );
startActivity(i);
}
});
ad.setNeutralButton( "Help", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "You chose Help.
alertprep", Toast.LENGTH_SHORT).show();
wv.stopLoading();
wv.loadUrl( helpurl );
}
});
ad.setNegativeButton( "Exit", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Toast.makeText(getApplicationContext(), "You chose to
exit.", Toast.LENGTH_SHORT).show();
finish();
}
});
ad.create();
ad.show();
}
private class wvc extends WebViewClient
{
//when page started loading
public void onPageStarted(WebView view, String url, Bitmap favicon)
{
super.onPageStarted(view, url, favicon);
//circular progress bar open
progress.setVisibility(View.VISIBLE);
if (url.contains(mycaturl))
{
WebSettings ws = wv.getSettings();
if ( !reachable(getApplicationContext()) )
{
if ( ws.getCacheMode() == WebSettings.LOAD_DEFAULT )
{
alertprep();
}
else if ( ws.getCacheMode() ==
WebSettings.LOAD_CACHE_ELSE_NETWORK )
{
Toast.makeText(getApplicationContext(), "loading
cache coz not reachable",
Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "CACHE
MODE OUT OF BOUNDS!!",
Toast.LENGTH_SHORT).show();
}
}
else
{
if ( ws.getCacheMode() ==
WebSettings.LOAD_CACHE_ELSE_NETWORK )
{
Toast.makeText(getApplicationContext(),
"Connection to server established.",
Toast.LENGTH_SHORT).show();
}
}
}
}
//when page finished
@Override
public void onPageFinished(WebView view, String url)
{
super.onPageFinished(view, url);
Toast.makeText(getApplicationContext(), "PAGE DONE
LOADING!!", Toast.LENGTH_SHORT).show();
//circular progress bar close
progress.setVisibility(View.GONE);
}
//when received an error
@Override
public void onReceivedError(WebView view, int errorCode, String
description, String failingUrl)
{
super.onReceivedError(view, errorCode, description,
failingUrl);
//wv.destroy();
wv.loadUrl(helpurl);
WebSettings ws = wv.getSettings();
if ( ws.getCacheMode() == WebSettings.LOAD_DEFAULT )
{
Toast.makeText(getApplicationContext(), "Page
unavailable", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "Page not
cached", Toast.LENGTH_SHORT).show();
}
alertprep();
}
/*url loading
@Override
public boolean shouldOverrideUrlLoading( WebView view, String url )
{
if (url != null && url.endsWith("feedback.htm")) //what to
search in the end of the feedback form
{
Toast.makeText(getApplicationContext(), "URL LOADING
TRUE?!!", Toast.LENGTH_SHORT).show();
Uri uriUrl = Uri.parse(fbackurl);
Intent launchBrowser = new Intent(Intent.ACTION_VIEW,
uriUrl);
startActivity(launchBrowser);
//view.loadUrl(url);
return true;
}
else
{
Toast.makeText(getApplicationContext(), "URL LOADING
FALSE?!!", Toast.LENGTH_SHORT).show();
return false;
}
}*/
}
//checking connectivity by checking if site is reachable
public static boolean reachable(Context context)
{
final ConnectivityManager connMgr = (ConnectivityManager)
context.getSystemService(Context.CONNECTIVITY_SERVICE);
final NetworkInfo netInfo = connMgr.getActiveNetworkInfo();
if (netInfo != null && netInfo.isConnected())
{
try
{
URL url = new URL(mycaturl);
HttpURLConnection urlc = (HttpURLConnection)
url.openConnection();
urlc.setConnectTimeout(5000); // five seconds timeout in
milliseconds
urlc.connect();
if (urlc.getResponseCode() == 200) // good response
{ return true; } else { return false; }
}
catch (IOException e)
{ return false; }
}
else
{ return false; }
}
//options menu inflation
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
super.onCreateOptionsMenu(menu);
// inflate the menu; this adds items to the action bar if it is
present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
//when back button is pressed
public void onBackPressed ()
{
if (wv.isFocused() && wv.canGoBack())
{ wv.goBack(); } else { finish(); }
}
//when options button is pressed
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.item1:
wv.loadUrl( helpurl );
break;
case R.id.item2:
wv.loadUrl( fbackurl );
break;
case R.id.item3:
String currurl=wv.getUrl();
wv.loadUrl(currurl);
break;
case R.id.item4:
Intent i = getBaseContext().getPackageManager()
.getLaunchIntentForPackage(
getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
break;
case R.id.item5:
finish();
break;
default:
break;
}
return true;
}
//saving instance state
@Override
protected void onSaveInstanceState(Bundle outState )
{
super.onSaveInstanceState(outState);
wv.saveState(outState);
}
//restoring instance state
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState)
{
super.onSaveInstanceState(savedInstanceState);
wv.restoreState(savedInstanceState);
}
}
Please help, needs urgently. Thanks.

How to inherit from a multiprocessing queue?

How to inherit from a multiprocessing queue?

With the following code, it seems that the queue instance passed to the
worker isn't initialized:
from multiprocessing import Process
from multiprocessing.queues import Queue
class MyQueue(Queue):
def __init__(self, name):
Queue.__init__(self)
self.name = name
def worker(queue):
print queue.name
if __name__ == "__main__":
queue = MyQueue("My Queue")
p = Process(target=worker, args=(queue,))
p.start()
p.join()
This throws:
... line 14, in worker
print queue.name
AttributeError: 'MyQueue' object has no attribute 'name'
I can't re-initialize the queue, because I'll loose the original value of
queue.name, even passing the queue's name as an argument to the worker
(this should work, but it's not a clean solution).
So, how can inherit from multiprocessing.queues.Queue without getting this
error?

C program for adding and deleting nodes from an ascending order in linked list

C program for adding and deleting nodes from an ascending order in linked
list

I get segmentation fault when I execute the following code. The
segmentation fault occurs only when I add an item in a node whose data is
greater than that of 1st node item.
In this code when I try to add 20 then I encounter a segmentation fault
because 20 is greater than the item in the first node. Why does this occur
and how to prevent this error?
Code:
#include <stdio.h>
struct node
{
int data;
struct node *link;
};
int main()
{
struct node *p;
p = NULL;
add(&p,10);
add(&p,9);
add(&p,1);
add(&p,20);
display(p);
printf("\nNo of elements in Linked List=%d",count(p));
delete(&p,7);
delete(&p,4);
delete(&p,5);
delete(&p,9);
display(p);
printf("\nNo of elements in Linked List=%d",count(p));
}
/* adds a node to an ascending order linked list */
add(struct node **q,int num)
{
struct node *r,*temp=*q;
r = malloc(sizeof(struct node));
r->data = num;
/* If list is empty or if new node is to be inserted before */
if(*q==NULL || (((*q)->data) > num))
{
*q = r;
(*q)->link = temp;
}
else
{
/* traverse the list to search the position to insert the new
node */
while(temp!=NULL)
{
if(temp->data <=num && (temp->link->data > num || temp->link
== NULL))
{
r->link = temp->link;
temp->link = r;
return;
}
temp = temp->link; /* go to next node */
}
}
}
display(struct node *q)
{
printf("\n");
while(q!=NULL)
{
printf("%d ",q->data);
q = q->link;
}
}
count(struct node *q)
{
int c=0;
while(q!=NULL)
{
q = q->link;
c++;
}
return c;
}
delete(struct node **q,int num)
{
struct node *old,*temp;
temp = *q;
while(temp!=NULL)
{
if(temp->data == num)
{
if(temp == *q)
{
*q =temp->link;
free(temp);
return;
}
else
{
old->link = temp->link;
free(temp);
return;
}
}
else
{
old = temp;
temp = temp->link;
}
}
printf("\nElement %d not found",num);
}

Create and Update a table from database using php

Create and Update a table from database using php

I have a database with the following fields:
-eventname (the name of the event - text)
-datestart (the start date of the event - e.g. ../../..)
-dateend (the end date of the event - e.g. ../../..)
I need to create a table with 3 columns, and however many rows depending
on how many events there are.
Here is the code I'm using at them moment to store the database data in an
array:
$allevents = mysql_query("SELECT * FROM Events ORDER BY datestart ASC");
while($event = mysql_fetch_array($allevents)){
As I said, I then need to to display the data in a table.
I'd really appreciate some help as to how to achieve this, as I'm very new
to PHP.
Thanks a lot, Joe

How to make $.load method a synchronous call?

How to make $.load method a synchronous call?

I want to make $.load method in jQuery a synchronous call. I know it is
possible to make $.ajax call by setting the property "async : false", but
how to work with $.load
i'm loading a html page using $.load(), the next part of the code is
getting executed before loading the html page. hence, i want to make it
synchronous

prevent bootstrap modal window from closing on form submission

prevent bootstrap modal window from closing on form submission

Hi I'm using Bootstrap for the first time and I can't get my modal form to
stay open on clicking the submit button. I've searched SO but all related
questions deal with slightly different issues (example below).
Disallow twitter bootstrap modal window from closing
Thanks in advance for any help.

apache: redirect only 404 error messages to a different log file in httpd.conf

apache: redirect only 404 error messages to a different log file in
httpd.conf

After a bit of searching, I couldn't find a way to redirect only 404
specific error messages to a different log file(not error_log). Please let
me know if there is way to achieve this. Quick help would be appreciated.
Thanks in advance. :)

Wednesday, 18 September 2013

Immutable string in java

Immutable string in java

i have basic confusion .
String s2=new String("immutable");
System.out.println(s2.replace("able","ability"));
s2.replace("able", "abled");
System.out.println(s2);
In first print statement it is printing immutability but it is immutable
right? why so? and in next printing statement it is not replaced> any
answers welcome..

Jasmine tests that require outside libraries

Jasmine tests that require outside libraries

I was wondering what is best practice or at least a practice for using
Jasmine to test javascript that requires remote libraries called on page
load, but not in the app.
More specifically, I'm creating a backbone view for processing payments
using stripe. Stripe recommends that you load their javascript in your
layout from their servers.
But my tests don't have my layout, so when I try to do this
it("calls stripe token creation", function() {
stripeSpy = spyOn(Stripe, "createToken");
form.submit();
expect(stripeSpy).toHaveBeenCalled();
});
It gives the error.
Stripe is not defined
I'd rather not depend on remote libraries for my test, nor do I really
want to go against stripe preferred method of relying on their source
code. What would be the best way to approach this?

In asp.net what is the difference between using asp.net web control and simple html imput control

In asp.net what is the difference between using asp.net web control and
simple html imput control

In my asp.net web control form i am using two text box 1st is simple input
html control and 2nd is asp.net input web control.
<form id="form1" runat="server">
Email: <input type="text" id="txt_email" name="txt_email" value=""
/><br />
Email2: <asp:TextBox ID="txt_email2"
runat="server"></asp:TextBox><br />
<asp:Button ID="btn_login" Name="btn_login" runat="server"
Text="Button"
onclick="btn_login_Click" />
</form>
I need to know what is the difference using simple control and asp.net
input control both of them pass the value to code behind after the form
submit. can any one help me on this?

Add white outline around text block

Add white outline around text block

Need to add straight white outline around text (without blur effect like
in text-shadow). Example:

DetailsView in Modalpopup won't load on second click on edit button

DetailsView in Modalpopup won't load on second click on edit button

I have a GridView that when you click the edit button it loads a
DetailsVIew in Edit Mode inside of a ModalPopup. It works fine the first
time you click edit. If you click edit again to make changes to a second
record it loads but the DetailsView is not in the ModalPopup. Can anyone
tell me what I"m doing wrong? My code is below.
this is my source code with the GridVIew and DetailsVIew:
<asp:SqlDataSource ID="sdsMembers" runat="server"
ConnectionString="<%$ ConnectionStrings:DoseRec_ABTConnectionString %>"
SelectCommand="SELECT [intMemberID], [vcharTitle], [vcharFirstName],
[vcharLastName], [vcharSuffix], [vcharJobTitle], [vcharAddress1],
[vcharAddress2], [vcharCity], [vcharState], [vcharZipCode],
[vcharPhone], [vcharFax], [bitActive] FROM [tbl_Members]"
DeleteCommand="DELETE FROM [tbl_Members] WHERE [intMemberID] =
@intMemberID"
InsertCommand="INSERT INTO [tbl_Members] ([vcharTitle],
[vcharFirstName], [vcharLastName], [vcharSuffix], [vcharJobTitle],
[vcharAddress1], [vcharAddress2], [vcharCity], [vcharState],
[vcharZipCode], [vcharPhone], [vcharFax], [bitActive]) VALUES
(@vcharTitle, @vcharFirstName, @vcharLastName, @vcharSuffix,
@vcharJobTitle, @vcharAddress1, @vcharAddress2, @vcharCity,
@vcharState, @vcharZipCode, @vcharPhone, @vcharFax, @bitActive)"
UpdateCommand="UPDATE [tbl_Members] SET [vcharTitle] = @vcharTitle,
[vcharFirstName] = @vcharFirstName, [vcharLastName] = @vcharLastName,
[vcharSuffix] = @vcharSuffix, [vcharJobTitle] = @vcharJobTitle,
[vcharAddress1] = @vcharAddress1, [vcharAddress2] = @vcharAddress2,
[vcharCity] = @vcharCity, [vcharState] = @vcharState, [vcharZipCode] =
@vcharZipCode, [vcharPhone] = @vcharPhone, [vcharFax] = @vcharFax,
[bitActive] = @bitActive WHERE [intMemberID] = @intMemberID">
<DeleteParameters>
<asp:Parameter Name="intMemberID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="vcharTitle" Type="String" />
<asp:Parameter Name="vcharFirstName" Type="String" />
<asp:Parameter Name="vcharLastName" Type="String" />
<asp:Parameter Name="vcharSuffix" Type="String" />
<asp:Parameter Name="vcharJobTitle" Type="String" />
<asp:Parameter Name="vcharAddress1" Type="String" />
<asp:Parameter Name="vcharAddress2" Type="String" />
<asp:Parameter Name="vcharCity" Type="String" />
<asp:Parameter Name="vcharState" Type="String" />
<asp:Parameter Name="vcharZipCode" Type="String" />
<asp:Parameter Name="vcharPhone" Type="String" />
<asp:Parameter Name="vcharFax" Type="String" />
<asp:Parameter Name="bitActive" Type="Boolean" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="vcharTitle" Type="String" />
<asp:Parameter Name="vcharFirstName" Type="String" />
<asp:Parameter Name="vcharLastName" Type="String" />
<asp:Parameter Name="vcharSuffix" Type="String" />
<asp:Parameter Name="vcharJobTitle" Type="String" />
<asp:Parameter Name="vcharAddress1" Type="String" />
<asp:Parameter Name="vcharAddress2" Type="String" />
<asp:Parameter Name="vcharCity" Type="String" />
<asp:Parameter Name="vcharState" Type="String" />
<asp:Parameter Name="vcharZipCode" Type="String" />
<asp:Parameter Name="vcharPhone" Type="String" />
<asp:Parameter Name="vcharFax" Type="String" />
<asp:Parameter Name="bitActive" Type="Boolean" />
<asp:Parameter Name="intMemberID" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
</p>
<p>
<asp:SqlDataSource ID="sdsMembersDetail" runat="server"
ConnectionString="<%$
ConnectionStrings:DoseRec_ABTConnectionString %>"
SelectCommand="SELECT [intMemberID] AS ID, [vcharTitle] AS Title,
[vcharFirstName] AS 'First Name', [vcharLastName] AS 'Last Name',
[vcharSuffix] AS Suffix, [vcharJobTitle] AS 'Job Title',
[vcharAddress1] AS Address1, [vcharAddress2] AS Address2,
[vcharCity] AS City, [vcharState] AS State, [vcharZipCode] AS 'Zip
Code', [vcharPhone] AS Phone, [vcharFax] AS Fax, [bitActive] AS
Active FROM [tbl_Members] WHERE ([intMemberID] = @intMemberID)">
<SelectParameters>
<asp:QueryStringParameter DefaultValue="" Name="intMemberID"
QueryStringField="intMemberID" Type="Int32" />
</SelectParameters>
</asp:SqlDataSource>
</p>
<p>
&nbsp;<asp:UpdatePanel ID="UpdatePanel1" runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<asp:GridView ID="gvMembers" runat="server"
AutoGenerateColumns="False"
DataKeyNames="intMemberID" DataSourceID="sdsMembers"
style="background-color:White;">
<Columns>
<asp:CommandField ShowDeleteButton="True" />
<asp:TemplateField ControlStyle-Width="50px"
HeaderStyle-Width="60px">
<ItemTemplate>
<asp:LinkButton ID="btnViewDetails"
runat="server"
OnClick="BtnViewDetails_Click">Edit</asp:LinkButton>
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="intMemberID" HeaderText="ID"
InsertVisible="False" ReadOnly="True"
SortExpression="intMemberID" />
<asp:BoundField DataField="vcharTitle"
HeaderText="vcharTitle"
SortExpression="vcharTitle" />
<asp:BoundField DataField="vcharFirstName"
HeaderText="First Name"
SortExpression="vcharFirstName" />
<asp:BoundField DataField="vcharLastName" HeaderText="Last
Name"
SortExpression="vcharLastName" />
<asp:BoundField DataField="vcharSuffix" HeaderText="Suffix"
SortExpression="vcharSuffix" />
<asp:BoundField DataField="vcharJobTitle" HeaderText="Job
Title"
SortExpression="vcharJobTitle" />
<asp:BoundField DataField="vcharAddress1"
HeaderText="Address1"
SortExpression="vcharAddress1" />
<asp:BoundField DataField="vcharAddress2"
HeaderText="Address2"
SortExpression="vcharAddress2" />
<asp:BoundField DataField="vcharCity" HeaderText="City"
SortExpression="vcharCity" />
<asp:BoundField DataField="vcharState" HeaderText="State"
SortExpression="vcharState" />
<asp:BoundField DataField="vcharZipCode" HeaderText="Zip
Code"
SortExpression="vcharZipCode" />
<asp:BoundField DataField="vcharPhone" HeaderText="Phone"
SortExpression="vcharPhone" />
<asp:BoundField DataField="vcharFax" HeaderText="Fax"
SortExpression="vcharFax" />
<asp:CheckBoxField DataField="bitActive" HeaderText="Active"
SortExpression="bitActive" />
</Columns>
</asp:GridView>
</ContentTemplate>
</asp:UpdatePanel>
<asp:Button id="btnShowPopup" runat="server" style="display:none" />
<ajaxToolKit:ModalPopupExtender
ID="mdlPopup" runat="server" TargetControlID="btnShowPopup"
PopupControlID="pnlPopup"
CancelControlID="btnClose"
BackgroundCssClass="modalBackground" />
<asp:Panel ID="pnlPopup" runat="server" Width="500px"
style="display:none">
<asp:UpdatePanel ID="updPnlCustomerDetail" runat="server"
UpdateMode="Conditional">
<ContentTemplate>
<asp:Label ID="lblMemberDetail" runat="server"
Text="Member Detail" BackColor="lightblue" Width="95%"
/>
<asp:DetailsView ID="dvMemberDetail" runat="server"
DefaultMode="Edit" Width="95%" BackColor="white"
OnItemUpdating="dvMembersDetail_ItemUpdating">
</asp:DetailsView>
</ContentTemplate>
</asp:UpdatePanel>
<div align="right" style="width:95%">
<asp:LinkButton
ID="btnSave" runat="server" Text="Save"
Width="50px" onclick="btnSave_Click" />
<asp:LinkButton ID="btnClose"
runat="server">Close</asp:LinkButton>
</div>
</asp:Panel>
protected void BtnViewDetails_Click(object sender, EventArgs e)
{
LinkButton btnDetails = sender as LinkButton;
GridViewRow row = (GridViewRow)btnDetails.NamingContainer;
this.sdsMembersDetail.SelectParameters.Clear();
this.sdsMembersDetail.SelectParameters.Add("intMemberID",
Convert.ToString(this.gvMembers.DataKeys[row.RowIndex].Value));
this.dvMemberDetail.DataSource = this.sdsMembersDetail;
this.dvMemberDetail.DataBind();
this.updPnlCustomerDetail.Update();
this.mdlPopup.Show();
}
If any other code, like the code for my save button is needed just let me
know and I will post it. Thanks.

View does not appear because of i0S 7

View does not appear because of i0S 7

I tried my app on my iPhone with iOS 7 and everything works perfectly
except one thing. On iOS 6 versions, when I executed the following code,
the loading view (with the activityindicator) appeared and disappeared at
the end of the loading. On iOS 7, the view does not appear at all during
the loading.
self.loadingView.alpha = 1.0;
[self performSelector:@selector(accessServices) withObject:nil
afterDelay:0.0f];
AccessServices method :
- (void)accessServices {
// Getting JSON stuff
// The code is OK, I just don't copy/paste it here
self.loadingView.alpha = 0.0;
}
What happens ? Is it an iOS 7 bug ?

report builder 3.0 SWTICH expression DEFAULT / ELSE

report builder 3.0 SWTICH expression DEFAULT / ELSE

I am trying to display a different logo based on the users franchise
number. Parameter = UserFranNr If the value <> 99 and <> 87, then the
embedded image to display is ID0. (Embedded image names need are strings.)
This works with nested IIFs but seems to be the right time / place to use
SWITCH. (There is a strong possibility that more franchises will use their
own logo in future.)
=Switch
(
Parameters!UserFranNr.Value = "99","ID99",
Parameters!UserFranNr.Value = "87","ID87",
"ID0"
)
I have not found any documentation that explains how to implement a
default value using SWITCH.
Is this even possible? If so how? If not any decent alternatives? Thanks
Resources: Expression Examples (Report Builder and SSRS) Define Formula
Dialog Box (Report Builder) Plus here and other forums.

How to draw reliable colored histogram in android?

How to draw reliable colored histogram in android?

I implemented the histogram as follow How to generate Image Histogram in
Android? but this is not displaying reliable result for some images. In
this we are getting the RGB values,Is there any alternated solution.
I am new to android.Please reply if anyone have the solution. Thanks in
advance!!

Tuesday, 17 September 2013

MVC4 Custom Forms Authentication - Unable to cast System.Web.HttpContext.Current.User as CustomPrincipal

MVC4 Custom Forms Authentication - Unable to cast
System.Web.HttpContext.Current.User as CustomPrincipal

I'm building a website in .Net MVC4 and am trying to implement my own
forms authentication using a CustomPrincipal object.
Here is my Login method...
public void Login(string email)
{
var user = _userManager.GetUserByEmail(email);
var encryptedCookieContent = FormsAuthentication.Encrypt(new
FormsAuthenticationTicket(1, user.Email, DateTime.Now,
DateTime.Now.AddMinutes(FormsAuthentication.Timeout.TotalMinutes),
false, user.Id + "|" + user.AccountId + "|" + user.RoleId + "|" +
user.Role.Name, FormsAuthentication.FormsCookiePath));
var formsAuthenticationTicketCookie = new
HttpCookie(FormsAuthentication.FormsCookieName,
encryptedCookieContent)
{
Domain = FormsAuthentication.CookieDomain,
Path = FormsAuthentication.FormsCookiePath,
HttpOnly = true,
Secure = FormsAuthentication.RequireSSL
};
HttpContext.Current.Response.Cookies.Add(formsAuthenticationTicketCookie);
}
This is my Custom Principal
public class CustomPrincipal : IPrincipal
{
public CustomPrincipal(IIdentity identity, int userId, int accountId,
string role, int roleId)
{
Identity = identity;
Role = role;
RoleId = roleId;
UserId = userId;
AccountId = accountId;
}
public bool IsInRole(string role)
{
return Role == role;
}
public bool IsInRole(int roleId)
{
return RoleId == roleId;
}
public IIdentity Identity { get; private set; }
public string Role { get; private set; }
public int RoleId { get; private set; }
public int UserId { get; private set; }
public int AccountId { get; private set; }
}
I'm not implementing a custom instance of Identity, I'm just reusing the
GenericIdentity. In my Global.asax file I've got my
Application_AuthenticateRequest method rigged up like this...
protected void Application_AuthenticateRequest(Object sender, EventArgs e)
{
if (Request.IsAuthenticated)
{
var formsCookie =
Request.Cookies[FormsAuthentication.FormsCookieName];
if (formsCookie != null)
{
var ticket = FormsAuthentication.Decrypt(formsCookie.Value);
var principal = PrincipalConfig.CreatePrincipal(ticket);
System.Web.HttpContext.Current.User = Thread.CurrentPrincipal
= principal;
}
}
}
PrincipalConfig.CreatePrincipal is the method that puts together my custom
principal object. This basically just fills in userData... like this...
public static CustomPrincipal CreatePrincipal(FormsAuthenticationTicket
ticket)
{
var userData = ticket.UserData.Split('|');
var principal = new CustomPrincipal(new
GenericIdentity(ticket.Name), Convert.ToInt32(userData[0]),
Convert.ToInt32(userData[1]), userData[3],
Convert.ToInt32(userData[2]));
return principal;
}
So now, referring back to the Application_AuthenticateRequest in the
global.asax file, you can see that I'm taking my newly created
CustomPrincipal object and assigning it to
System.Web.HttpContext.Current.User.
After doing so, if I put the following in the immediate window while still
in the Application_AuthenticateRequest method...
System.Web.HttpContext.Current.User as CustomPrincipal
I am shown all of the data in my CustomPrincipal object just as I would
expect.
However, if I later (in some other controller action) attempt to access
the System.Web.HttpContext.Current.User and cast it as a CustomPrincipal
it is returning a null.
Again, for each request that is made in the application I am able to
decrypt the FormsAuthenticationTicket from the FormsAuthentication cookie
inside of the Application_AuthenticateRequest method and I find all of my
UserData. So it seems that the cookie is being created and read properly.
But when the new CustomPrincipal is assigned to
System.Web.HttpContext.Current.User, there seems to be some sort of
disconnect from that time to the time that I attempt to access it again
inside another controller.
Can anyone see what I might be doing wrong here?
Let me know if I need to clarify anything.
Thanks

How can i let the BASH script run as process? So that even the Python script is killed the BASH script runs forever?

How can i let the BASH script run as process? So that even the Python
script is killed the BASH script runs forever?

I need to track and launch few BASH scripts as process (if they for some
reason crashed or etc). So i was trying as below: but not working
def ps(self, command):
process = subprocess.Popen(['/bin/bash'], shell=False,
stdin=subprocess.PIPE, stdout=subprocess.PIPE)
process.stdin.write(command + '\n')
process.stdout.readline()
ps("/var/tmp/KernelbootRun.sh")
ps("ps aux | grep processCreator.py | awk '{print $2}' | xargs kill -9")
None is working.

Monomac not resolved in Xamarin Studio on reopening solution

Monomac not resolved in Xamarin Studio on reopening solution

I recently updated to the 4.1.11 version of Xamarin Studio on the alpha
channel. When I create a new solution and then create a new project, I can
successfully add "using MonoMac.AppKit" to my .cs file and then compile.
However, when I close the solution and re-open it, I get:
Reference 'MonoMac, Version=0.0.0.0, Culture=neutral' not resolved
The type or namespace name 'MonoMac' could not be found. Are you missing
an assembly....
What gives?

How to get browser 's download dialog given the url of file

How to get browser 's download dialog given the url of file

My requirement is to download a file when "Download" button is clicked.
Service is giving me the url of the file. I used window.location but it is
replacing my page. I just want the default download dialog provided by
browser. How do I get that? I am getting a string (file location) from
service, not the file. I am using jQuery.

How to delay successive iterations of a loop in MOAI?

How to delay successive iterations of a loop in MOAI?

I want to delay successive iteration of a loop in MOAI. I've tried using a
timer to delay calling the loop, and putting an empty loop inside my main
loop. In the latter case, it just goes through all iterations of the inner
loop before proceeding to the outer loop. The result is, it stops at the
first iteration of the main loop, then goes through the inner loop, and
then finally executes the the main loop. How do I stop it from happening?

Javascrip NaN function

Javascrip NaN function

Good afternoon.
This function receive values for another one (the generation parameter).
My objective is return onde array in cloneGene variable, although it
appears like NaN and i do not know why. If anyone can help thank.
Regards
//Mutation and recombination rate
function GenerationStep (mutation_rate, recombination_rate, generation,
cloneGene) {
//var generation = [1, 2, 1, 54, 1, 1, 1];
generation = SampleWithReposition();
mutation_rate = recombination_rate = 0.1;
for(var i=0; i<pop_size; i++){
for(var j=0;j<gene_size; j++){
random_number = random();
var max_individual = Math.max.apply(Math, generation);
//mutation_rate
if(random_number < mutation_rate){
var cloneGene = 1;
cloneGene=generation[i][j]=generation[max_individual][j]+1;
//document.write(generation + ' <br />');
//return generation;
//return cloneGene;
document.write(cloneGene);
}
}
}
}

Sunday, 15 September 2013

Find distance between two nodes in binary tree

Find distance between two nodes in binary tree

Many answers on the net for 'finding Least Common Ancestor in binary tree'
and its supplementary question 'find distance between 2 nodes' have 4
issues 1) Does not consider duplicates 2) Does not consider if input node
is invalid/absent/not in tree 3) Use extra / aux storage 4) Not truncating
the traversal although answer is obtained. I coded this sample to overcome
all handicaps. but since I did not find 'a single' answer in this
direction, I would appreciate if my code has a significant disadvantage
which I am missing. Maybe there is none. Additional eyeballs appreciated.
public int distance(int n1, int n2) {
LCAData lcaData = new LCAData(null, 0, 0);
int distance = foundDistance (root, lcaData, n1, n2, new
HashSet<Integer>());
if (lcaData.lca != null) {
return distance;
} else {
throw new IllegalArgumentException("The tree does not contain
either one or more of input data. ");
}
}
private static class LCAData {
TreeNode lca;
int count;
int distance;
public LCAData(TreeNode parent, int count, int distance) {
this.lca = parent;
this.count = count;
this.distance = distance;
}
}
private int foundDistance (TreeNode node, LCAData lcaData, int n1, int
n2, Set<Integer> set) {
assert set != null;
if (node == null) {
return 0;
}
// when both were found
if (lcaData.count == 2) {
return 0;
}
// when only one of them is found
if ((node.item == n1 || node.item == n2) && lcaData.count == 1) {
// second element to be found is not a duplicate node of the
tree.
if (!set.contains(node.item)) {
lcaData.count++;
return 1;
}
}
int foundInCurrent = 0;
// when nothing was found (count == 0), or a duplicate tree node
was found (count == 1)
if (node.item == n1 || node.item == n2) {
if (!set.contains(node.item)) {
set.add(node.item);
lcaData.count++;
}
// replace the old found node with new found node, in case of
duplicate. this makes distance the shortest.
foundInCurrent = 1;
}
int foundInLeft = foundDistance(node.left, lcaData, n1, n2, set);
int foundInRight = foundDistance(node.right, lcaData, n1, n2, set);
// second node was child of current, or both nodes were children
of current
if (((foundInLeft > 0 && foundInRight > 0) ||
(foundInCurrent == 1 && foundInRight > 0) ||
(foundInCurrent == 1 && foundInLeft > 0)) &&
lcaData.lca == null) {
// least common ancestor has been obtained
lcaData.lca = node;
return foundInLeft + foundInRight;
}
// first node to match is the current node. none of its children
are part of second node.
if (foundInCurrent == 1) {
return foundInCurrent;
}
// ancestor has been obtained, aka distance has been found. simply
return the distance obtained
if (lcaData.lca != null) {
return foundInLeft + foundInRight;
}
// one of the children of current node was a possible match.
return (foundInLeft + foundInRight) > 0 ? (foundInLeft +
foundInRight) + 1 : (foundInLeft + foundInRight);
}

Securely storing connection strings in PHP?

Securely storing connection strings in PHP?

Is there a secure way I can store my connection strings in my PHP
connection files? In C# I've often encrypted the string and still had it
function as per normal, is there a similar approach that can be taken with
PHP?

C#: Loop over Textfile, split it and Print a new Textfile

C#: Loop over Textfile, split it and Print a new Textfile

I get many lines of String as an Input that look like this.
@VAR;Variable=Speed;Value=Fast;Op==;@ENDVAR;@VAR;Variable=Fabricator;Value=Freescale;Op==;@ENDVAR;
I split it, to remove the unwanted fields, like @VAR,@ENDVAR and Op==. The
optimal Output would be:
Speed = Fast;
Fabricator = Freescale; and so on.
I am able to cut out the @VAR and the@ENDVAR. Cutting out the "Op==" wont
be that hard, so thats now not the main focus of the question. My biggest
concern right now is,thatI want to print the Output as a Text-File. To
print an Array I would have to loop over it. But in every iteration, when
I get a new line, I overwrite the Array with the current splitted string.
I think the last line of the Inputfile is an empty String, so the Output I
get is just an empty Text-File. It would be nice if someone could help me.
string[] w ;
Textwriter tw2;
foreach (EA.Element theObjects in myPackageObject.Elements)
{
theObjects.Type = "Object";
foreach (EA.Element theElements in PackageHW.Elements)
{
if (theObjects.ClassfierID == theElements.ElementID)
{
t = theObjects.RunState;
w = t.Replace("@ENDVAR;", "@VAR;").Replace("@VAR;", ";").Split(new
string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
foreach (string s in w)
{
tw2.WriteLine(s);
}
}
}
}

Dialer not setting Preferred Line for custom TSP

Dialer not setting Preferred Line for custom TSP

I was trying to build a custom TSP. The problem is, it is not showing in
the Line drop down of dialer. If I use the 'Connect Using...' menu item,
it gets listed in the drop down!
Also, after I select my tsp from the Line drop down, the 'Preferred Line'
key in registry is not getting updated, (resets to 0). What am I missing.
I was wondering about the significance of the number shown in 'Preferred
Line' for other tsp. Where did it came from? Is it something I return
during 'TSPI_providerInit' or something like that?
Any idea is welcome.

How do I access a resource(style) through code?

How do I access a resource(style) through code?

I have a Resource Dictionary containing all my custom styles for the
programs controls. The Dictionary is mergerd with the application's
resources as displayed below:
<ResourceDictionary x:Key="Controls">
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Controls.xaml" />
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
I can easily access the different styles through xaml:
<Button Style="{StaticResource Button}" />
But whenever I try assigning controls with this style through code, it fails.
I've tried:
Button.Style = Application.Current.Resources("Button")
Button.Style = CType(Application.Current.Resources("Button"), Style)
And different approaches similar to the ones above. During testing some of
the different ways to get the styles, I was faced with "Resource not
found" but when using the above ones the program seemed to find the style.
I could successfully run the program - but without any visual proof that
the style was indeed applied.
How do I properly assign a control a style found in a Resource Dictionary?

Why can I add item to my list but not reallocate it?

Why can I add item to my list but not reallocate it?

This might be a very noob question but I cannot fully understand why am I
able to add items to my list and why can't I set it to null ?
public class Test
{
public List<string> Source { get; set; }
public Test()
{ this.Source = new[] { "Hey", "hO" }.ToList(); }
}
class Program
{
static void Main(string[] args)
{
Test test = new Test();
ModifyList(test.Source);
//Why here test.Source.Count() == 3 ? Why isn't it null ?
}
private static void ModifyList(List<string> list)
{
list.Add("Three");
list = null;
}
}
Why after the call ModifyList, test.Source.Count() == 3 ? Why isn't it null ?
I would have expected the list to be either NULL or remain unchanged with
two elements.
Can someone explain to me what is happening? Thank you very much!

Best learning resource for HTML5/CSS3 for a programmer?

Best learning resource for HTML5/CSS3 for a programmer?

I was just wondering what you thought would be the best education material
for HTML5/CSS3 is (not older web technologies) for a guy who is just a
programmer (i.e. mostly C/C++, Java, Pascal, and Python)? Reason I ask, is
because the HTML and CSS syntax mostly confuses me, and there are some
things I just do not understand (e.g. the float styling attribute, I
usually just end up putting that somewhere and hoping it works, if not,
try putting it somewhere else). So I was hoping there was an explicit
guide/tutorial on getting a programmer up to speed on HTML5/CSS3.
Alternatively, if there is no direct answer to that question, then what is
a good learning resource for HTML5/CSS3 and what are the
pitfalls/shortcomings (if any) in the markup language that I/others might
encounter on this journey/transition?
Keep in mind I have minimal experience writing HTML/CSS markup, and have
written no HTML5/CSS3 markup at all.
Regards and thank you in advance. :-)

Saturday, 14 September 2013

java - when else condition execute?

java - when else condition execute?

int x = 0;
if (x == x) {
System.out.println("Ok");
} else {
System.out.println("Not ok");
}
I want else condition to execute without change if, how come?

PyQt continuously updating variable.

PyQt continuously updating variable.

I am very new to PyQt and new to GUI programming. I am making a game. I
need a variable to update continuously (it is a function of the time). I
am struggling to figure out how to do this. I did this in tkinter with
self.after(10,self.updateCost()) which lead to an update every .01
seconds.

how to set a Bitmap to background for a view Android API 10-18?

how to set a Bitmap to background for a view Android API 10-18?

What I have is:
Manifest:
<uses-sdk
android:minSdkVersion="10"
android:targetSdkVersion="18" />
source:
View view = createViewFromWhatever();
Bitmap bitmap = loadSomethingAddMore();
Everywhere I have searched this is the accepted, suggested:
view.setBackgroundDrawable(new BitmapDrawable(bitmap));
But it is Deprecated in API 18. I am terrorised with framework bugs and
miss documentations at OS level. I want to respect what they are saying
and in case of crash "it is not my fault"
I can't even use the new BitmapDrawable(bitmap) and I need new
BitmapDrawable(getActivity().getResources(), bitmap) instead. If I change
my method to a recommended way: setBackground(new
BitmapDrawable(getActivity().getResources(), bitmap));
It will mark as error with message:
Call requires API level 16 (current min is 10):
android.widget.RelativeLayout#setBackground
As a solution I could check what version is running the user and do an
if-else than I will have a code will with if(isAndroidVersion10()) else if
() ...
Any solution acceptable solution?
If I escape from deprecation warnings via reflection I still will have the
responsibility in case of crash, because I have release the code with
deprecated method! -just the way how I call is different.
If I ignore that Lint, than it will crash at a low version api, tested.

How can .htaccess change $_SERVER[REQUEST_URI]?

How can .htaccess change $_SERVER[REQUEST_URI]?

I've a website at http://ex.com/web2/ this is a real path in my server,
but I wanted visitors to be able to access the website also over the URL
http://ex.com/web3/ (without changing the URL on the browser), so after
looking around (and asking help) I added the following to my .htaccess:
<IfModule mod_rewrite.c>
Options +FollowSymLinks -MultiViews
RewriteEngine On
RewriteBase /
RewriteRule ^web3/?$ /web2/ [L,NC]
RewriteRule ^web3/(.+)$ /web2/$1 [L,NC]
</IfModule>
The "silent" redirect that DOES NOT change the browser URL works fine, but
in PHP if I print $_SERVER[REQUEST_URI] I get the URL the user placed on
the browser, /web3/ instead of /web2/.
Is there any way .htaccess can also "fake" the path that is sent to the
PHP var? (I was told this would be hard or even impossible.)
Thank you.

swfdotnet library reference issue in vs2010

swfdotnet library reference issue in vs2010

I am creating an windows forms app using vs2010, framework 4.0, C#. I am
adding reference of swfdotnet library's three dll files, include them in
the code, intellisense is also the showing its classes, methods and
properties. But when i run the program it gives following warning and
program doesnt work.
The referenced assembly "SwfDotNet.IO" could not be resolved because it
has a dependency on "System.Web, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a" which is not in the currently targeted
framework ".NETFramework,Version=v4.0,Profile=Client". Please remove
references to assemblies not in the targeted framework or consider
retargeting your project.
Should i need to add some other files. HelP!

Best practice to eliminate blank lines in HTML due to templating engines

Best practice to eliminate blank lines in HTML due to templating engines

Blank lines within and especially at the top of an HTML source file look
untidy to me.
A common template code (in this case, Jinja2) may look like this:
{% block header %}
{% include "templates/partials/something_header.html" %}
{% endblock header %}
{% block body %}
{% include "templates/partials/something_body.html" %}
{% endblock body %}
{% block footer %}
{% include "templates/partials/something_footer.html" %}
{% endblock footer %}
Now, without even adding indentation issues to make the above more
presentable, it already has the adverse effect of generating 2 empty lines
due to the 2 carriage returns within the templating code:
..
..
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv=....
Whilst I can utilize a minifier/post-processor in this particular case,
I'm wondering what others do to keep their template code easy on the eyes
whilst preventing unnecessary blank lines?

Cannot upload file to dropbox

Cannot upload file to dropbox

I'm having trouble uploading file to Dropbox. I do not get any errors, the
app folder is created in my account, but the file is not uploaded to
dropbox. Here is my code:
public void exportDataInCSV(final String file_name,
final ArrayList<Assessment> assessments, final boolean dropBox)
throws IOException {
final File folder = new
File(Environment.getExternalStorageDirectory()
+ "/MYDIR");
boolean var = false;
if (!folder.exists())
var = folder.mkdir();
System.out.println("" + var);
final String filename = folder.toString() + "/" + file_name + ".csv";
// show waiting screen
CharSequence contentTitle = getString(R.string.app_name);
final ProgressDialog progDailog =
ProgressDialog.show(DataExport.this,
contentTitle, "Exporting data...", true);// please
// wait
new Thread() {
public void run() {
try {
FileWriter fw = new FileWriter(filename);
fw.append("MYNAME");
fw.append(',');
fw.append("MYSIRNAME");
fw.close();
if (dropBox) {
File file = new File(folder.toString() + "/"
+ file_name + ".csv");
FileInputStream inputStream = new
FileInputStream(file);
Entry response = mDBApi.putFile("/magnum-opus.txt",
inputStream, file.length(), null, null);
}
} catch (Exception e) {
}
progDailog.dismiss();
}
}.start();
}
So can someone help me and tell me how can I upload the file i'm creating
using the filewriter to Dropbox, that is also saved to the phone's SD
card.