Friday, 27 September 2013

One To Many LINQ Joins Across Nested Collections

One To Many LINQ Joins Across Nested Collections

I have a development scenario where I am joining two collections with
Linq; a single list of column header objects which contain presentation
metadata, and an enumeration of kv dictionaries which result from a web
service call. I can currently iterate (for) through the dictionary
enumeration, and join the single header list to the current kv dictionary
without issue. After joining, I emit a curated array of dictionary values
for each iteration.
What I would like to do is eliminate the for loop, and join the single
header list directly to the entire enumeration. I understand the 1-to-1
collection join pretty well, but the 1-to-N syntax is eluding me.
Details
I have the following working method:
public void GetQueryResults(DataTable outputTable)
{
var odClient = new ODataClient(UrlBase);
var odResponse = odClient.FindEntries(CommandText);
foreach (var row in odResponse)
{
var rowValues = OutputFields
.Join(row, h => h.Key, r => r.Key,
(h, r) => new { Header = h, ResultRow = r })
.Select(r => r.ResultRow.Value);
outputTable.Rows.Add(rowValues.ToArray());
}
}
odResponse contains IEnumerable<IDictionary<string, object>>; OutputFields
contains IList<QueryField>; the .Join produces an enumeration of anons
containing matched field metadata (.Header) and response kv pairs
(.ResultRow); finally, the .Select emits the matched response values for
row consumption. The OutputField collection looks like this:
class QueryField
{
public string Key { get; set; }
public string Label { get; set; }
public int Order { get; set; }
}
Which is declared as:
public IList<QueryField> OutputFields { get; private set; }
By joining the collection of field headers to the response rows, I can
pluck just the columns I need from the response. If the header keys
contain { "size", "shape", "color" } and the response keys contain {
"size", "mass", "color", "longitude", "latitude" }, I will get an array of
values for { "size", "shape", "color" }, where shape is null, and the
mass, longitude, and latitude values are ignored. For the purposes of this
scenario, I am not concerned with ordering. This all works a treat.
Problem
What I'd like to do is refactor this method to return an enumeration of
value array rows, and let the caller manage the consumption of the data:
public IEnumerable<string[]> GetQueryResults()
{
var odClient = new ODataClient(UrlBase);
var odResponse = odClient.FindEntries(CommandText);
var responseRows = //join OutputFields to each row in odResponse by .Key
return responseRows;
}
Followup Question
Would a Linq-implemented solution for this refactor require an immediate
scan of the enumeration, or can it pass back a lazy result? The purpose of
the refactor is to improve encapsulation without causing redundant
collection scans. I can always build imperative loops to reformat the
response data the hard way, but what I'd like from Linq is something like
a closure.
Thanks heaps for spending the time to read this; any suggestions are
appreciated!

SQL Syntax error on commented T-SQL only in SQL Server 2012

SQL Syntax error on commented T-SQL only in SQL Server 2012

I had an error occur while installing on a customer site using SQL Server
2012. I was able to reproduce the syntax error locally on SQLExpress 2012.
The same DDL script runs fine under 2008 R2 but fails with "Incorrect
syntax near '44445'".
Checking the SQL that is being executed, the text '44445' is commented
out. Again, this SQL works on 2008 R2. The last line posted is the syntax
offender. Notice, it is commented out as is most of this example.
[snipped]
IF NOT EXISTS (SELECT * FROM ::fn_listextendedproperty(N'Updatable' ,
N'USER',N'dbo', N'TABLE',N'PublishLog', NULL,NULL))
EXEC dbo.sp_addextendedproperty @name=N'Updatable', @value=N'True' ,
@level0type=N'USER',@level0name=N'dbo',
@level1type=N'TABLE',@level1name=N'PublishLog'
GO
--SET ANSI_NULLS ON
--GO
--SET QUOTED_IDENTIFIER ON
--GO
--IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id =
OBJECT_ID(N'[dbo].[MetaData]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1)
--BEGIN
--CREATE TABLE [dbo].[MetaData](
-- [ID] [int] IDENTITY(1,1) NOT NULL,
-- [DataName] [nvarchar](255) NULL,
-- [DataDescription] [nvarchar](255) NULL,
-- CONSTRAINT [MetaData_PK] PRIMARY KEY NONCLUSTERED
--(
-- [ID] ASC
--) ON [PRIMARY]
--) ON [PRIMARY]
--END
--GO
--SET ANSI_NULLS ON
--GO
--SET QUOTED_IDENTIFIER OFF
--GO
--IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id =
OBJECT_ID(N'[dbo].[T_MetaData_DTrig]') AND OBJECTPROPERTY(id,
N'IsTrigger') = 1)
--EXEC dbo.sp_executesql @statement = N'CREATE TRIGGER
[dbo].[T_MetaData_DTrig] ON [dbo].[MetaData] FOR DELETE AS
--SET NOCOUNT ON
--/* * PREVENT DELETES IF DEPENDENT RECORDS IN ''DocumentsData'' */
--IF (SELECT COUNT(*) FROM deleted, DocumentsData WHERE (deleted.ID =
DocumentsData.MetaTagsID)) > 0
-- BEGIN
-- RAISERROR 44445 ''The record can''''t be deleted or changed.
Since related records exist in table ''''DocumentsData'''', referential
integrity rules would be violated.''
-- ROLLBACK TRANSACTION
-- END
[snipped]

Corrupted image when posting a tweet using spring framework twitter API

Corrupted image when posting a tweet using spring framework twitter API

I am trying to publish a tweet with an embedded image from a Java Tomcat
server using the Spring framework's twitter API. The image is a JPG hosted
online (via Amazon Cloudfront CDN). I try to post using the updateTweet
function in the code snippet below:
import org.springframework.social.twitter.api.TweetData;
import org.springframework.social.twitter.api.TwitterProfile;
import org.springframework.social.twitter.api.Tweet;
import org.springframework.social.twitter.api.impl.TwitterTemplate;
// ...
public Tweet updateTweet(String accessToken, String accessTokenSecret,
String tweetMessage, String imageUrl){
TwitterTemplate twitter = new TwitterTemplate(twitterConsumerKey,
twitterConsumerSecret, accessToken, accessTokenSecret);
twitter.setRequestFactory(twitterHttpRequestFactory);
TweetData tweetData = new TweetData(tweetMessage);
try {
UrlResource imageUrlResource = new UrlResource(imageUrl);
logger.info("Trying to tweet image with url {} content length {}",
imageUrl, imageUrlResource.contentLength());
tweetData = tweetData.withMedia(imageUrlResource);
} catch(MalformedURLException e) {
logger.error("Malformed url for tweet image: {}", imageUrl);
} catch(IOException e) {
logger.error("IOException for tweet image {}\n{}", imageUrl, e);
}
return twitter.timelineOperations().updateStatus(tweetData);
}
The tweet posts to my user's timeline, and does include a JPG image with
the correct dimensions (640x640, like the source image) - however, the
actual image data is corrupted! Here is an example of the corrupted image
that ends up on my twitter timeline:
https://pbs.twimg.com/media/BVC5M5pCcAApIgP.jpg:large
My first thought was that the image data was being truncated somehow.
However, I've confirmed via the logger.info line in the code sample above
that the URLResource pointing at the image reports a content-length
matching the filesize of the original image.
I am unsure why this code is sending corrupted image data to twitter. I
have searched for working examples that post images to twitter using the
TweetData.withMedia function from Spring's framework, but I haven't been
able to find one.

How to color convert a texture before it's time to display with openGL ES

How to color convert a texture before it's time to display with openGL ES

I'm working on a video player (based on openGL ES) for iPhone where the
frames arrive at the renderer at a rate faster than the display rate
(33ms). As the frame arrive I store them and then when it's time to
display a frame, I use an openGL shader to make a color conversion and the
RGB converted image is displayed on the screen. What I would like to do is
to be able to convert the frames as they arrive but I'm not sure how to
proceed. Can some one describe the steps needed to accomplish this? Also
is this necessary, what I mean is it a good practice to do the color
conversion right when the frame is received and only swap the buffers when
the display callback is fired?

Customize color of reference graph in DbVisualizer

Customize color of reference graph in DbVisualizer

Is it somehow possible to create differenet colored groups in the
reference graph of DbVisualizer Free 9.1?
For Example: I have table user and roles, category and pictures and each
picture is related to an user, but user and roles "boxes" in the diagramm
should be shown in green and the other two in red.
I hope you understand me :)
PS: If it is possible in SchemaSpy, it would be also nice to know :)

Thursday, 26 September 2013

how to get only those which have maximum value in a specified column in asp.net c#

how to get only those which have maximum value in a specified column in
asp.net c#

I have a table with "customer_id, date, installment_no, amount" columns. I
want to get the information of last installment of each customer_id till
today. here installment_no is int type and when a new installment is
deposited, the installment_no is increased by 1 in new entry. My table
look like:
CS1001 | 12-06-2013 | 1 | 2500
CS1002 | 19-06-2013 | 1 | 1600
CS1001 | 14-07-2013 | 2 | 2500
I want to get a sqlcommand statement for do so.

Thursday, 19 September 2013

set flag in signal handler

set flag in signal handler

In C++11, what is the safest (and perferrably most efficient) way to
execute unsafe code on a signal being caught, given a type of request-loop
(as part of a web request loop)?
It is acceptable for the 'unsafe code' to be run on the next request being
fired, and no information is lost if the signal is fired multiple times
before the unsafe code is run.
For example, my current code is:
static bool globalFlag = false;
void signalHandler(int sig_num, siginfo_t * info, void * context) {
globalFlag = true;
}
void doUnsafeThings() {
// thigns like std::vector push_back, new char[1024], set global vars,
etc.
}
void doRegularThings() {
// read filesystem, read global variables, etc.
}
void main(void) {
// set up signal handler (for SIGUSR1) ...
struct sigaction sigact;
sigact.sa_sigaction = onSyncSignal;
sigact.sa_flags = SA_RESTART | SA_SIGINFO;
sigaction(SIGUSR1, &sigact, (struct sigaction *)NULL);
// main loop ...
while(acceptMoreRequests()) { // blocks until new request received
if (globalFlag) {
globalFlag = false;
doUnsafeThings();
}
doRegularThings();
}
}
where I know there could be problems in the main loop testing+setting the
globalFlag boolean.

javafx: how to make a custum listview using css

javafx: how to make a custum listview using css

how to make a listview that each item should have a different icon using
css, if it's possible. THANK YOU

PostgreSQL concurent update selects

PostgreSQL concurent update selects

I am attempting to have some sort of update select for a job queue. I need
it to support concurrent processes affecting the same table or database
This server will be used only for the queue so a database per queue is
acceptable. Orginally I was thinking about something like the following:
UPDATE state=1,ts=NOW() FROM queue WHERE ID IN (SELECT ID FROM queue WHERE
state=0 LIMIT X) RETURN *
Which I been reading that this will cause a race condition, I read that
there was a an option for the SELECT subquery to use FOR UPDATE, but then
that will lock the row and concurrent calls will be blocked where I would
not mind if they skip over to the next unlocked row.
So what i am asking for is the best way to have a fifo system in postgres
that requires the least amount of locking the entire database.

Google Sheets - Move a ROW up

Google Sheets - Move a ROW up

I have a spreadsheet with multiple sheets and I am moving rows from sheet
to sheet when a cell has a certain value. Note we are using drop down data
validation in the cell.
I need help moving a row to the top, just below our locked header row of
the same sheet it is in.
This is what I am trying to do.
if (activatedSheetName == testQueue.getName() && activatedCellColumn == 2
&& activatedCellValue == "1st-Urgent" ) {
testQueue.insertRows(3,1);
var rangeToMove =
testQueue.getRange(activatedCellRow,1,1,testQueue.getMaxColumns());
rangeToMove.moveTo(testQueue.getRange("A3"));
testQueue.getRange("A3").setValue(getTimeStamp());
testQueue.deleteRow(activatedCellRow);
}
I know the above code is not right and would appreciate any help.
Thank you!

I want to convert curl to javascript?

I want to convert curl to javascript?

I want to change this code to java script and i don't have knowledge of http
curl -u username:password \
-H 'Content-Type: application/json' \
-H 'User-Agent: MyApp (yourname@example.com)' \
-d '{ "name": "My new project!" }' \
https://xxxxxx.com/999999999/api/v1/projects.json
to
var option = {
method: "get",
muteHttpExceptions: true,
headers: {
"Content-Type": "application/json",
"User-Agent": "MyApp (yourname@example.com)",
"username": "xxxxxx"
}
};
Thanks

Frequency counts in R

Frequency counts in R

This may seem like a very basic R question, but I'd appreciate an answer.
I have a data frame in the form of:
|column1| column2|
a | g
a | h
a | g
b | i
b | g
b | h
c | i

I want to transform it into counts, so the outcome would be like this.
I've tried using table () function, but seem to only be able to get the
count for one column.
|a | b |c
g|2 1 0
h|1 1 0
i|0 1 1

How do I do it in R?

how to group by with a sql that has multiple subqueries

how to group by with a sql that has multiple subqueries

I am trying to add a group by to this statement:
SELECT SC_JOBS.CREATIONDATE,
(SELECT SUM(SC_JOBS.GROSSEXCLVAT) FROM SC_JOBS WHERE
SC_FRAMES.GROUPPRODUCTTYPE = 'ATI' AND SC_FRAMES.JOBID = SC_JOBS.JOBSID
AND SC_JOBS.INVOICEDATE < '1990-01-01') AS Product 1,
(SELECT SUM(SC_JOBS.GROSSEXCLVAT) FROM SC_JOBS WHERE
SC_FRAMES.GROUPPRODUCTTYPE = 'ATI' AND SC_FRAMES.JOBID = SC_JOBS.JOBSID
AND SC_JOBS.INVOICEDATE < '1990-01-01') AS Product 2
FROM SC_JOBS INNER JOIN SC_FRAMES ON SC_FRAMES.JOBID = SC_JOBS.JOBSID
WHERE SC_JOBS.CREATIONDATE BETWEEN :StartDate AND :EndDate ORDER BY
SC_JOBS.CREATIONDATE
Any suggestions please?

Batch .BAT script to rename files

Batch .BAT script to rename files

Im looking for a batch script to (recursively) rename a folder of files..
Example of the rename: 34354563.randomname_newname.png to newname.png
I already dug up the RegEx for matching from the beginning of the string
to the first underscore (its ^(.*?)_ ), but cant convince Windows Batch to
let me copy or rename using RegEx.

Wednesday, 18 September 2013

hide img tag if src is empty but without javascript/jQuery or css3

hide img tag if src is empty but without javascript/jQuery or css3

, am designing templates in Channel Advisor for eBay store and it doesn't
allow javascript/jQuery. Also, the CSS3 doesn't work in various IE
versions specially the img[src*=] implementation is broken.
When I use template tags in img like:
<img src="{{THUMB(ITEMIMAGEURL1)}}">
where {{THUMB(ITEMIMAGEURL1)}} is the image path, if the image is missing
and the template is posted to eBay then the end result would be like this:
<img src="">
and this shows a broken image.
Is there a way to hide <img src=""> with HTML or CSS that works in IE7+

scrape data from a webpage that has no _viewstate

scrape data from a webpage that has no _viewstate

I want to scrap a webpage containing a list of user with addresses, email
etc. webpage contain list of user with pagination i.e. page contains 2
users when I click on page 2 link it will load users list form 2nd page
and update list so on for all pagination links.
I am trying to collect data from http://www.hyundai.co.uk/dealer-locator
with WC1V 7EP zipcode. An example can be more helpful.
Thank

Calling my function I passed through as a parameter

Calling my function I passed through as a parameter

I have a function:
public void Callback()
{
// Does some stuff
}
I want to pass that in to another function, which then passes it to
another function, which then executes the function... I have this so far:
public void StartApp() // entry point
{
StartMyAwesomeAsyncPostRequest( Callback );
}
public void StartMyAwesomeAsyncPostRequest( Delegate callback )
{
// Work out some stuff and start a post request
TheActualAsyncPostRequest( callback );
}
public void TheActualAsyncPostRequest( Delegate callback )
{
// Do some jazz then run the delegated function
callback();
}
I have looked through a few other examples but coming from a PHP and
javascript background, I'm struggling with the explanations, can you
perhaps give me an example or explanation specific to my request? Thanks
in advance!

Sybase/JDBC: how to detect reorgs or exclusive locks?

Sybase/JDBC: how to detect reorgs or exclusive locks?

We use Sybase ASE (15.5) server as our DB and are having strange,
intermittent SPID blocking issues that I am trying to detect and mitigate
programmatically at the application-layer.
Sybase allows you to schedule so-called "reorgs" which from what I can
tell are periodic re-indexes/table compactions, cleanups, etc. Scheduled
DB maintenance, basically.
Every once in a while, we get all the planets coming into alignment with
each other, where:
A query is executed (creating a SPID in Sybase) and hangs for some reason.
This places a (blocking) shared lock on, say, the widgets table; then
The scheduled reorg kicks off, and wants to cleanup the widgets table. The
reorg places an exclusive lock request on widgets, but can't obtain the
lock because widgets is already locked and blocked by the hanging
SPID/query; then
Subsequent queries are executed, each requesting shared locks on widgets;
such that
The whole system is now tied up: the reorg can't start until it obtains an
exclusive lock on widgets, but widgets is tied up in a blocking shared
lock by a hung SPID. And because the reorg has placed an exclusive lock on
widgets, all other queries wanting shared locks on widgets have to wait
until the reorg is complete (because a newly requested exclusive lock
trumps a newly requested shared lock).
I think my ideal strategy here would be to:
Timeout DB queries after say, 2 minutes, which will prevent SPIDs from
hanging and thus preventing the reorgs from running; and then
If a query attempts to hit a table that has an exclusive lock on it,
detect this and hadle it specially (like schedule the query to run again
1hr later, when hopefully the reorg is complete, etc.)
My questions:
How do I timeout a query to release a shared lock after, say, 2mins?
Is there a way to programmatically (most likely through the Sybase JDBC
driver, but perhaps via Sybase command-line, HTTP calls, etc.) determine
if a reorg is running? Or, that an exclusive lock exists on a table? That
way I could detect the exclusive lock and handle it in a special way.
Thanks in advance!

Undoing forced push: how to update remote ref with specific remote revision

Undoing forced push: how to update remote ref with specific remote revision

There is a common situation - forced updating of remote branch with losing
some revisions from it:
$ git push --force origin
Counting objects: 19, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (12/12), done.
Writing objects: 100% (12/12), 2.27 KiB, done.
Total 12 (delta 8), reused 0 (delta 0)
remote: => Syncing... [OK]
To git@gitserver.com:path/to/project.git
C..B master -> master
In other words, before the pushing remote master was like A---B---C and
forcing update changed it to A---B.
C revision is remote only - it exists on git-server and on the working
station of it's author. It means that there is no such local ref C.
Question 1: is there a way to set remote master to C revision?
I've tried to update it with push --force again like the answer for
similar question offers, but it allows to use only local refs:
$ git push --force origin C:master
error: src refspec C does not match any.
error: failed to push some refs to 'git@gitserver.com:path/to/project.git'
So if I'm getting it right the whole problem is to retrieve this revision
from git server.
Question 2: is there a way to fetch remote revision that doesn't belong to
any branch?
PS: let's think that there is no ssh access to git server, it means that
there is no way to manipulate git from the server side.

validateField doesn't work with models

validateField doesn't work with models

I want to use validateField with models but it says Method is not defined
for this object!
I code like this:
$user_payment=$this->add("Model_Payment");
$user_payment->getField("amount")
->validateNotNull()
->validateField('($this->get())<=0','Please enter a
posetive number!');

Neo4j REST API List All Labels returns labels when graph is empty?

Neo4j REST API List All Labels returns labels when graph is empty?

I'm currently working on a REST API wrapper for Neo4j written in node.js.
Why does the REST API return labels of nodes that are removed? Can I get
all labels of existing nodes?
Code can be found at: https://github.com/Stofkn/node-neo4j (main.js method
listAllLabels)

C# Binary Formatters - Deserialization throws IO exception

C# Binary Formatters - Deserialization throws IO exception

So I have a serialized binary file with some contents in it and I'm trying
to deserialize it.
I have:
try
{
using (Stream stream = File.Open(file, FileMode.Open))
{
BinaryFormatter bin = new BinaryFormatter();
var contents = bin.Deserialize(stream);
}
}
catch (IOException io)
{
Debug.LogError(io.ToString());
}
But I get an IO Exception
System.IO.FileNotFoundException: Could not load file or assembly
'Packaging Tool, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or
one of its dependencies. The system cannot find the file specified. File
name: 'Packaging Tool, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null'
That's the start of the file itself. I tried it in a console application
and it works perfectly, but when I import it into Unity3D, things get
messy. Does someone know where the root of the problem may be?
Also, when I comment the line with bin.Deserialize, the exception disappears.

Displaying dates using vbnewline in vb.net

Displaying dates using vbnewline in vb.net

I have two datetime pickers in vb.net that calculate the number of days
between two dates and display in a message box the number of days. I want
the number to display in a text box using vbnewline or any method but NOT
to display in a messageBox
Private Sub btnCalculate_Click(sender As System.Object, e As
System.EventArgs)Handles btnCalculate.Click
If True Then
Dim dt1 As DateTime = Convert.ToDateTime(DateTimePicker1.Text)
Dim dt2 As DateTime = Convert.ToDateTime(DateTimePicker2.Text)
Dim ts As TimeSpan = dt2.Subtract(dt1)
If Convert.ToInt32(ts.Days) >= 0 Then
MessageBox.Show("Total Days are " & Convert.ToInt32(ts.Days))
Else
MessageBox.Show("Invalid Input")
End If
End If
End Sub
Any input appreciated

Tuesday, 17 September 2013

install4j Unix installer supported on AIX?

install4j Unix installer supported on AIX?

Will a Unix installer created with install4j work on AIX as well? Or is
there a way/need to create installers for different flavors of Unix? I
would have tried it on AIX but I don't have ready access at this moment.
Thanks in advance

Rename Couchbase Document (Without Sending/Receiving Contents)?

Rename Couchbase Document (Without Sending/Receiving Contents)?

Is there a command to rename Couchbase documents without having to
transfer the document contents?
Preferably with the C# client.

Is ther a JS Help Framework?

Is ther a JS Help Framework?

Is there a javascript framework that help my end-users to easily use a
website?
A framework to become possible from a config file that I specify wich
buttons, divs and etc. need some informations about how to easily use a
site.

Play Framework Scala Template

Play Framework Scala Template

I've worked around with Play Framework for a while but I'm almost new to
Scala Templates . For me as a C-familiar language developer sometimes it
looks a bit strange
I was wondering if someone here could help me understand this code better
I took it from http://www.playframework.com/documentation/2.2.x/JavaGuide3
(Zentask Example)
@(projects: List[Project], todoTasks: List[Task])
@main("Welcome to Play") {
<header>
<hgroup>
<h1>Dashboard</h1>
<h2>Tasks over all projects</h2>
</hgroup>
</header>
<article class="tasks">
@todoTasks.groupBy(_.project).map {
case (project, tasks) => {
<div class="folder" data-folder-id="@project.id">
<header>
<h3>@project.name</h3>
</header>
<ul class="list">
@tasks.map { task =>
<li data-task-id="@task.id">
<h4>@task.title</h4>
@if(task.dueDate != null) {
<time datetime="@task.dueDate">
@task.dueDate.format("MMM dd
yyyy")</time>
}
@if(task.assignedTo != null &&
task.assignedTo.email != null) {
<span
class="assignedTo">@task.assignedTo.email</span>
}
</li>
}
</ul>
</div>
}
}
</article>
}
This 3 lines are really confusing for me :
@todoTasks.groupBy(_.project).map {
case (project, tasks) => {
@tasks.map { task =>
I do appreciate if anyone can explain me in more details what exactly
these 3 lines are doing?
Thanks guys

Generate Any number of Rects in pygame

Generate Any number of Rects in pygame

I thought you guys might be able to help me wrap my head around this. I
want to be able to generate rects and assign images to those rects. I've
been doing this for the whole project and isn't too hard. The hard part
here is that I want this particular function to be able to generate as
many different rects as I want. The project is a game that takes place on
like a chess board. I figure I can write like... if statements for every
single space and then have like a bazillion parameters in the function
that dictate which rects get generated and where, but I was hoping someone
might be able to think of a more elegant solution.

Limit internal dependencies lookups to inner repository

Limit internal dependencies lookups to inner repository

Is there a way to express this: groupId % artifactId % versionId onlyFrom
http://myInternalRepo/ My idea is to avoid to ask for my
private/unpublished artifacts all around the world.

Sunday, 15 September 2013

when i click login button it shows eror on con.open()

when i click login button it shows eror on con.open()

Public Class frmLogin Dim con As New SqlConnection("Data
Source=.\sqlexpress;Integrated Security=True;database=F:\a\Super Market
Management System\Super Market Management System\db_SuperMarket.mdf")
Private Sub frmLogin_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
End Sub
Private Sub btnReset_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnReset.Click
txtUsername.Clear()
txtPassword.Clear()
End Sub
Private Sub btnClose_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnClose.Click
Me.Close()
End Sub
Private Sub btnLogin_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnLogin.Click
Dim a, b As String
a = txtUsername.Text
b = txtPassword.Text
Dim flag As Integer = 0
con.Open()
Dim cmd As New SqlCommand("select * from tbl_Login", con)
Dim rd As SqlDataReader
rd = cmd.ExecuteReader()
While (rd.Read())
If (a = rd(0).ToString.Trim() And b = rd(1).ToString.Trim()) Then
flag = 1
Exit While
Else
flag = 0
End If
End While
If (flag = 1) Then
'MsgBox("Login Successfull", MsgBoxStyle.OkOnly, "Done")
Me.Hide()
Form1.Show()
Else
MsgBox("User Name or Password may be wrong.",
MsgBoxStyle.Critical, "Error")
End If
con.Close()
End Sub
Private Sub txtPassword_KeyDown(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.KeyEventArgs) Handles txtPassword.KeyDown
If (e.KeyCode = Keys.Enter) Then
btnLogin_Click(sender, e)
End If
End Sub
End Class

I would like a text or hyperlinklink to change when i enter value(s) in a textbox in asp.net

I would like a text or hyperlinklink to change when i enter value(s) in a
textbox in asp.net

A part of my code looks like this, a simple hyperlink to an image.
<a href="http://www.google.com"><img src="Logo.jpg" height= "120";
width="280"; /></a>
I would want it such that i can change the link as many times as i want
but only through a textbox in another form.

Get page creation date Facebook?

Get page creation date Facebook?

I have had a look at the Facebook api, and I don't see anything related to
a creation date, however I do need to get this from a list of about 1000
ID's, so manually getting this date wouldn't be practical.
Is there any tricks anyone can think of to get this?

Importing page styling into a different Wordpress template

Importing page styling into a different Wordpress template

I'm playing around with a wordpress theme from the ground up and want to
pull in a particular page's content into the home page along with any
styling I made in the editor (line breaks, color changes, bolding, etc.).
As of right now, it just pulls the text with no line breaks or anything
else. Here's the code I'm using to pull in the page:
<?php
$home_page_post_id = 15;
$home_page_post = get_post( $home_page_post_id, ARRAY_A );
$content_home = $home_page_post['post_content'];
echo $content_home;
?>
What in the world am I missing? Thanks so much!

How to quote this on Ruby?

How to quote this on Ruby?

i have as string, with these value:
'`~!@#:;|$%^>?,)_+-={][&*(<]./"'
how to declare it on .rb without heredoc?
with heredoc:
bla = <<<_
'`~!@#:;|$%^>?,)_+-={][&*(<]./"'
_
bla.chop!

searching the result from mysql should be display in one alertbox

searching the result from mysql should be display in one alertbox

In the below code i have a php code when i search for a particular
variable ie iam looking for a variable which starts in b.All the variable
which starts in b are displaying one by one in alertbox.But i want to
display in one alert. Actual result:it displays one by one alert
<?php
$search = (isset($_POST['search']) ? $_POST['search'] : null);
mysql_connect("localhost", "root", "") OR die (mysql_error());
mysql_select_db ("slseatapp") or die(mysql_error());
$query = "SELECT * FROM `coursemaster` WHERE `course_code` LIKE
'%$search%' or `course_name` like '%$search%'";
$result = mysql_query($query) or die (mysql_error());
if($result)
{
while($row=mysql_fetch_row($result))
{
echo"<script>alert('ID=$row[0],COURSE CODE=$row[1],COURSE
NAME=$row[2]');</script>";
}
}
else
{
echo "No result";
}
?>
<form action="coursemaster_view" method="post">
<center> SEARCH:<input type="text" name="search"
placeholder="SEARCH"><br></center>
<center> <input type="submit" class="btn-success btn"></center>
</form>

Unit Testing (PHP): When to fake/mock dependencies and when not to

Unit Testing (PHP): When to fake/mock dependencies and when not to

is it better to fake dependencies (for example Doctrine) for unit-tests or
to use the real ones?

Comparing with getClass() when the other item is of a primative datatype

Comparing with getClass() when the other item is of a primative datatype

Is it possible to do something like the following
for (int i = 0; i < chararray.length; i++) {
Character myChar = new Character (chararray[i]);
if (myChar.getClass() == char) {
body of method;
}
}
Basically I want to test whether the value stored at position i of
chararray is of a certain datatype eg. is it A-Z or a number 1-100.
Thanks.

Saturday, 14 September 2013

How to set Text from another layout without using Shared Preferences or putExtra

How to set Text from another layout without using Shared Preferences or
putExtra

I have two textViews in different activity A and B that need to have the
same Value. I can not use putExtra because I am not going from Activity A
to B. I do not want to use Shared Preferences. I do not want to put then
query from a sqlite. Is there a way for me to call for the Text in
Activity A when I am on Activity B ?
I am able to get the Layout value of Activity A from Activity B but not
the text Value in a textView of Activity A
In Activity B
Name1.setText(R.layout.menuview);
That will give me the name value of the xml file. I want the value of a
this textView inside the xml file.
In Activity A
m1a = (TextView) findViewById(R.id.m1a);

SASS - Extend class across multiple files

SASS - Extend class across multiple files

I have a project that uses Compass with SASS/SCSS. It is a single page
application.
I have a master .scss file that holds all of my variables, mixins and
function declarations.
//Master.scss
$foo: 'bar';
@function border($color) {
@return 1px solid $color;
}
// etc.
I have a base.scss file that has the main UI's css.
My system uses AMD to import other modules later on, after load. This
means some stylesheets are loaded after the fact.
Each module, or 'App''s stylesheet imports the master .scss file, which
has all of the variables, etc. The master.scss does not have any actual
class declarations, so there are no duplicate imports when a module is
loaded.
Now, I prefer using @extend over mixins where I am repeating the same
code. Such as:
.a { @extend .stretch; }
Instead of:
.a { @include stretch() },
Which both produce the same result:
.a { position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; }
Doing an extend is better, as then a repeat of that code is not splattered
all over the place. Doing this:
.stretch { @include stretch() }
.a { @extend .stretch; }
.b { @extend .stretch; }
.b { @extend .stretch; }
Only produces:
.stretch, .a, .b, .c { position: absolute; top: 0px; right: 0px; bottom:
0px; left: 0px; }
As opposed to:
.a { position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; }
.b { position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; }
.b { position: absolute; top: 0px; right: 0px; bottom: 0px; left: 0px; }
So we like extend. Now the only problem, is that if I put the extendable
class (.stretch) into the master.scss file, it will copy itself to every
single css page. If I put it into the base.scss file, Compass does not
seem to recognize the class when compiling and so does not extend it.
Not sure what the best way to go to solve this is. My exact question then,
is:
How do I extend a css class across multiple files while only declaring it
once?

No solution for

No solution for

The following code continues to give the error:
*The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local
machine.*
The code below:
var excel = new ExcelQueryFactory("~/App_Data/uploads/" +
tempName);
var usersForImport = from c in excel.Worksheet<User>()
select c;
int count = usersForImport.Count();
for (int i = 0; i < count; i++)
{
User user = new User();
user = usersForImport.Skip(i).First();
db.Users.Add(user);
db.SaveChanges();
}
I have tried 2 solutions from previous posts, as I thought this problem
was identical, but they do not solve the problem. These are to either
install the Microsoft Access Database Engine or set the target platform
for x86.
The code relies on 'linqtoexcel' package.
Has anyone else run into these problems? Any solutions?

Rails date difference between now and created_at in days

Rails date difference between now and created_at in days

Hello i have table with ticket where i have valid_from column in DATETIME
format and validity column in INTEGER. Now i need find out how many days
is ticket active (for how many days it will inactive). Im using integer
converting to getting days but it looks that return not days.
>> valid_from #DATETIME
=> Thu, 12 Sep 2013 18:24:52 UTC +00:00
>> validity #INTEGER
=> 14
>> DateTime.now
=> Sat, 14 Sep 2013 13:17:32 -0500
>> ((valid_from + validity.days) - DateTime.now.utc).to_i
=> 1037228
command ((valid_from + validity.days) - DateTime.now.utc).to_i returned
1037228 days.. where is a mistake ? thank you

Combine an unknown number of .mp3 files

Combine an unknown number of .mp3 files

I have this:
$number = 1;
$mp3 = file_get_contents("http://example.com/text=".$value);
$file = md5($value)."-".$number.".mp3";
file_put_contents($file, $mp3);
$number++;
Result: create abcdef-1.mp3, abcdef-2.mp3, abcdef-3.mp3.
Now I want to combine abcdef-1.mp3 with abcdef-2.mp3 and abcdef-3.mp3.
This works:
file_put_contents('abcdef.mp3',
file_get_contents('abcdef-1.mp3') .
file_get_contents('abcdef-2.mp3') .
file_get_contents('abcdef-3.mp3'));
But is not suitable for my code, because abcdef differ. Numbers too.
I've tried:
$number = 1;
$mp3 = file_get_contents("http://example.com/text=".$value);
$file = md5($value)."-".$number.".mp3";
file_put_contents($file, $mp3);
file_put_contents(md5($value).".mp3", file_get_contents($file));
$number++;
Result: create abcdef-1.mp3, abcdef-2.mp3, abcdef-3.mp3 and abcdef.mp3 but
when I play it's only abcdef-1.mp3. Where is the problem?

Pointers referencing a objects from a structure

Pointers referencing a objects from a structure

Recently I've been learning C++ after only using web programming so far
things have been going quite well working through the cplusplus tutorials.
One thing I'm struggling to get my head around though is the use of
pointers referencing objects in a data structure. Basically:
string mystr;
movies_t amovie; // create new object amovie from structure movies_t
movies_t* pmovie; // create a new pointer with type movies_t
pmovie = &amovie; // reference address of new object into pointer
cout << "Enter movie title: ";
getline(cin, pmovie->title);
cout << "Enter year: ";
getline (cin, mystr);
(stringstream) mystr >> pmovie->year;
cout << endl << "You have entered:" << endl;
cout << pmovie->title;
cout << " (" << pmovie->year << ")" << endl;
Can be written just as easily as:
string mystr;
movies_t amovie;
cout << "Enter movie title: ";
getline(cin, amovie.title);
cout << "Enter year: ";
getline(cin, mystr);
(stringstream) mystr >> amovie.year;
cout << endl << "You have entered:" << endl;
cout << amovie.title;
cout << " (" << amovie.year << ")" << endl;
I understand their use in arrays, but am struggling to grasp why using
pointers would be preferable than referencing the values themselves from a
structure.

php select query to sum quantity of items sold order by date

php select query to sum quantity of items sold order by date

Need some help on this. Thanks in advance!
Here is my first table: table_bill
id table_id status added_date
73 1 1 9/1/2013 0:00
74 8 1 9/1/2013 0:00
75 17 1 9/1/2013 0:00
76 15 1 9/1/2013 0:00
77 20 1 9/1/2013 0:00
78 10 1 9/1/2013 0:00
79 4 1 9/1/2013 0:00
81 8 1 9/1/2013 0:00
82 16 1 9/1/2013 0:00
83 17 1 9/1/2013 0:00
84 14 1 9/1/2013 0:00
85 10 1 9/1/2013 0:00
86 9 1 9/1/2013 0:00
87 8 1 9/2/2013 0:00
88 11 1 9/2/2013 0:00
89 14 1 9/2/2013 0:00
90 2 1 9/2/2013 0:00
91 12 1 9/2/2013 0:00
92 30 1 9/2/2013 0:00
93 14 1 9/2/2013 0:00
94 5 1 9/2/2013 0:00
95 10 1 9/2/2013 0:00
96 2 1 9/2/2013 0:00
97 10 1 9/2/2013 0:00
98 11 1 9/3/2013 0:00
99 8 1 9/3/2013 0:00
100 11 1 9/3/2013 0:00
101 12 1 9/3/2013 0:00
102 20 1 9/3/2013 0:00
103 4 1 9/3/2013 0:00
And here is my second table: table_data
id bill_id item_id quantity
166 73 21 2
167 73 31 1
168 73 115 1
169 73 183 1
170 73 131 8
171 73 170 4
172 73 63 4
173 74 103 1
174 74 187 1
175 74 101 1
177 74 207 1
178 74 136 5
179 74 170 2
180 74 65 2
181 75 25 2
182 75 36 1
183 75 180 1
184 75 65 2
185 75 108 1
187 75 135 2
188 75 141 2
189 75 170 2
190 76 202 1
191 76 118 1
192 76 136 5
193 76 170 3
194 76 63 4
195 77 188 2
196 77 110 1
197 77 63 5
I want to get the sum of each item sold in a day datewise
Here is my query for the same....
$sql = "SELECT ocs.item_id, os.added_date, ocs.quantity FROM table_bill
os, table_data ocs WHERE os.id = ocs.bill_id";
However, i am getting sold item results multiple time for a day
For ex: if item number 1 is sold to 5 different customers in a day, i am
getting 5 different results for item number 1, i want the total number of
sale for that item number in a day.
Any help would be greatly appreciated. Thanks!

Friday, 13 September 2013

obj-c dictionary to url parameter string

obj-c dictionary to url parameter string

Are there any built in methods (or really simple examples, not using
libraries) that can turn a dictionary into a url parameter string (to be
appended to url). I'm expecting something similar to the psuedo below:
objectSerialization(obj){
var ret = "";
for(key in obj){
if(dict[key] is "array"){
ret = objectSerialization(dict[key]);
}else{
ret += key + "=" + dict[key];
}
ret += "&";
}
return ret;
}
Obviously there may be glaring bugs in this example, but the idea is
there. I suppose I could just port this example into obj-c code, but my
question is if there is a more acceptable way of doing this. The main
purpose of this is to build GET request urls with dynamic url parameters,
originally contained in dictionaries. Thanks for any help.

How to configure/reduce tcp segment size

How to configure/reduce tcp segment size

I need to send data from my machine to a remote server over tcp and I need
the data to be fragmented (it's a test). That explains the reason I am
looking for a way to change the segment size to a small number.
I have googled around and I found that we can set MSS using iptables
iptables -A FORWARD -p tcp --tcp-flags SYN,RST SYN -j TCPMSS --set-mss
some-number
However, after more googling, it seems like that solution is used to tell
the server the TCP segment size that my machine can accept versus setting
the segment size on the tcp packets/segments that my machine is sending
over to the server.
I also learnt about MTU and how to change it, but that doesn't seem to be
what I want because I need/want to cut my data up in a higher level (in
the transport level). My questions are 1) how can I set MSS for TCP
segments that my machine is sending? 2) is it possible to do it using
Java?
Sorry for these newbie questions.

background-color getting inherited from body element

background-color getting inherited from body element

I am trying to have two stacked elements with footer
.background
.container-fluid
.footer
Please see my fiddle:
http://jsfiddle.net/z9Unk/309/
I expect green to be shown in background with footer in the bottom.
But it shows black (background-color of body). Why is that?
If I remove background-color from body, then it shows the green background.
How can I show the green background without removing background-color from
body?

JavaDoc: Reduce redundancy for Repeated Method Descriptions

JavaDoc: Reduce redundancy for Repeated Method Descriptions

For example, i have two methods, public Tree<T> addChild(final T data) {}
and public Tree<T> addChild(final T... data) {}, their JavaDocs are
identical. How to put the /** method description */ in one of them, and
use a tag to refer another JavaDoc to the previous one?
Just like, in concept:
/**
* method description
*/
public Tree<T> addChild(final T data) { ... }
/**
* @theTag #addChild(Object)
*/
public Tree<T> addChild(final T... data) { ... }
If i remember it correctly, i once accidentally came across a tag, which
imports the entire method description of a Java native API method. So, it
should be possible.
What is @theTag? Thanks very much!

Get more then 25 comments from a Video

Get more then 25 comments from a Video

I'm having promblems getting more then the default 25 comments per request
in my application. I know I have to set the max-results parameter, but
whenever I try to set it, the application crashes with a
GDataRequestException with the information Execution of request failed.
But the url looks okay:
http://gdata.youtube.com/feeds/api/videos/kpzWVicfdQk?max-results=50
Used code:
string url =
String.Format("http://gdata.youtube.com/feeds/api/videos/{0}?max-results=50",
"kpzWVicfdQk");
YouTubeRequest request = new YouTubeRequest(new
YouTubeRequestSettings("GComments","***"));
Video v = request.Retrieve<Video>(new Uri(url));
Feed<Comment> comments = request.GetComments(v);
Without ?max-results=50 it works perfectly. I tried to set it on new
Uri(url) too, but it does not work there too. Thank you for helping!

Thursday, 12 September 2013

How to ignore system input method when using shortcuts prefixed with C-x or C-c?

How to ignore system input method when using shortcuts prefixed with C-x
or C-c?

Env: OS X 10.8.5
Emacs ver: GNU Emacs 24.3
I'm using the system Chinese input method and found it's very inconvenient
when using shortcuts like C-x or C-c. It will print the words on current
buffer.

Multiple object of shared preference deletes data

Multiple object of shared preference deletes data

I'm using shared preferences throughout my application. I'm having a
problem though. I think my data is being lost on background.
SharedPreferences preferences = getSharedPreferences(pref_data,
Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("isDriverLogin", "True");
editor.putString("driverPassword", driverPassword);
editor.putString("carrierId", carrierId);
editor.putString("CCTID", cctid);
editor.putString("shipment", entityShipment);
editor.putString("isAccepted", "");
editor.commit();
And somewhere in the app I create another object and edit just one portion
of the data
SharedPreferences preferences = getSharedPreferences(pref_data,
Context.CONTEXT_IGNORE_SECURITY);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("isDriverLogin", "True");
editor.commit();
I'm doing this throughout my application. Editing just one or two data.
But at some point my app crashes or the expected behavior is not
happening. This behaviors are dependent on my preference data.
I tried fixing it by just creating one object of share preferences and
always edit them with all the data. For example I have 5 data on shared
preferences. If I just need to edit one, I will still put some data on the
other 4 just to make sure nothing is being overwritten.
Do you guys have any idea?

Issue scrolling with fixed position

Issue scrolling with fixed position

I am having trouble with the scrolling when I use a position:fixed inside
of another position:fixed. The simplest way to demonstrate this issue is
with this fiddle:
http://jsfiddle.net/xDDJb/
I want to be able to scroll with the mousewheel while having the mouse
over the smaller fixed div. I have to keep .wrapper the way it is (aka I
cannot remove the position:fixed).
The context is that I'm using Bootstrap 3 modals and I want to essentially
create this layout in the modal. The BS .modal class uses position: fixed
and creates the same construct as the example's .wrapper.
I would love any suggestions please!

HTML JQuery Ref Passed to Function

HTML JQuery Ref Passed to Function

this is my code. I want the alert("SHOW ME!!") to show but it works all
the way up until that point, so the line before is causing the problem.
Idk how to fix it. Could it be how I'm passing reference to the function?
Thank you!!!
<!DOCTYPE html>
<html>
<head>
<script
src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("#Sub1").click(function(){
readIngred($("#ingredForm"));
});
});
</script>
<script type="text/javascript">
function readIngred(form)
{
var checked;
var checkedBoxes;
//Create an array of checked radio buttons
checked = form.elements["checkSet"];
alert("SHOW ME!!!");
checkedBoxes = new Array(checked.length);
for(var i = 0, j = 0; i < radios.length; i++, j++)
{
if(checked[i].checked == true)
{
checkedBoxes[j] = checked[i];
}
else
j--;
}
var c = 0;
while(checkedBoxes[c] !== null)
{
c++;
}
alert("You picked " + c + " ingredients");
}
</script>
</head>
<body>
<form id="ingredForm">
<ul style="list-style-type:none;">
<li><input type="checkbox" name="checkSet" value="Pep">Pep</li>
<li><input type="checkbox" name="checkSet" value="Mush">Mush</li>
<li><input type="checkbox" name="checkSet" value="Olive">Olive</li>
<li><input type="checkbox" name="checkSet" value="Cheese">Cheese</li>
</ul>
<input type="submit" name="Submit_Button" id="Sub1" value="Send">
</form>
</body>

Shared Preferences not passing data between activities

Shared Preferences not passing data between activities

I've had this issue for a few days now. It would seem that my shared
preferences is not working for when I set my data. The user starts at
main, which displays "oncreate" and then goes to the settings page(Where
the data is automatically set(for now)), when they return to the main
Activity, the data doesn't seem to want to come over. I am using the joda
Time library and I'm trying to calculate the difference between two dates
in time.
Main:(The onCreate Code and onResume code are the same)
public class MainActivity extends Activity {
TextView tv;
Button set;
//CONST
final static long MILLIS_IN_DAY = 86400000;
final static long MILLIS_IN_HOUR = 3600000;
final static long MILLIS_IN_MINUTE = 60000;
long day, hour, minute;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView) findViewById(R.id.textViewx);
set = (Button) findViewById(R.id.setting);
tv.setText("ONCREATE!");
//LOAD DATA
SharedPreferences prefs = getPreferences(MODE_PRIVATE);
long loadedTime = prefs.getLong("quitDate", 0); //Load Settings Data
boolean test = prefs.getBoolean("test", false);
//get Comparison Data
DateTime newDate = new DateTime();
long updateTime = newDate.getMillis();
long diffInMillis = (updateTime-loadedTime);
//Calculate
minute = (diffInMillis/MILLIS_IN_MINUTE)%60;
hour = (diffInMillis/MILLIS_IN_HOUR)%24;
day = (diffInMillis/MILLIS_IN_DAY);
tv.setText(""+Long.toString(loadedTime));
if(test==true){
tv.setText("" + "\nDay|Hour|Minute: " + Long.toString(day)
+":" + Long.toString(hour) + ":" + Long.toString(minute));
}
set.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent x = new Intent(MainActivity.this, Settings.class);
startActivity(x);
}
});
Settings:
import org.joda.time.DateTime;
import android.content.SharedPreferences;
public class Settings extends Activity implements View.OnClickListener {
Button bAbout,bSettings,bFacebook;
//(5000);
final long MILLIS_IN_DAY = 86400000;
final long MILLIS_IN_HOUR = 3600000;
final long MILLIS_IN_MINUTE = 60000;
//Variables
long loadedTime;
int packs;
float cost;
long day, hour, minute, second;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Settings");
setContentView(R.layout.activity_settings);
setUpButtons();
DateTime d1 = new DateTime(2013,9,11,0,0);
long today = d1.getMillis();
//SAVE DATA
SharedPreferences.Editor editor =
getPreferences(MODE_PRIVATE).edit();
editor.putLong("quitDate", today);
editor.putBoolean("test", true);
editor.commit();
minute = (today/MILLIS_IN_MINUTE)%60;
hour = (today/MILLIS_IN_HOUR)%24;
day = (today/MILLIS_IN_DAY);
TextView tv = (TextView) findViewById(R.id.TEMPDATE);
TextView tv2 = (TextView) findViewById(R.id.todayis);
tv2.setText("Today is: " + Long.toString(today));
}

Getting the output to be correct

Getting the output to be correct

My output for the code is this
Clubs : 1 0 0 0 0 1 0 1 0 0 2 0 1
Diamonds : 0 2 1 1 1 0 0 0 0 0 0 0 0
Hearts : 1 2 0 1 1 0 0 0 0 3 0 0 1
Spades : 1 1 2 1 0 1 0 0 0 0 1 1 0
However, I want the output to look like this:
Clubs: 1 0 0 0 0 1 0 1 0 0 2 0 1
Diamonds: 0 2 1 1 1 0 0 0 0 0 0 0 0
Hearts: 1 2 0 1 1 0 0 0 0 3 0 1 1
Spades: 1 1 2 1 0 1 0 0 0 0 1 1 0
In other words, I want it so the numbers line up. However, I can't get my
code to do it. Here's my code:
for (int s=0; s < 4; s++)
{
cout << left << setw(2) << suit[s] << ": ";
for (int t=0; t <13; t++)
{
cout << right << setw(2) << deck[s][t];
if (t==12)
cout <<endl;
}
}

C++ Linked List Access Violation

C++ Linked List Access Violation

I've tried searching extensively, but all related answers seem to suggest
there is a null pointer somewhere causing trouble. I've checked several
times and it is possible I'm just blatantly missing it. However since the
error will always occur at the end of the node::node(const myObject&
newmyObject) function no matter how much gibberish I put after the
myObject data = newmyObject;, and before returning to tail = head; I am
honestly at a loss.
This is a first year programming task and neither the lectures nor the
textbook go into any detail on a linked list involving objects, so any
direction would be appreciated.
Exact error when using Visual Studio debugger: First-chance exception at
0x00E38FFB in Assignment1.exe: 0xC0000005: Access violation writing
location 0xCCCCCCCC.
node.h
class node
{
public:
node* next;
myObject data();
node();
node(const myObject& newmyObject);
private:
};
node.cpp
node::node()
{
next = NULL;
}
node::node(const myObject& newmyObject)
{
next = NULL;
myObject data = newmyObject;
} // << crashes upon reaching the end of this, statements between
newmyObject and here will execute fine
LinkedList.h
class LinkedList
{
public:
LinkedList();
void addmyObject(myObject* newmyObject);
private:
int size;
node* head;
node* tail;
};
LinkedList.cpp
LinkedList::LinkedList()
{
node* head = NULL;
node* tail = NULL;
myObject* tempmyObject;
}
void LinkedList::addmyObject(myObject* newmyObject)
{
myObject * tempmyObject = newmyObject;
if (head == NULL)
{
head = new node(*tempmyObject);
tail = head;
}
else
{
node* newNode = new node(*tempmyObject);
tail->next = newNode;
tail = newNode;
}
}

Wednesday, 11 September 2013

some .asax .svc files become empty after deploy

some .asax .svc files become empty after deploy

We use msdeploy to push our services(about 10 services) to AWS EC2.
Here is my step:
1.Create instance in AWS.
2.Deploy all services to AWS one by one.
3.Terminate the instance created in step 1.
4.Snap a new image based on the terminated instance.
5.Launch instances based on the new image.
It's strange that after deploy (step 2), the Global.asax and *.svc files
in the last service become empty.
I checked the source files in PackageTmp, they are not empty.
Does anyone have idea about this?
Thank you.

Waiting for a promise?

Waiting for a promise?

I have the following angularjs code:
$scope.clients = commonFactory.getData(clientFactory.getClients());
if ($scope.clients.length > 0) {
$scope.sampleForm.ClientId = $scope.clients[0].ClientId;
}
And the getData function in commonFactory:
factory.getData = function (method) {
method.then(function (response) {
return response.data;
}, function (error) {
$rootScope.alerts.push({ type: 'error', msg:
error.data.ExceptionMessage });
});
};
The problem is that $scope.clients.length is undefined when it hits that
line because of the async call.
Is there a way to not do my length check until I know that $scope.clients
has been assigned? I've looked at something like this:
$scope.clients =
commonFactory.getData(clientFactory.getClients()).then(function () {
if ($scope.clients.length > 0) {
$scope.sampleForm.ClientId = $scope.clients[0].ClientId;
}
});
Trying to chain my then promises, but no dice... the goal here is to have
the getData method to avoid a bunch of boilerplate code for catching
errors... maybe I'm going about this wrong?

Fatal error using session_start inside foreach (after migration)

Fatal error using session_start inside foreach (after migration)

When did the problem start?
My hosting provider had to change my site to another server like one week
ago. Since then, one of my scripts is throwing an error. As everything was
working before the changes I'm assuming that the code was initially
correct so I'm totally confused why can this happen and I would like you
to try getting me in the good direction.
The code
The code that is giving problems is the following:
session_start();
$items=$_SESSION['items'];
$_SESSION['numItems']=0;
session_write_close();
foreach($items as $num => $currentItem){
//here I work with $currentItem...
session_start();//starting error line
$_SESSION['numItems']++;
session_write_close();
}
session_start();
unset($_SESSION['numItems']);
session_write_close();
The error
If I run the code I get a PHP Fatal error: Maximum execution time of 30
seconds exceeded in the line commented as starting error line.
Now, the weirdest thing is that if I check the value of
$_SESSION['numItems'] it can arrive to 12500 (or more) when the array
$items cannot have more than 250 elements. So something is creating kind
of an infinite loop!
Things to have into account
If I comment out the three session lines inside the foreach structure (or
I move them outside) everything works fine.
If I comment out only the second of those lines, the problem persists.
The same code structure but with a while instead of a foreach is working
in another script on the same server.
My hosting provider cannot say me which PHP version and configuration did
I have. Now, the version is 5.2.17.
Thank you for your help!

Titanium Appcelerator Social logins

Titanium Appcelerator Social logins

Without using plugins like social.js, birdhouse.js or codebird.js.. Is it
possible to create social logins, tweets and so on using authentication
provider api docs.. Because javascript approach for google login is same
for all web projects so if we do it, it has to work in ios and also
android. Many solutions for social sharing in Appcelerator are platform
based, then what is the meaning in cross-platform. If I understood
anything wrong, please do suggest me right path. Thanks in advance.

html - positioning element to right side

html - positioning element to right side

i am trying to make something like this with css3 but i don't know how to
position search button to be on the right side of 'result' div. not after
the labels

<div id="ResultBox" style="margin-right:10px;margin-top:5px;
height:90%;">
<div class="result" style="display:inline;">
<div style="height:100px; width:150px;">
Name:
<label>Mojtaba Iranpanah</label><br>
Email:
<label>00000000</label><br>
Phone Numner:
<label>00000000</label>
</div>
<div class="btn" style="float:right;">
<button>Search!</button>
</div>
</div>
</div>

Porting C++ code from windows to linux about template specification in a nested struct

Porting C++ code from windows to linux about template specification in a
nested struct

There is a section codes which work well in windows. But it can not be
compiled in linux.
template< class p_true, class p_false >
struct sic
{
template< bool b >
struct condition { typedef p_true ctype; };
template<>
struct condition < p_false > { typedef p_false ctype; };
};
I recevied compile error:explicit specialization in non-namespace scope
'struct sic' Anyone have any idea how to resolve it? Thanks very much.

Tuesday, 10 September 2013

mapping json returned from controller to strongly typed view

mapping json returned from controller to strongly typed view

Here is my strongly typed view
@using ( Html.BeginForm("Index", "Home",null, FormMethod.Post, new {
id="FormPost" }))
{
@Html.TextBoxFor(x => x.Name) @Html.ValidationMessageFor(x => x.Name)
<br />
@Html.TextBoxFor(x => x.LastName) @Html.ValidationMessageFor(x =>
x.LastName)
<br />
@Html.TextBoxFor(x => x.Age) @Html.ValidationMessageFor(x => x.Age)
<br />
<input type=submit value="submit" />
<br /><br />
}
This is the view model class:
public class MyViewModel
{
[Required(ErrorMessage="Please enter first name") ]
public string Name { get; set; }
[Required]
public string LastName { get; set; }
[Required]
public int Age { get; set; }
}
I post the form back to the Index action method using the script below
ReusableJqueryPost.prototype.CommonPost = function (formId) {
var fid = $("#" + formId);
var validated = $(fid).valid();
if (validated) {
$.ajax({
type: 'POST',
url: $(fid).attr('action'),
data: $(fid).serialize(),
accept: 'application/json',
error: function (xhr, status, error) {
alert('error: ' + xhr.responseText + '-' + error);
},
success: function (response) {
alert('DATA SAVED!');
var resp = response;
}
});
}
};
The Index Action method can now return as ActionResult
return View(objMyViewModel);
or as or JsonResult
return Json(objMyViewModel);
If I was not using a jquery post and was returning data as an ActionResult
then I wouldnt need to do anything on the client side. Asp.net MVC would
take care of binding the values to the appropriate text boxes on account
of the @Html.TextBoxFor(....)
Since I am using a jquery post to post to the action method and returning
data as JsonResult , I want this same flexibility of auto-binding each
element in the json string to the respective Html.TextBoxFor(...)
textboxes instead of having to use jquery to find the textboxes or
selectboxes( if there are any) and then binding the data to it based on
the values received in the json string.
Questions
Is this possible under some feature of asp.net mvc out of the box?
Is the only option available there to use jquery to find the textboxes or
dropdowns or any other input element by name/id and then assign the value
from the json string
Is there any way I can write this assignment once so that I can reuse the
same code without repeating it all over the project for every view? much
like I have one jquery post method here to be used through out the
project.
Thanks

How to create PDF using itextsharp

How to create PDF using itextsharp

Is there anyone created a report using iTextsharp taking data from sql
database? i was busy searching for the solution online with no luck...
Please if you have a code you are more than welcome to post it or put a link
Please Please Please Help....

How to save or modify files from a browser

How to save or modify files from a browser

OK, so my question today is a bit vague, but it's one that a lot of people
seem to be asking. Is there anyway to save a file from an HTML page that
isn't strictly IE specific? I am trying to write an HTML page that opens
and XML file and lets you edit the file in the page and save it. Obviously
as a general practice this is bad, since there are huge security
implications with writing files using scripts, but there must be some way.
I am using JavaScript for most of the manipulation of the data, but after
I make changes to the XML file, I want to be able to see these changes
reflected in the saved copy on my hard disk. What options are there for
something like this?

Canvas - Get position of colour if available

Canvas - Get position of colour if available

Is it possible to get the position of a colour on canvas.
I know you can get the colour at a position like this
context.getImageData( arguments ).data
But I would like to try and find a colour in canvas, so say I would have
this colour black.
rgb(0, 0, 0);
I would like to get the position of that colour if it exists on canvas,
I've asked Google but I only get the Get colour at position which is the
opposite of what I need.

how to exclude all subdirectories of a given directory in the search path of the find command in unix

how to exclude all subdirectories of a given directory in the search path
of the find command in unix

i need to backup all the directory hierarchy of our servers, thus i need
to list all the sub directories of some of the directories in the server.
the problem is that one of those sub directories contains tens of
thousands of sub directories (file with only the names of the sub
directories could take couple of hundreds megabytes and the respective
find command takes very long).
for example if i have a directory A and one sub directory A/a that
contains tens of thousands of sub directories. i want to use the find
command to list all the sub directories of A excluding all the sub
directories of A/a but not excluding A/a itself.
i tried many variations of -prune using the answers in this question to no
avail.
is there a way to use the find command in UNIX to do this?

Compiler Depenedent Error with typedef

Compiler Depenedent Error with typedef

I am trying to compile my project with different compilers. i have a
stable compiled version of the project compiling without any error with
the ARM 4.41 compiler. I want to compiler the exactly same source code
with the ARM 5 compiler and the Win64 compiler. How ever without any
change in the source code, just by switching the compiler from ARM 4.41 to
ARM 5 && ARM 4.41 to Win64 i am getting the following error with the
typedef's.
I am not able to figure it out, why does it behaves so..?
Header file with typedef's - a_stdtypes.h
#define _STD_TYPE_H
typedef unsigned char bool; // Error #84: invalid combination of type
specifiers
typedef unsigned char bit8;
typedef unsigned short bit16;
typedef unsigned long bit32;

http request directed to 2nd server

http request directed to 2nd server

We are developing a sevlet SSO application on Spring platform, composing
of a client and 2 servers. We want to access the 2nd server by showing its
web page with only loging in to the 1st server, by passing a specific Http
request with user info in its customized header from the 1st server to the
2nd one.
Currently we have 2 issues:
"HttpClient" to fetch a web page It seems that the easiest way is to
implement the "HttpClient" class (though I am new to it), and indeed this
works to set up the communication with the 2nd server by acknowledging the
specific header from 2nd server. However, "HttpClient" could only extract
the HTML/XML info from the 3rd server without displaying any web page to
the browser. Can anyone advice me on this issue by returning a normal web
page?
Both "redirect" and "forward" fail To circumvent the first issue, we try
other class/interface as well. First, we try "forward" but instantly
realised it won't work because the 2nd server is in different context.
Then we try the "redirect" but this also won't work because "redirect"
will instruct the browser to send a new Http request and the formatted
Http header (including the user info) will be lost. So both ways fail.
Anyone can suggest better solution to this?
Thanks, Charlie

Monday, 9 September 2013

ending PHPSESSID cookie sessions

ending PHPSESSID cookie sessions

I am having dificulty ending the session cookie. whenever i login and
logout, the browser still shows the "PHPSESSID".
Below is the web address for the php files that I used to build . I have
tried on both "Chrome and Firefox" and still same problem. I do know it is
a big ask for help, but I would appriciate it vey much.
The files are in the source folder with following files. fg-membersite.php
membersite_config.php
https://github.com/simfatic/RegistrationForm/tree/master/source

Sliding Header/NavBar

Sliding Header/NavBar

I have a header but I am stuck at 2 things.
How do I get it all positioned properly? What I want is it to be
positioned as a header with a navbar at the bottom of it, then in that
navbar I want a div that I can make slide around and I want x amount of
tabs.
How would I make the div slide left/right using JavaScript/JQuery? Sorry
if it doesn't make sense.
My code is:
<body>
<div class="header">
<div id="topHeader"> </div>
<div class="navBar">
//buttons/text here
<div id="slider"> </div>
</div>
</div>
</body>

rvm/ruby - bundler not working when trying to create gem skeleton

rvm/ruby - bundler not working when trying to create gem skeleton

I updated my ubuntu version from 12.04 to 13.04 and so had to reinstall
everything... Most things are now working... However, 'bundler' is not.
i.e. when running the following to create a new gem skeleton:
bundle gem np_search
it gives me the following error:
when under rvm ruby v. 2.0.0 (same error seen with 1.9.3)
Unfortunately, a fatal error has occurred. Please see the Bundler
troubleshooting documentation at http://bit.ly/bundler-issues. Thanks!
/home/ismail/.rvm/gems/ruby-2.0.0-p247@global/gems/bundler-1.3.5/lib/bundler/cli.rb:689:in
``': No such file or directory - git (Errno::ENOENT)
from
/home/ismail/.rvm/gems/ruby-2.0.0-p247@global/gems/bundler-1.3.5/lib/bundler/cli.rb:689:in
`gem'
from
/home/ismail/.rvm/gems/ruby-2.0.0-p247@global/gems/bundler-1.3.5/lib/bundler/vendor/thor/task.rb:27:in
`run'
from
/home/ismail/.rvm/gems/ruby-2.0.0-p247@global/gems/bundler-1.3.5/lib/bundler/vendor/thor/invocation.rb:120:in
`invoke_task'
from
/home/ismail/.rvm/gems/ruby-2.0.0-p247@global/gems/bundler-1.3.5/lib/bundler/vendor/thor.rb:344:in
`dispatch'
from
/home/ismail/.rvm/gems/ruby-2.0.0-p247@global/gems/bundler-1.3.5/lib/bundler/vendor/thor/base.rb:434:in
`start'
from
/home/ismail/.rvm/gems/ruby-2.0.0-p247@global/gems/bundler-1.3.5/bin/bundle:20:in
`block in <top (required)>'
from
/home/ismail/.rvm/gems/ruby-2.0.0-p247@global/gems/bundler-1.3.5/lib/bundler/friendly_errors.rb:3:in
`with_friendly_errors'
from
/home/ismail/.rvm/gems/ruby-2.0.0-p247@global/gems/bundler-1.3.5/bin/bundle:20:in
`<top (required)>'
from /home/ismail/.rvm/gems/ruby-2.0.0-p247@global/bin/bundle:23:in `load'
from /home/ismail/.rvm/gems/ruby-2.0.0-p247@global/bin/bundle:23:in `<main>'
when running under the system ruby (i.e. without rvm) ruby version 2.0.0
-bash: /usr/local/bin/bundle: /usr/bin/ruby1.8: bad interpreter: No such
file or directory
I have carried out all the steps in the link in the first error message
but still the problem remained. Also, had a look on google and
stackoverflow but couldn't find anything that fixed the problem...
This is what I get when typing "bundle env"
when in rvm:
Bundler 1.3.5
Ruby 2.0.0 (2013-06-27 patchlevel 247) [x86_64-linux]
Rubygems 2.0.7
rvm 1.22.5 (stable)
GEM_HOME /home/ismail/.rvm/gems/ruby-2.0.0-p247
GEM_PATH
/home/ismail/.rvm/gems/ruby-2.0.0-p247:/home/ismail/.rvm/gems/ruby-2.0.0-p247@global
Gemfile
<No Gemfile found>
Gemfile.lock
<No Gemfile.lock found>
when using system ruby 2.0.0, 'bundle env' just gives me
-bash: /usr/local/bin/bundle: /usr/bin/ruby1.8: bad interpreter: No such
file or directory
I did try to export the ruby path to the .bashrc (something I read online)
by typing this...
sudo ln -s /usr/bin/ruby /usr/local/bin/ruby
But it made no difference.
Many thanks for all your help...

Why the private property does not have the same scope?

Why the private property does not have the same scope?

I am studying module pattern with javascript and the code below is my
first try, a list of tasks. I have a small issue with variable's scope.
In one of my public methods I can access the tasks variable, in another
one I can't. I will try to give more details.
I have my public method "addItem" which basically does a "push" in an
array tasks.push(values); in this moment it works well, my array gets the
new data.
But when I try to show the same variable in my other public method
"deleteTask", example: console.log('deleteTask: ', tasks);. It returns me
"deleteTask: undefined"
In the second code snippet, I am showing, how I access the methods.
Well, basically I am trying to understand, why am I not able to access the
private variable in "deleteTask"? And why can I in "addItem"? What the
difference? It looks like simple, but I am not getting so far.
var todoModule = (function ($) {
var tasks = [];
function doListOfTasks() {
for(var i=0; i<tasks.length; i++){
$('<li>', {
name : 'liTask',
id : 'liTask'+i,
html : tasks[i].title + ' - '
}).appendTo('#listOfTasks');
$('<input>', {
type : 'button',
name : 'delTask',
id : 'delTask'+i,
value : 'Del'
}).appendTo('#liTask'+i);
$('#delTask'+i).data('idTask', i);
}
}
function clearListTasks(){
$('#listOfTasks').html('');
}
return {
init: function(){
this.getListTasks();
},
getListTasks: doListOfTasks,
addItem: function( values ) {
tasks.push(values);
clearListTasks();
this.getListTasks();
console.log('addItem: ', tasks);
},
deleteTask: function(item) {
console.log('deleteTask: ', tasks);
var tasks = $.grep(tasks, function(value, item) {
//console.log('value: ', value);
//console.log('item: ', item);
return value != item;
});
clearListTasks();
doListOfTasks();
}
};
}(jQuery));
My HTML:
Here I am accessing the public methods through events:
<script type="text/javascript">
$( document ).ready(function() {
todoModule.init();
$( '#btnAdd' ).click(function() {
todoModule.addItem({
title: $('#tarefa').val(),
date: '01/01/1999',
flag: 0
});
});
$('ul').on('click', 'input', function() {
var idTask = $('#'+this.id).data('idTask');
todoModule.deleteTask(idTask);
});
});
</script>
I am studying this pattern through this link below:
http://addyosmani.com/resources/essentialjsdesignpatterns/book/#modulepatternjavascript

SQL Server rounding Error, Giving different values

SQL Server rounding Error, Giving different values

I have a Stored Procedure that does a lots of calculation, stores the
results in several temporary table.Finally calculating the sum and
rounding to two decimal and stores in a temporary table and selects that.
All the intermediate and final temporary table has datatype float for the
column of concern.
original Scenario:
Declare @Intermediate table
{
--several other columns
Labor float
--several other columns
};
---Lots of calculation ---xx-----
Declare @Final table
{
--several other columns
LaborTotal float
--several other columns
};
INSERT INTO @Final SELECT ROUND(ISNULL((SELECT SUM([Labor]) FROM
@Intermediate ),0),2) AS LaborTotal;
SELECT * FROM @Final;
Result: 7585.22 --> when rounded //Here is the error Expecting 7585.23
7585.225 --> when not rounded
TestCases :
DECLARE @test float = 7585.225;
SELECT ROUND(@test,2) AS Result; --> results 7585.23
SELECT ROUND(7585.225,2) AS Result --> results 7585.23
Inserted individual values to a temporary table, and then calculated the sum
DECLARE @TmpTable table
(
MaterialAmount float
,LaborAmount float
);
INSERT INTO @TmpTable VALUES (12.10,1218.75);
INSERT INTO @TmpTable VALUES (12.10,1090.125);
INSERT INTO @TmpTable VALUES (12.10,900);
INSERT INTO @TmpTable VALUES (12.10,1632.6);
INSERT INTO @TmpTable VALUES (12.10,1625);
INSERT INTO @TmpTable VALUES (12.10,1118.75);
SELECT ROUND(ISNULL((SELECT SUM(MaterialAmount) FROM @TmpTable), 0),2) AS
MatSum,
ISNULL((SELECT SUM(LaborAmount) FROM @TmpTable), 0) AS
LabSumUnrounded, --> 7585.225
ROUND(ISNULL((SELECT SUM(LaborAmount) FROM @TmpTable), 0),2) AS
LabSum; --> 7585.23
SELECT ROUND(SUM(MaterialAmount),2),
ROUND(SUM(LaborAmount),2) ---> 7585.23
FROM @TmpTable;
Any idea/suggestion why i am getting 0.01 difference in my original
scenario, while getting exact values in all my testcases ? Thanks in
advance.

How to loop through and clean a recursive array (PHP)

How to loop through and clean a recursive array (PHP)

I'm struggling with the final step on a function that I am writing to
clean up a multi-dimensional array. I want the function to loop through
the array (and any sub-arrays) and then return a cleaned array.
Whilst I can use array_walk_recursive to output the cleaned data, I'm
struggling with returning the data as an array in the same structure as
the inputted. Can anyone help? Any help greatly appreciated....
Here's my code:
function process_data($input){
function clean_up_data($item, $key)
{
echo strip_tags($item) . ' '; // This works and outputs all the
cleaned data
$key = strip_tags($item); // How do I now output as a new array??
return strip_tags($item);
}
array_walk_recursive($input, 'clean_up_data');
}
$array = process_data($array); // This would be the ideal usage
print_r($array); // Currently this outputs nothing

Does it matter whether finals are static or not?

Does it matter whether finals are static or not?

Does it matter whether I declare a class constant as static or not?
public class MyClass {
private final static int statConst = 1;
private final int nonStatConst = 2;
}
statConst and nonStatConst can never change since they are final, so even
nonStatConst will be the same in every instance. Does it matter whether or
not I make them static?
(I realise that there would be a difference with just private final int
otherConst;)

Sunday, 8 September 2013

#EANF#

#EANF#

I try to use google.com/chart/infographics/docs/qr_codes and goQR.me, but
neither have an "alphanumeic characteres" option, only complete binary
(UTF8 or ISO) character set. I need only a little alphanumeric
(A-Z,0-9,-,/,etc.), so a string like "http://bit.ly/1234" (a string with
length=18) can be expressed by a Version-1 (21 rows) QR-Code symbol.
Examples:
Good:
https://chart.googleapis.com/chart?chs=250x250&cht=qr&chl=http://bit.ly/12&chld=L|1
Generates a symbol of "http://bit.ly/12" (a string with length=16) with a
version-1 QR-Code. OK! The guide say "... can encode up to 25 alphanumeric
characters", so 16<25, then espected to version-1.
1.1 Bad:
https://chart.googleapis.com/chart?chs=250x250&cht=qr&chl=http://bit.ly/12&chld=M|1
(change L to M), generates a version-2 (25 rows) symbol.
1.2 Bad:
https://chart.googleapis.com/chart?chs=250x250&cht=qr&chl=http://bit.ly/1234&chld=L|1
(change length from 16 to 18), generates a version-2 (25 rows) symbol.

c# .NET Fast (realtime) webresponse reading

c# .NET Fast (realtime) webresponse reading

I got code, that sending GET request and recieves answer in stream. I read
stream with streamreader to end. Here is code:
HttpWebRequest requestGet = (HttpWebRequest)WebRequest.Create(url);
requestGet.Method = "GET";
requestGet.Timeout = 5000;
HttpWebResponse responseGet = (HttpWebResponse)requestGet.GetResponse();
StreamReader reader = new StreamReader(responseGet.GetResponseStream());
StringBuilder output = new StringBuilder();
output.Append(reader.ReadToEnd());
responseGet.Close();
But i dont like that program is waiting until all data recieved before
starting working with response. It would be great if i can do it like
this(pseudocode):
//here sending GET request
do
{
response.append(streamPart recieved);
//here work with response
} while (stream not ended)
I tried streamReader.Read(string, int32_1, int32_2), but i cant specify
int32_2, becouse i dont know how many symbols i recieved. And if i use
ReadToEnd - it waits for all response to load.

Rails Installation of Spree Commerce

Rails Installation of Spree Commerce

Hello im creating my first spree commerce and i did this
rails new spreecommerce
cd spreecommerce
i added this to Gemfile
gem 'spree_auth_devise', github: 'spree/spree_auth_devise', branch:
'2-0-stable'
rails g spree:install
rails s
now i can browse products and categories but /admin URL doesnt work. so i
tried
rake spree_auth:admin:create
but it says an error
rake aborted!
Don't know how to build task 'spree_auth:admin:create'
Im too wonder where are controllers and views located ? not in
spreecommerce/ directory where i installed application, how can i edit
that app ?

Persisting Empty Clob with JPA

Persisting Empty Clob with JPA

I am trying to persist empty clob (read not null) using JPA (Hibernate)
using the following method
public Long createEmptyReport() {
try {
Report report = new Report();
report .setExecState(ExecState.WAIT);
report .setExportContent(oracle.sql.CLOB.getEmptyCLOB());
report = entityManager.merge(report);
return report .getId();
} catch (Exception e) {
//Do nothing
}
I have following mapping in the entity Report
@Lob
@Column(name = "TB_EXPORT_CONTENT", columnDefinition="CLOB NOT NULL")
private java.sql.Clob exportContent;
But when I persist that in the database, it is not an empty clob but a
null. I have tried doing many things but same result. Can someone help me
please.

Reduce MySQL queries by saving result to textfile

Reduce MySQL queries by saving result to textfile

I have an app that is posting data from android to some MySQL-tables
through PHP with a 10 second interval. The same PHP-file does a lot of
queries on some other tables in the same database and the result is
downloaded and processed in the app (with DownloadWebPageTask). I usually
have between 20 and 30 clients connected this way. Most of the data each
client query for is the same as for all the other clients. If 30 clients
run the same query every 10th second, 180 queries will be run. In fact
every client run several queies, some of them are run in a loop (looping
through results of another query).
My question is: if I somehow produce a textfile containing the same data,
and updating this textfile every x seconds, and let all the clients read
this file instead of running the queries themself - is it a better
approach? will it reduce serverload?

Javascript indexOf() not working

Javascript indexOf() not working

I am working on a service that randomly generates a URL and then uploads
some pasted HTML code to the URL with PHP fwrite(). As a precation, I
added a system to check if the URL has already been taken:
var URL = "thehtmlworkshop.com/test4.html";
$('#existingurls').load('existingurls.txt');
var existing = $('#existingurls').html();
var isunique = existing.indexOf( URL );
if (isunique == -1) {
alert('Form submit');
} else {
alert('Whoops! Looks like the randomly generated URL was already taken.
Please try again (this will be automatic in future).');
}
existingurls.txt contains all the created URLs. When I first tried it, to
test what would happen when the URL was a duplicate of a current URL,
instead of using the random 7 letter string generator I just put one of
the URLs already in the txt file.
This is the contents of existingurls.txt:
thehtmlworkshop.com/test1.html
thehtmlworkshop.com/test2.html
thehtmlworkshop.com/test3.html
thehtmlworkshop.com/test4.html
thehtmlworkshop.com/test5.html
Anyway, what should happen is that indexOf searches for all occurances of
'thehtmlworkshop.com/test4.html' and return it's position as 91 or
whatever its position is and it would then tell the user that the randomly
generated URL was taken. However, it seems to return -1 each time because
it always goes to the submit form dialog.
NOTE: Yes, I am using jQuery.

Saturday, 7 September 2013

Generating random Alphanumeric incorporated into button

Generating random Alphanumeric incorporated into button

I've been searching and thinking for a few hours now and can't come up
with a way to have a button click generate a set length alphanumeric value
and then print it eg. "The alphanumeric value is (alphanumeric value put
here)". I might be being stupid and it's blindly obviously but everything
I've come up with and tried just doesn't seem to be working (too many
failed attempts to bother posting code). Just some suggestion and pointers
in the right direction would be helpful.

Can you serialize using a interface collection with interface entries?

Can you serialize using a interface collection with interface entries?

Suppose I have
public interface General extends Serializable {
...
}
and
public class Specific implements General {
...
}
Can I send and object of the type ArrayList<Specific> through an
ObjectOutputStream and deserialize it by casting to List<General>? Will
that work? If not, how should I do it?

SSH most convinent way

SSH most convinent way

I constantly need to log into a remote server and do all kinds of work. I
am using my Mac and every time I have to type in a long command to do
that.
ssh -i ~/key.pem ubuntu@255.255.255.255
I am wondering what would be the easiest way to log into the remote server
without typing in the command everyday.
Handy apple apps are also welcome

Using Orchard CMS is it possible to build an interface for fast list entry?

Using Orchard CMS is it possible to build an interface for fast list entry?

I'm digging into orchard CMS, but I'm a little bit skeptical that I might
not have the ability to do something like create new content items quickly
without posting back to the server.
For example. Let's say I define a content type for a product. One property
a product might have is a collection of variations or similar products
that can maybe be sorted by relevance. (Think a comic book with variant
covers)
Could you build an interface for this where you enter a new product, and
search for and include multiple variant products all from the same client
interface without ever having to post back or do a hard page refresh?
I guess maybe, what I'm really asking is if it would be easy to expose the
content through Web API or something like that, and from there you can
really just build anything.
I'm a little worried about starting down the road of using a nice
framework like this, only to find half-way through that I'm limited by the
framework itself.

End a javaws.exe application

End a javaws.exe application

There is javaws application that starts on launching a JNLP file.
Everything works fine. This javaws application doesn't have any visible
interface,its runs as a background process. Now every time it has to
forcefully killed to restart the application. Now is there any way to end
it without forcefully killing it every time?

Friday, 6 September 2013

MS SQL including 'AND' & 'OR' breaks query

MS SQL including 'AND' & 'OR' breaks query

I'm trying to run a query that selects where db1.specific is equal to
either 'OO' or 'AA', but running my query breaks
Here's what I've tried
SELECT *lots*
FROM db1 INNER JOIN
db2 ON db1.id = db2.id
WHERE (db1.num = 2353) AND (db1.specific = 'OO') OR
(db1.specific = 'AA')
the query runs fine and returns 12 entries without the OR (db1.specific =
'AA'). But with the OR statement added it seems to run a select * or
something (query keeps going, thousands of entries)
I've tried to place the OR differently or re arrange the query but haven't
had any luck.