Thursday, 3 October 2013

Apache Error 503 - only for some countries?

Apache Error 503 - only for some countries?

Today my webserver started acting weird, I'm receiving Error 503
503 Service Temporarily Unavailable
The server is temporarily unable to service your request due to
maintenance downtime or capacity problems. Please try again later.
Strange enough this is only when I'm accessing the site with a german IP ?
I've got this report from some users so I tried myself with around 5
different german proxies, with all of them I'm receiving Error 503, any
other country the website loads fine !
I'm using all default httpd config and never had this happen before, any
ideas ?

Wednesday, 2 October 2013

How does client-side caching of JavaScript work?

How does client-side caching of JavaScript work?

I was wondering how browsers determine when to fetch a script from the
server vs from the cache...
When developing, I never have to clear my cache to see changes. However,
some people often experience problems with their browser caching scripts
and not fetching a newer version. I know you can append a query string to
the filepath to force it to fetch from the server, but in this question
I'm more interested in understanding the mechanics behind the problem. Why
does the cache interfere only sometimes and why does it not effect
everyone the same?
Also, how might this differ from browser to browser? IE, Firefox, Chrome,
etc...
Thanks

How can I make GUI responsive during long iteration?

How can I make GUI responsive during long iteration?

To begin with, I'm relatively new to programming. I went through some
introductory C# training for my new job, and it's the first language I've
worked with.
I recently had a business problem that I decided to solve using C#, both
to save time (I had hoped) and to learn more C# in the process. The
business problem I mentioned was this: I had 600+ Word files that I needed
to audit. For each document, I had to make sure that...
There was no text with strike-through anywhere in the document.
Track Changes was disabled.
There were no pending changes (as in changes that were made while Track
Changes was enabled and have yet to be accepted or rejected).
There were no comments.
It would have been fastest to have my program iterate through all of the
documents, making changes as it went along. But because of the nature of
this assignment I wanted to make the changes manually, limiting the
program's use to generating a list of files (out of the 600) where changes
were necessary, and detailing what changes needed to be made for each of
those files.
So, I have a button that calls up a FolderBrowserDialog.
private void AddFolderButtonClick(object sender, EventArgs e)
{
var folderBrowser = new FolderBrowserDialog();
if (folderBrowser.ShowDialog() != DialogResult.OK)
{
return;
}
this.progressBar1.Visible = true;
this.progressBar1.Style = ProgressBarStyle.Marquee;
this.Cursor = Cursors.WaitCursor;
var args = new
List<string>(Directory.EnumerateDirectories(folderBrowser.SelectedPath));
// Get list of files in selected directory, adding to list of
directories
args.AddRange(Directory.EnumerateFiles(folderBrowser.SelectedPath));
this.displayListBox.BeginUpdate();
foreach (string path in args)
{
if (File.Exists(path))
{
// This path is a file
this.ProcessFile(Path.GetFullPath(path));
}
else if (Directory.Exists(path))
{
// This path is a directory
this.ProcessDirectory((Path.GetFullPath(path)));
}
else
{
Console.WriteLine(Resources.Finder_Invalid_File_Or_Directory,
path);
}
}
this.displayListBox.EndUpdate();
this.progressBar1.Visible = false;
this.progressBar1.Style = ProgressBarStyle.Continuous;
this.Cursor = Cursors.Default;
}
Together, the following two methods iterate through all subdirectories and
files to create a full list of all files below the top level directory
selected through the FolderBrowserDialog:
private void ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
string[] fileEntries = Directory.GetFiles(targetDirectory);
foreach (string fileName in fileEntries)
{
this.ProcessFile(fileName);
}
// Recurse into subdirectories of this directory.
string[] subdirectoryEntries =
Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
{
this.ProcessDirectory(subdirectory);
}
}
private void ProcessFile(string path)
{
Console.WriteLine(Resources.Finder_File_Processed, path);
string fileName = Path.GetFileName(path);
if (fileName == null || fileName.StartsWith(@"~$") ||
this.selectedFilesList.Contains(path))
{
return;
}
this.selectedFilesList.Add(path);
this.filePathsCountLabel.Text = (@"Count: " +
this.selectedFilesList.Count);
this.displayListBox.Items.Add(path);
}
Once all this code has run, I get a full list of documents. I click a
button and the program does what it's supposed to from here on out. Okay,
cool. I mentioned before that half of the reason I chose to use C# to
solve this was for the sake of learning. At this point I've got everything
I need but what I really want to know is how can I implement threading to
make the GUI responsive while the list of files is being generated? I've
looked through several examples. They made sense. For some reason I just
can't get my head around it for this application though. How can I make
the whole process of processing subdirectories and files happen without
locking up the GUI?

App crashed on iOS 7 for Map functionality developed using MKAnnotation, CGBitmapContextCreate and NSOperationQueue

App crashed on iOS 7 for Map functionality developed using MKAnnotation,
CGBitmapContextCreate and NSOperationQueue

Our App has Map and GPS based location tracking functionality. This app is
already uploaded on Apple Store. The App contains following feature:
Map Shows real-time traffic data Shows real-time traffic event (Accident,
Traffic Jam etc.)
User's GPS location tracking The application runs fine for the iOS
versions 5 and 6. We are facing following crashing issue for iOS 7 Beta
while operating Map functionality in the app. We have used the following
features of iOS to render the traffic data and traffic event on Map:
MKAnnotation to render the traffic event
To render the traffic data, app is using the CGBitmapContextCreate function.
context = CGBitmapContextCreate (NULL, self.mapView.frame.size.width,
self.mapView.frame.size.height, 8, // bits per component
bitmapBytesPerRow, colorSpace, kCGImageAlphaPremultipliedLast);
CGContextSetAllowsAntialiasing (context,YES)
Draw the line to display the traffic data on the Bitmap context.
Created bitmap context will be displayed on map using the MKAnnotation API.
App uses the NSOperationQueue to render the traffic and event data because
the user interaction with map is smooth. Following is the snippet of the
code: [queue addOperationWithBlock:^{ [Set the required data], [Update the
UI] }];
Following are two crash logs which gets generated while random operation n
of the Map functionality.
Crash Log - 1
Incident
Identifier: 471EAE21-E118-4E3D-AAAE-D7D82B1D6326
CrashReporter
Key:
bdbf75eb30240449214769478f38830aa7a14f7f
Hardware
Model: iPhone5,2
Process: {Application Name} [246]
Path:
/var/mobile/Applications/4FA0A7F2-4998-4F8F-A4C6-66D849D074B8/{Application
Name}.app/{Application Name}
Identifier: {Application bunald name}
Version: X.X.X.X
Code
Type: ARM (Native)
Parent
Process: launchd [1]
Date/Time: 2013-08-30 14:21:24.523 +0530
OS
Version: iOS 7.0 (11A4449d)
Report
Version: 104
Exception
Type: EXC_BAD_ACCESS (SIGSEGV)
Exception
Subtype: KERN_INVALID_ADDRESS at 0x8000000c
Triggered
by Thread: 0
Thread
0 Crashed:
0 libobjc.A.dylib 0x38ed3b66
objc_msgSend + 6
1 CoreFoundation 0x2ede773c -[__NSSetM
removeObject:] + 92
2 MapKit 0x3002de96 -[MKAnnotationManager
_removeRepresentationForAnnotation:fromCull:] + 490
3 MapKit 0x3004bc54 -[MKAnnotationManager
_removeAnnotation:updateVisible:removeFromContainer:] + 272
4 MapKit 0x3004bb38 -[MKAnnotationManager
removeAnnotation:] + 24
5 SLIM 0x00165828
-[TravelStarViewController
mapView:viewForAnnotation:] (TravelStarViewController.m:1735)
6 MapKit 0x3005ea86 -[MKMapView
annotationManager:representationForAnnotation:] + 74
7 MapKit 0x3002a136 -[MKAnnotationManager
_addRepresentationForAnnotation:]
+ 362
8 MapKit 0x30028c4a -[MKAnnotationManager
updateVisibleAnnotations] +
1034
9 Foundation 0x2f876358 __NSFireTimer + 60
10 CoreFoundation 0x2ee7ae84
__CFRUNLOOP_IS_CALLING_OUT_TO_A_TIMER_CALLBACK_FUNCTION__
+ 12
11 CoreFoundation 0x2ee7aa9e
__CFRunLoopDoTimer + 790
12 CoreFoundation 0x2ee78e26 __CFRunLoopRun +
1214
13 CoreFoundation 0x2ede353c
CFRunLoopRunSpecific + 520
14 CoreFoundation 0x2ede331e
CFRunLoopRunInMode + 102
15 GraphicsServices 0x3387733e
GSEventRunModal + 134
16 UIKit 0x313fc7b0 UIApplicationMain + 1132
17 SLIM 0x000f3fa6
main (main.m:15)
18 SLIM 0x000f3efc start + 36

how to check if attribute changed while using callback after_commit. changed? method not working

how to check if attribute changed while using callback after_commit.
changed? method not working

I am using callback "after_commit" and in that i am using rails "changed?"
method to know if some attributes value changed. I read the documentation
it seems that "changed? and "_was" methods are not supported in after
commit callback its supported in after_save but i dont want to use that.
def some_function
if some_attributes_value_changed?
previous_value = some_attributes_value_was
end
end
What is the alternate to these methods to know if value changed after
database updated.

Tuesday, 1 October 2013

Slider Puzzle problems

Slider Puzzle problems

This is my slider puzzle game. So far it can only do 3x3 games. When I try
and pass the variables l and w (length and width) of the board it doesn't
work. It only works when i set the variables ROWS and COLS as finals. When
I try and change it I get errors. I'm not sure what to do, any help would
be appreciated.
Currently the user can input values that can't do anything at the moment.
When the game is started, a 3x3 board is generated. The user can restart
the game with a different scrambled board but the buttons that solve the
board and the buttons that reset the board to the original state do not
work yet.
public class SlidePuzzle {
public static void main(String[] args)
{
JFrame window = new JFrame("Slide Puzzle");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String length = JOptionPane.showInputDialog("Length");
String width = JOptionPane.showInputDialog("Width");
int l = Integer.parseInt(length);
int w = Integer.parseInt(width);
window.setContentPane(new SlidePuzzleGUI());
window.pack();
window.show();
window.setResizable(false);
}
}
public class SlidePuzzleGUI extends JPanel
{
private GraphicsPanel _puzzleGraphics;
private SlidePuzzleModel _puzzleModel = new SlidePuzzleModel();
This class contains the GUI for the Slider Puzzle
public SlidePuzzleGUI() {
JButton newGameButton = new JButton("New Game");
JButton resetButton = new JButton("Reset");
JButton solveButton = new JButton("I GIVE UP :(");
resetButton.addActionListener(new ResetAction());
newGameButton.addActionListener(new NewGameAction());
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
controlPanel.add(newGameButton);
controlPanel.add(resetButton);
controlPanel.add(solveButton);
_puzzleGraphics = new GraphicsPanel();
this.setLayout(new BorderLayout());
this.add(controlPanel, BorderLayout.NORTH);
this.add(_puzzleGraphics, BorderLayout.CENTER);
}
This is the graphics panel
class GraphicsPanel extends JPanel implements MouseListener {
private static final int ROWS = 3;
private static final int COLS = 3;
private static final int CELL_SIZE = 80;
private Font _biggerFont;
public GraphicsPanel() {
_biggerFont = new Font("SansSerif", Font.BOLD, CELL_SIZE/2);
this.setPreferredSize(
new Dimension(CELL_SIZE * COLS, CELL_SIZE*ROWS));
this.setBackground(Color.black);
this.addMouseListener(this);
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int r=0; r<ROWS; r++) {
for (int c=0; c<COLS; c++) {
int x = c * CELL_SIZE;
int y = r * CELL_SIZE;
String text = _puzzleModel.getFace(r, c);
if (text != null) {
g.setColor(Color.gray);
g.fillRect(x+2, y+2, CELL_SIZE-4, CELL_SIZE-4);
g.setColor(Color.black);
g.setFont(_biggerFont);
g.drawString(text, x+20, y+(3*CELL_SIZE)/4);
}
}
}
}
public void mousePressed(MouseEvent e) {
int col = e.getX()/CELL_SIZE;
int row = e.getY()/CELL_SIZE;
if (!_puzzleModel.moveTile(row, col)) {
Toolkit.getDefaultToolkit().beep();
}
this.repaint();
}
public void mouseClicked (MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered (MouseEvent e) {}
public void mouseExited (MouseEvent e) {}
}
public class NewGameAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
_puzzleModel.reset();
_puzzleGraphics.repaint();
}
}
public class ResetAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
_puzzleModel.tryAgain();
_puzzleGraphics.repaint();
}
}
public class solveAction implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
_puzzleModel.solve();
_puzzleGraphics.repaint();
}
}
}
public class SlidePuzzleModel {
private static final int ROWS = 3;
private static final int COLS = 3;
private Tile[][] _contents;
private Tile[][] _solved;
private Tile _emptyTile;
public SlidePuzzleModel() {
_contents = new Tile[ROWS][COLS];
reset();
}
String getFace(int row, int col) {
return _contents[row][col].getFace();
}
public void reset() {
for (int r=0; r<ROWS; r++) {
for (int c=0; c<COLS; c++) {
_contents[r][c] = new Tile(r, c, "" + (r*COLS+c+1));
}
}
_emptyTile = _contents[ROWS-1][COLS-1];
_emptyTile.setFace(null);
for (int r=0; r<ROWS; r++) {
for (int c=0; c<COLS; c++) {
exchangeTiles(r, c, (int)(Math.random()*ROWS)
, (int)(Math.random()*COLS));
}
}
}
public void tryAgain()
{
}
public void solve()
{
for (int i = 1; i < ROWS+1;i++)
{
for(int j = 1; j < COLS+1;j++)
{
exchangeTiles(i, j, i, j);
}
}
}
public boolean moveTile(int r, int c) {
return checkEmpty(r, c, -1, 0) || checkEmpty(r, c, 1, 0)
|| checkEmpty(r, c, 0, -1) || checkEmpty(r, c, 0, 1);
}
private boolean checkEmpty(int r, int c, int rdelta, int cdelta) {
int rNeighbor = r + rdelta;
int cNeighbor = c + cdelta;
if (isLegalRowCol(rNeighbor, cNeighbor)
&& _contents[rNeighbor][cNeighbor] == _emptyTile) {
exchangeTiles(r, c, rNeighbor, cNeighbor);
return true;
}
return false;
}
public boolean isLegalRowCol(int r, int c) {
return r>=0 && r<ROWS && c>=0 && c<COLS;
}
private void exchangeTiles(int r1, int c1, int r2, int c2) {
Tile temp = _contents[r1][c1];
_contents[r1][c1] = _contents[r2][c2];
_contents[r2][c2] = temp;
}
public boolean isGameOver() {
for (int r=0; r<ROWS; r++) {
for (int c=0; c<ROWS; c++) {
Tile trc = _contents[r][c];
return trc.isInFinalPosition(r, c);
}
}
return true;
}
}
class Tile {
private int _row;
private int _col;
private String _face;
public Tile(int row, int col, String face) {
_row = row;
_col = col;
_face = face;
}
public void setFace(String newFace) {
_face = newFace;
}
public String getFace() {
return _face;
}
public boolean isInFinalPosition(int r, int c) {
return r==_row && c==_col;
}
}
How would I make it so that the user can specify dimensions of the game
board?
EDIT public class SlidePuzzle {
public static void main(String[] args)
{
JFrame window = new JFrame("Slide Puzzle");
window.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
String length = JOptionPane.showInputDialog("Length");
String width = JOptionPane.showInputDialog("Width");
int l = Integer.parseInt(length);
int w = Integer.parseInt(width);
window.setContentPane(new SlidePuzzleGUI());
window.pack();
window.show();
window.setResizable(false);
}
} public class SlidePuzzleGUI extends JPanel {
private GraphicsPanel _puzzleGraphics;
private SlidePuzzleModel _puzzleModel = new SlidePuzzleModel();
public SlidePuzzleGUI(int l, int w) {
JButton newGameButton = new JButton("New Game");
JButton resetButton = new JButton("Reset");
JButton solveButton = new JButton("I GIVE UP :(");
resetButton.addActionListener(new ResetAction());
newGameButton.addActionListener(new NewGameAction());
JPanel controlPanel = new JPanel();
controlPanel.setLayout(new FlowLayout());
controlPanel.add(newGameButton);
controlPanel.add(resetButton);
controlPanel.add(solveButton);
_puzzleGraphics = new GraphicsPanel(l,w);
this.setLayout(new BorderLayout());
this.add(controlPanel, BorderLayout.NORTH);
this.add(_puzzleGraphics, BorderLayout.CENTER);
}
class GraphicsPanel extends JPanel implements MouseListener {
private int ROWS;
private int COLS;
private static final int CELL_SIZE = 80;
private Font _biggerFont;
public GraphicsPanel(int l, int w) {
_biggerFont = new Font("SansSerif", Font.BOLD, CELL_SIZE/2);
this.setPreferredSize(
new Dimension(CELL_SIZE * COLS, CELL_SIZE*ROWS));
this.setBackground(Color.black);
this.addMouseListener(this);
ROWS = l;
COLS = w;
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
for (int r=0; r<ROWS; r++) {
for (int c=0; c<COLS; c++) {
int x = c * CELL_SIZE;
int y = r * CELL_SIZE;
String text = _puzzleModel.getFace(r, c);
if (text != null) {
g.setColor(Color.gray);
g.fillRect(x+2, y+2, CELL_SIZE-4, CELL_SIZE-4);
g.setColor(Color.black);
g.setFont(_biggerFont);
g.drawString(text, x+20, y+(3*CELL_SIZE)/4);
}
}
}
}
public void mousePressed(MouseEvent e) {
int col = e.getX()/CELL_SIZE;
int row = e.getY()/CELL_SIZE;
if (!_puzzleModel.moveTile(row, col)) {
Toolkit.getDefaultToolkit().beep();
}
this.repaint();
}
public void mouseClicked (MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
public void mouseEntered (MouseEvent e) {}
public void mouseExited (MouseEvent e) {}
}
public class NewGameAction implements ActionListener {
public void actionPerformed(ActionEvent e) {
_puzzleModel.reset();
_puzzleGraphics.repaint();
}
}
public class ResetAction implements ActionListener {
@Override
public void actionPerformed(ActionEvent e) {
_puzzleModel.tryAgain();
_puzzleGraphics.repaint();
}
}
public class solveAction implements ActionListener
{
@Override
public void actionPerformed(ActionEvent e)
{
_puzzleModel.solve();
_puzzleGraphics.repaint();
}
}
}

Calling scaled out SignalR

Calling scaled out SignalR

How can I call a scaled out SignalR service?
I hosted locally on dev fabric an MVC 4 application with SignalR hubs. I
have been trying to call it from my client, but I am not seeing my Hubs
handling calls as they should.
I have also seen the topics being created on Azure.
I make the connection to localhost (the server hosting the SignalR)
project is this correct? Should I connect to the Azure Bus address
instead?

How "submitted", "to appear", "accepted" papers are evaluated in a CV=?iso-8859-1?Q?=3F_=96_academia.stackexchange.com?=

How "submitted", "to appear", "accepted" papers are evaluated in a CV? –
academia.stackexchange.com

Assume a search committee is reading my CV and in the publication section
they notice some of my papers are only submitted or claimed to appear in a
journal (or accepted for publication in a journal). …

Integral of repeated convolution of the unit step function

Integral of repeated convolution of the unit step function

Background
Let $\theta$ be the unit step function: $$\theta(x) = \begin{array}{ll}
\left\{ \begin{array}{ll} 0 & x \lt 0 \\ 1 & x\ge 0. \end{array}\right.
\end{array} $$ Further, the convolution of two functions $f$ and $g$ is
the function: $$ (f \star g)(x) = \int_{-\infty}^{\infty} f(x-y)g(y) dy.
$$ Let $\theta^{\star n}(x)$ denote the repated convolution (and not
pointwise multiplication) of the unit step function.
Question
I know that, by simple integration, $$ \theta^{\star n}(x) = \theta(x)
\frac{x^{n-1}}{(n-1)!} $$ but I am unable to follow how this integral was
calculated (the detailed calculations were not provided, just this
result). Can anybody give me a hint? Thank you.

Monday, 30 September 2013

Photo storage / sort

Photo storage / sort

I'm wondering what the best practice is for photo storage. I'm in the
business of storing photos with a user. Each user can have up to 35 photos
and we currently have around a 100k users. I currently reference the
photo's from a database.
My proposed solution is a hash of the photo name like so.
f56c0de1c61fdb926e79e8a0a65bd12930c9.jpg
broke out into directories like so
Photo 1
f5/6c/0d/e1c61fdb926e79e8a0a65bd12930c9.jpg
f5/6c/0d/e1c61fdb926e79e8a0a65bd12930c9_thumb.jpg
Photo2
ec/1c/55/bfb660548a6770238668c4b117d92f.jpg
ec/1c/55/bfb660548a6770238668c4b117d92f_thumb.jpg
database Stored in the database as a comma separated array like so for
sort ordering.
ec1c55bfb660548a6770238668c4b117d92f,ec1c55bfb660548a6770238668c4b117d92f
Is this the most efficient way to do this? and is it scalable? I'm not
sure if the photo hash is to large and I'm also not sure if the directory
size is correct.
I created a more detailed post over on stackoverflow, just not sure where
this question belongs.
http://stackoverflow.com/questions/19106596/how-to-store-photo-on-file-system-and-store-sort-order-in-database

Making XMonad redetect two monitors [migrated]

Making XMonad redetect two monitors [migrated]

I accidentally pressed Meta-Q and xmonad restarted. Now, it has mirrored
the same thing on both of my monitors. How do I get it go back to treating
them as two separate screens?
Things I have tried: - Pressing Meta-Q again - Turning one of the monitors
off and back on
This has happened before, and logging out and back in again worked. But I
don't want to do that every time I accidentally press Meta-Q. This has
started happening since I started using dmenu_run to launch apps.
Previously, Meta-Q would restart xmonad harmlessly (without going into
mirrored mode).

Toggling a absolute DIV is not working after firsttime

Toggling a absolute DIV is not working after firsttime

$('.pallete').hide();
$(document).delegate('.pick', 'click', function () {
var pos = $(this).offset();
var x = pos.left - $(window).scrollLeft() + $(this).width();
var y = pos.top - $(window).scrollTop() + $(this).height();
$('.pallete').css({
top: y + "px",
left: x + "px",
}).show();
});
$(document).delegate('.col', 'click', function () {
var pos = $(this).css('background-color');
$('.pick').css('background-color', pos);
$(this).parents('div').fadeOut();
});
Here is the fiddle, http://jsfiddle.net/zPNk3/5/. The problem is when I
click first time on .pick element the '.palette' element is shown
properly. But when I click next time the same is not working.

How to get a TextView at the bottom of the screen under a listview?

How to get a TextView at the bottom of the screen under a listview?

I'm making a settings screen in my android app. This list of course has a
pre defined set of options (notifications/colors/log out/etc.). So I
decided to create the list statically in xml. Because the list should
equally well display if it has more content than the screen I nested my
LinearLayout within a ScrollView (couldn't use a ListView because I want
to statically define the items in it).
This works fine with the following code now:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/black" >
<TextView
android:layout_width="fill_parent"
android:layout_height="80dp"
android:paddingTop="30dp"
android:text="@string/account_notifications"
android:background="@color/white"
android:layout_marginBottom="1dp"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="80dp"
android:text="@string/colors"
android:background="@color/white"
android:layout_marginBottom="1dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="80dp"
android:text="@string/log_out"
android:background="@color/white"
android:layout_marginBottom="1dp" />
</LinearLayout>
</ScrollView>
As you can see I set the background of the LinearLayout to black and the
items to white, with a marginBottom of 1dp, so that there is a separator
between the list items. I now want the logout TextView always at the
bottom of the screen. In case there are more items than the screen can
hold, the Logout should simply be situated at the end of the list.
To get the logout to the bottom of the screen I found some solutions in
this SO question. I first use the first suggestion like so:
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="fill_parent" >
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/black" >
<TextView
android:layout_width="fill_parent"
android:layout_height="@dimen/list_item_height"
android:text="@string/account_notifications"
android:background="@color/white"
android:layout_marginBottom="1dp"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="@dimen/list_item_height"
android:text="@string/colors"
android:background="@color/white"
android:layout_marginBottom="1dp" />
</LinearLayout>
<TextView
android:layout_width="fill_parent"
android:layout_height="@dimen/list_item_height"
android:text="@string/log_out"
android:background="@color/white"
android:layout_marginBottom="1dp"
android:layout_alignParentBottom="true" />
</RelativeLayout>
</ScrollView>
This surprisingly makes the logout TextView totally disappear. So I tried
the second suggestion like so:
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="@color/black" >
<TextView
android:layout_width="fill_parent"
android:layout_height="@dimen/list_item_height"
android:layout_weight="1"
android:text="@string/account_notifications"
android:background="@color/white"
android:layout_marginBottom="1dp"/>
<TextView
android:layout_width="fill_parent"
android:layout_height="@dimen/list_item_height"
android:layout_weight="1"
android:text="@string/colors"
android:background="@color/white"
android:layout_marginBottom="1dp" />
<TextView
android:layout_width="fill_parent"
android:layout_height="@dimen/list_item_height"
android:text="@string/log_out"
android:background="@color/white"
android:layout_marginBottom="1dp" />
</LinearLayout>
</ScrollView>
But this unfortunately doesn't do anything either. No clue why not.
So my question, does anybody know how I can get my logout to the bottom of
the screen, or in case the list is to long for the screen, to the bottom
of the list.
All tips are welcome!

Sunday, 29 September 2013

Store the line break from textarea , store to database and show on frontend?

Store the line break from textarea , store to database and show on frontend?

Currently I am working on storing textarea paragraph
<textarea rows="10"></textarea>
I can save the whole content but the problem is it does not include line
breaks. I wonder what is the best practice of storing the space/line break
from the textarea to database. Also, I need to prevent the user from
inserting the inside the textarea.
Is it good parctice ?
e.g.
text=replace(text,"/n","<br>")
text=replace(text," ","&nbsp;")
text=replace(text,"<script>","")
text=replace(text,"</script>","")
Thanks

Repeating after wrong answer

Repeating after wrong answer

Today I was messing around and I was trying to create a multiple choice
test. I got this far and it works. I was wondering though, how would I
make it repeat the question if the user got the answer wrong? If anyone
could help me out that would be fantastic! Thanks!
import java.util.Scanner;
public class multipleChoiceTest {
public static void main(String[] args) {
Scanner myScanner = new Scanner(System.in);
System.out.println("What color is the sky?");
System.out.println("A. Blue");
System.out.println("B. Green");
System.out.println("C. Yellow");
System.out.println("D. Red");
String userChoice = myScanner.nextLine();
if (userChoice.equalsIgnoreCase("a")) {
System.out.println("You're right!");
} else {
System.out.println("You're wrong! Try Again.");
}
}

Boolean value is set to true from the start

Boolean value is set to true from the start

Hey i have been trying to make this work, but i can't figure out what the
problem is.
I want the stopValue to be false when i start the app, and then it is
gonna be set by my actions in the app. I have found out boolean values are
false from the start and therefore my start intent is set to false.
This is not my only problem, when i have entered the start kilometers and
my stop kilometers it give me the stop kilometers only. and the result
should have been start - stop kilometers.
I don't know if these problems have a connection. Maybe i don't get the
sharedpreferences part right or maybe it's the putextra or getIntent part.
Thanks for your time.
My main class
public class Main extends Activity{
Button bStart, bStop;
TextView tvView;
Spinner spinner1;
boolean stopValue;
int startkilometer;
String date;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bStart = (Button) findViewById(R.id.bStart);
tvView = (TextView) findViewById(R.id.tvView);
spinner1 = (Spinner) findViewById(R.id.spinner1);
date = getIntent().getStringExtra("datoen");
startkilometer = getIntent().getIntExtra("startkm", 0);
SharedPreferences sp =
getApplicationContext().getSharedPreferences("stopValue", 0);
stopValue = sp.getBoolean("stopper", stopValue);
SharedPreferences sp1 = getSharedPreferences("startkilometer",
Activity.MODE_PRIVATE);
startkilometer = sp1.getInt("startkm", startkilometer);
SharedPreferences sp2 = getSharedPreferences("date",
Activity.MODE_PRIVATE);
date = sp2.getString("datoen", date);
stopValue = getIntent().getBooleanExtra("stopper", stopValue);
if(stopValue){
bStart.setText("Start");
bStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent start = new Intent("com.uniqueapps.runner.START");
startActivity(start);
}
});
}
if(stopValue == false){
bStart.setText("Stop");
bStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent stop = new Intent("com.uniqueapps.runner.STOP");
stop.putExtra("startkm", startkilometer);
stop.putExtra("datoen", date);
startActivity(stop);
}
});
}
KilometerSQL info = new KilometerSQL(this);
info.open();
String data = info.getData();
info.close();
tvView.setText(data);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
SharedPreferences sp =
getApplicationContext().getSharedPreferences("stopValue", 0);
Editor edit = sp.edit();
edit.putBoolean("stopper", stopValue);
edit.commit();
SharedPreferences sp1 =
getApplicationContext().getSharedPreferences("startkilometer", 0);
Editor edit1 = sp1.edit();
edit1.putInt("startkm", startkilometer);
edit1.commit();
SharedPreferences sp11 =
getApplicationContext().getSharedPreferences("date", 0);
Editor edit11 = sp11.edit();
edit11.putString("datoen", date);
edit11.commit();
super.onPause();
}
My start class
public class Start extends Main implements OnClickListener {
Button bStartTur;
EditText etDate, etKm;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.start);
bStartTur = (Button) findViewById(R.id.bStartTur);
bStartTur.setOnClickListener(this);
etDate = (EditText) findViewById(R.id.etdate);
etKm = (EditText) findViewById(R.id.etKm);
Calendar cal = Calendar.getInstance();
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
etDate.setText(format.format(new Date()));
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
String date = etDate.getText().toString();
int startkilometer;
switch (v.getId()) {
case R.id.bStartTur:
startkilometer = Integer.valueOf(etKm.getText().toString());
Intent menu = new Intent("com.uniqueapps.runner.MENU");
menu.putExtra("stopper", false);
menu.putExtra("startkm", startkilometer);
menu.putExtra("datoen", date);
startActivity(menu);
break;
}
}
}
My stop class
public class Stop extends Main implements OnClickListener {
Button bStop;
EditText sqllocations, kilometer;
int startkilometer;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.stop);
bStop = (Button) findViewById(R.id.bstopTur);
bStop.setOnClickListener(this);
sqllocations = (EditText) findViewById(R.id.locations);
kilometer = (EditText) findViewById(R.id.kilometer);
sqllocations.setText("Unknown");
}
@Override
public void onClick(View v) {
int startkilometer;
int slutkilometer;
startkilometer = getIntent().getIntExtra("startkm", 0);
date = getIntent().getStringExtra("datoen");
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.bstopTur:
slutkilometer = Integer.valueOf(kilometer.getText().toString());
int kortekm = (slutkilometer - startkilometer);
try{
String locations = sqllocations.getText().toString();
KilometerSQL entry = new KilometerSQL(this);
entry.open();
entry.createEntry(date, kortekm, locations);
entry.close();
}catch(Exception e){
e.printStackTrace();
}
Intent menu = new Intent("com.uniqueapps.runner.MENU");
menu.putExtra("stopper", true);
startActivity(menu);
break;
}
}
}
My SQL class
public class KilometerSQL {
public static final String KEY_ROWID = "date";
public static final String KEY_KILOMETER = "kilometer";
public static final String KEY_LOCATIONS = "locations";
private static final String DATABASE_NAME = "Kilometerdb";
private static final String DATABASE_TABLE = "kilometertable";
private static final int DATABASE_VERSION = 1;
private DbHelper ourHelper;
private final Context ourContext;
private SQLiteDatabase ourDatabase;
private static class DbHelper extends SQLiteOpenHelper{
public DbHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
// TODO Auto-generated constructor stub
}
@Override
public void onCreate(SQLiteDatabase db) {
// TODO Auto-generated method stub
db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" +
KEY_ROWID + " TEXT NOT NULL, " +
KEY_KILOMETER + " INTEGER, " +
KEY_LOCATIONS + " TEXT NOT NULL);"
);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int
newVersion) {
// TODO Auto-generated method stub
db.execSQL("DROP TABLE IF EXISTS " + DATABASE_TABLE);
onCreate(db);
}
}
public KilometerSQL (Context c){
ourContext = c;
}
public KilometerSQL open(){
ourHelper = new DbHelper(ourContext);
ourDatabase = ourHelper.getWritableDatabase();
return this;
}
public void close(){
ourHelper.close();
}
public long createEntry(String date, int kortekm, String locations) {
// TODO Auto-generated method stub
ContentValues cv = new ContentValues();
cv.put(KEY_ROWID, date);
cv.put(KEY_KILOMETER, kortekm);
cv.put(KEY_LOCATIONS, locations);
return ourDatabase.insert(DATABASE_TABLE, null, cv);
}
public String getData() {
// TODO Auto-generated method stub
String [] columns = new String []{ KEY_ROWID, KEY_KILOMETER,
KEY_LOCATIONS};
Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null,
null, null, null);
String result = "";
int iDate = c.getColumnIndex(KEY_ROWID);
int iKilometer = c.getColumnIndex(KEY_KILOMETER);
int iLocations = c.getColumnIndex(KEY_LOCATIONS);
for (c.moveToFirst();!c.isAfterLast();c.moveToNext()){
result = result + c.getString(iDate) + " " +
c.getString(iKilometer) + " " + c.getString(iLocations) + "\n";
}
return result;
}
}

jQuery does not delete user info

jQuery does not delete user info

I have a php page that uses a jQuery to confirm before deleting data,
Infact when I click delete it doesnt do anything the link doesnt do
anything, I tried my efforts still nothing happens, please assist me
my code teacher.php
<?php
require_once('../auth.php');
?>
<html>
<head>
<title>Silay Institute</title>
<link rel="stylesheet" href="../css/main.css" type="text/css"
media="screen" />
<!--sa poip up-->
<link href="src/facebox.css" media="screen" rel="stylesheet"
type="text/css" />
<script src="lib/jquery.js" type="text/javascript"></script>
<script src="src/facebox.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(document).ready(function($) {
$('a[rel*=facebox]').facebox({
loadingImage : 'src/loading.gif',
closeImage : 'src/closelabel.png'
})
})
</script>
<link rel="stylesheet" href="febe/style.css" type="text/css"
media="screen" charset="utf-8">
<script src="argiepolicarpio.js" type="text/javascript"
charset="utf-8"></script>
<script src="js/application.js" type="text/javascript"
charset="utf-8"></script>
<style>
#mainhhh {
background: none repeat scroll 0 0 #FFFFFF;
border: 8px solid #EEEEEE;
border-radius: 5px 5px 5px 5px;
box-shadow: 0 0 10px #4E707C;
font: 11px "Trebuchet MS",Verdana,Arial,Helvetica,sans-serif;
margin: 5em auto;
position: relative;
text-align: left;
width: 1000px;
}
#mainhhh h1 {
background: none repeat scroll 0 0 #0092C8;
border-bottom: 1px solid #007DAB;
color: #FFFFFF;
font-size: 14px;
margin: 0;
padding: 5px 10px;
text-shadow: 0 1px 0 #007DAB;
}
</style>
</head>
<body>
<div id="mainhhh">
<h1>
<a id="addq" href="index.php" title="click to enter homepage"
style="background-image:url('../images/out.png');
background-repeat:no-repeat; padding: 3px 12px 12px; margin-right:
10px;"></a>
<label for="filter">Filter</label> <input type="text" name="filter"
value="" id="filter" />
<a rel="facebox" href="addteacher.php" id="addq">Add Teacher</a>
</h1>
<table cellpadding="1" cellspacing="1" id="resultTable">
<thead>
<tr>
<th style="border-left: 1px solid #C1DAD7"> Name </th>
<th>ID Number</th>
<th>Work</th>
<th>Gender</th>
<th>Status</th>
<th>Birthday</th>
<th>Advisory</th>
<th> Action </th>
</tr>
</thead>
<tbody>
<?php
include('../connect.php');
$result = mysql_query("SELECT * FROM teacher");
while($row = mysql_fetch_array($result))
{
echo '<tr class="record">';
echo '<td style="border-left: 1px solid
#C1DAD7">'.$row['fname'].' '.$row['mname'].'
'.$row['lname'].'</td>';
echo '<td><div
align="left">'.$row['idnumber'].'</div></td>';
echo '<td><div
align="left">'.$row['work'].'</div></td>';
echo '<td><div
align="left">'.$row['gender'].'</div></td>';
echo '<td><div
align="left">'.$row['status'].'</div></td>';
echo '<td><div
align="left">'.$row['bday'].'</div></td>';
echo '<td><div align="left">';
$sdsd=$row['idnumber'];
$results = mysql_query("SELECT * FROM advisory
WHERE tid='$sdsd'");
while($rows = mysql_fetch_array($results))
{
echo $rows['level'].' section
'.$rows['section'];
}
echo '</div></td>';
echo '<td><div align="center"><a rel="facebox"
href="editprofile.php?id='.$row['id'].'"
title="Click To Edit">Edit Profile</a> | <a
href="#" id="'.$row['id'].'" class="delbutton"
title="Click To Delete">delete</a></div></td>';
echo '</tr>';
}
?>
</tbody>
</table>
</div>
<script src="js/jquery.js"></script>
<script type="text/javascript">
$(function() {
$(".delbutton").click(function(){
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("id");
//Built a url to send
var info = 'id=' + del_id;
if(confirm("Sure you want to delete this update? There is NO undo!"))
{
$.ajax({
type: "GET",
url: "deleteteacher.php",
data: info,
success: function(){
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7"
}, "fast")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>
</body>
</html>
deleteteacher.php
<?php
// This is a sample code in case you wish to check the username from a
mysql db table
include('../connect.php');
if($_GET['id'])
{
$id=$_GET['id'];
$sql = "delete from teacher where id='$id'";
mysql_query( $sql);
}
?>

Saturday, 28 September 2013

Apache: redirect if host doesn't start with www or cdn

Apache: redirect if host doesn't start with www or cdn

My goal is to redirect to domain with www. if both these conditions are met:
current host is not www.example.com
current host is not cdn.example.com
I'm using a .htaccess file with this code, but the second condition is not
honoured:
RewriteCond %{HTTP_HOST} !^www\.example\.com [NC]
RewriteCond %{HTTP_HOST} !^cdn\.example\.com [NC]
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
Thank you

PHP using iconv to convert large files

PHP using iconv to convert large files

I need to convert text files' character encodings without hogging the
server's memory, while the input file is user configured and its size
isn't limited.
Would it be more efficient to wrap an unix's iconv command using exec()
(which I'd rather avoid, although I already use it in the application for
other file operations), or should I read the file line by line and output
it into another file?
I'm thinking working this way:
$in = fopen("in.txt", "r");
$out = fopen("out.txt", "w+");
while(($line = fgets($in, 4096)) !== false) {
$converted = iconv($charset["in"], $charset["out"], $line);
fwrite($out, $converted);
}
rename("out.txt", "in.txt");
Is there any better approach to convert the file fast and efficiently? I'm
thinking this might be rather CPU intensive, but then I believe iconv
itself is an expensive task so I'm not sure if I can make it actually not
eat the server much at all.
Thanks!

list of english sentences?

list of english sentences?

I'm making a very weak python ai where the user inputs a sentence and the
computer answers, just a proof of concept type idea, using the Stanford
POST tagger, and I'd like a txt file of a bunch of random sentences to
test it. Random lines from books, wikipedia, etc. it doesn't really
matter, but preferably grammatically correct and sentences that people
actually use.
If anyone knows of such a file that would be awesome.

java.lang.NullPointerException in Queue

java.lang.NullPointerException in Queue

I have this error when i call the function enqueue to enqueue a stack into
a queue. This the code where the problem is:
ladder.push(start);
ladder.push(helpWord);
this.wordLadders.enqueue(ladder); <--Here is the problem(The code above is
given)
(start and helpWord are string)
where:
private Queue<Stack<String>> wordLadders;
and costractor is:
this.wordLadders = new Queue<Stack<String>>();
Also the function of enqueue is working using stacks, this the code where
A is a stack:
public void enqueue(AnyType value) {
A.push(value);
}
thank you!

Friday, 27 September 2013

new import with imports pre-def

new import with imports pre-def

how to import foo module like this example.
main.py :
import time
from foo import main
return main()
foo.py :
def main()
print 'hello', time.time()
I tried to explain, there are two or more files, I wanted to upload a
import already defined by another file without defining in what will be
loaded, like my example

Django template does not render CSS and Javascript

Django template does not render CSS and Javascript

I have the following folder structure for my project.
-App1
-App2
-App3
-App4
-static
-css
-bootstrap.css
-js
-bootstrap.js
-jquery.js
-tempaltes
-base.html
Now, in my base.html file i have
But, when i view the file the css and javascript does not seem to be
loaded on the page. In my, i have
settings.py
TEMPLATE_DIRS = "Absolute-path-to-base.html"
STATIC_URL = '/static'
STATICFILES_DIRS = 'Absolute-path-to-the above static folder'
As per all the docs and posts what i understood was, we need to keep all
the staticfiles in one place, viz, static folder in my case...and all the
templates (including base.html) in one place. After doing so, i open the
base.html in my browser to view the page...and it does not display the CSS
and the javascript. Instead when i place the file (base.html) in the
static folder things work fine.
Can someone point me in the right direction!

parse "deep" JSON

parse "deep" JSON

I have a multi-level JSON:
{
"1":{
"name":"PHP",
"slug":"/tag/php",
"type":"Tag"
},
"2":{
"name":"JavaScript",
"slug":"/tag/javascript",
"type":"Tag"
},
"3":{
"name":"X-Browser Shadow",
"slug":"/post/x-browser-shadow",
"type":"Post"
}
}
I would like to know what is the best way to parse this JSON, pure JS of
jQuery, i don't care which of them.
Thanks :)

Confused about setting the value of @transactional

Confused about setting the value of @transactional

Can anybody explain me that when I should put readOnly value as true and
when I should set it as false when using it with @Transactional ?

Implementing CSS in jQuery

Implementing CSS in jQuery

Assuming that one is developing a web application which is sufficiently
non-intensive that overhead is not a concern. Is it reasonable to
implement CSS solely in Javascript/jQuery and completely abandon external
css files?
$('<div/>').attr({'id':'special_box'}).addClass('little_box').appendTo('body')
$('<div/>').addClass('little_box').appendTo('body')
$('<div/>').addClass('little_box').appendTo('body')
...
$('.little_box').css({'color':'red'})
$('#special_box').css({'color':'blue'})
Is there anybody advocating this complete conflation? Is there anything
that completely prevents it or makes it evidently unreasonable?

Capacity of textarea

Capacity of textarea

What is the maximum capacity of a textarea that it can accept some
text.The html page is working fine when the text limits to about 130-140
words.But when the text exceeds that limit it doesn't do anything(just
hangs). This text is passed through javascript for some manipulations and
displayed in another textarea. If there is a limit how to make it accept
large amount of text?

Thursday, 26 September 2013

is this linkedlist code a good practice?

is this linkedlist code a good practice?

Hi everyone I am a newbie in C and trying to learn it. I have a simple
query regarding this linkedlist implementation which I found at many
places:
void addNode(node **listhead, int data, int pos){
if(pos<=0 || pos > length(*listhead)+1){
printf("Invalid position provided, there are currently %d
nodes in the list \n", length(*listhead));
return;
}else{
node *current = *listhead;
node *newNode = (node*)malloc(sizeof(node));
if(newNode == NULL){
printf("Memory allocation error\n");
return;
}
newNode->data = data;
newNode->next = NULL;
if (current == NULL){
*listhead = newNode;
return;
}else{
int i = 0;
while(current->next != NULL && i < pos-1){
++i;
current = current->next;
}
if(current->next == NULL){
current->next = newNode;
}
if(i == pos-1){
newNode->next = current->next;
current->next = newNode;
}
}
}
}
int main(){
node *head = NULL;
node **headref = &head;
addNode(headref, 1, 1);
addNode(headref, 2, 2);
addNode(headref, 3, 3);
printList(head);
return 0;
}
my query is here we are creating a pointer to a pointer which is pointing
to NULL. This code works, however I wanted to know if this is a good
practice. If it is not, how should I create my head pointer and pass its
reference to the addNode function.

Wednesday, 25 September 2013

Python script to copy data from an external drive

Python script to copy data from an external drive

I am in the process of writing a a python program to move user profile
data from an externally attached HD to a new computer. I am currently
having trouble getting the python script to recognize the external drive.
The file path seems accurate, but I am getting an error:
Traceback (most recent call last):
File "C:\Users\Eric\Documents\KoelCopy\KoelCopy.py", line 9, in <module>
distutils.dir_util.copy_tree(source, destination)
File "C:\Python33\lib\distutils\dir_util.py", line 124, in copy_tree
"cannot copy tree '%s': not a directory" % src)
distutils.errors.DistutilsFileError: cannot copy tree 'F:\Users\Nick\My
Documents': not a directory
My code is as follows:
import distutils.core
input_source = input('Enter User Name: ')
source_drive = input('Enter source drive letter: ')
directories = ["\\My Documents", "\\Favorites", "\\Desktop"]
for directory in directories:
source = source_drive + ':\\Users\\' + input_source + directory
destination = 'C:\\Users\\' + input_source + directory
distutils.dir_util.copy_tree(source, destination)
I have also noticed if I get this to work coping from the C drive to C
drive I am getting access denied errors. Would this be caused by windows
security or should I be using a different copy command? I also noticed
when I tested just copying the Desktop is was getting an access denied
error on just the desktop.ini file. How would I exclude such files? I know
I have a lot of questions, I appreciate your time.
Thanks!

Thursday, 19 September 2013

How to wrap the jQuery function

How to wrap the jQuery function

Question
I'd like to know the best way I can wrap the jQuery function while
retaining all functionality. Essentially I want to call $('#someId') but
have it operate as $('#' + id + 'someId') by wrapping the function,
modifying the arguments, and passing it through to the original jQuery
function.
Motivation
I have a section of JS that will reuse the same variable winId which is
concatenated and passed to jQuery. Instead of writing
$('#' + winId + 'someId').html();
$('#' + winId + 'someOtherId').css();
...
$('#' + winId + 'someThirdId').text();
throughout the whole file, I want to wrap the jQuery function so I can
just call
$('#someId').html();
$('#someOtherId').css();
...
$('#someThirdId').text();
and and have winId added in before passing through to $.



My attempt
Here's what I'm thinking as a wrapper:
(function(){
var fn = $;
return $ = function(){
for(var i = 0; i < arguments.length; i++){
if(typeof arguments[i] == 'string'){
arguments[i] = /* code to add in winId, omitted */
}
}
return fn.apply(this, arguments);
}
})();
This works great, except that obviously none of the methods like $.ajax
are available:
Uncaught TypeError: Object function (){
for(var i = 0; i < arguments.length; i++){
if(typeof arguments[i] == 'string'){
arguments[i] = /* code to add in winId, omitted */
}
}
return fn.apply(this, arguments);
} has no method 'ajax'
Note: I know I could copy the object over using jQuery.extend($, jQuery),
but I'm interested in a more elegant solution than that if possible.

How to fill an ArrayList from a file while formatting the information at the same time? [on hold]

How to fill an ArrayList from a file while formatting the information at
the same time? [on hold]

I am working on this project here for school and I really am stuck at this
point. Basically I have to take this trivia.txt file that he supplied and
fill an ArrayList with it, that i have somewhat of a clue how to do. But
then I have to format the output so that my program will recognize the
different categories and be able to output them correctly. Here is what he
has written,
"In this assignment you will write an application that simulates a trivia
game. You will be given a text file that contains a set of questions and
answers in six different categories. Your program will select a random
question from each category to be answered by the player. The score will
be displayed at the end of each run.
Input data format: The input file contains questions and answers in
different categories. For each category, the first line indicates the name
of the category. This line will be followed by a number of pairs of lines.
The first line of the pair is the question, and the second line is its
corresponding answer. A blank line separates the categories. Technical
requirements:
„h Create a class called TriviaQuestion that represents a typical question
object.
„h After reading the data, store the information inside ArrayList(s).
„h Be user friendly in your input/output. Ignore cases. Accept partially
correct answers if possible."
Right now as my code will show I am stuck on how to add the info to the
ArrayList in the format that he has specified. I don't want anyone to do
my work for me. I just need nudged in the proper direction. I dont know if
I need many arraylists for each category and if I do, do I need them to be
in seperate classes? This is only my second semester so I'm still pretty
perplexed by these things. There are other jave trivia games online and on
this forum but I can't find any that work in this fashion. Anyway, here is
the code and the text file afterwards....
import java.io.File;
import java.util.ArrayList;
public class TriviaGame {
/**
* I want to make several array lists and then use a random question for
each category. Then compare the user
* answer to the real answer to see if they won. Keep a count of the
correct answers. Ignore case.
*/
//instance fields
private String player; // The player
private int points; // Player's number of points
private String currentAnswer; // Current typed answer
private File gameFile = new File ("trivia.txt");
//constructors
public TriviaGame(String playerName)
{
playerName = player;
points = 0;
}
public TriviaGame(String player, int points, String currentAnswer,
File gameFile, ArrayList<String> triviaQuestion) {
super();
this.player = player;
this.points = points;
this.currentAnswer = currentAnswer;
this.gameFile = gameFile;
}
//Getters and Setters
/**
* @return the player
*/
public String getPlayer() {
return player;
}
/**
* @param player the player to set
*/
public void setPlayer(String player) {
this.player = player;
}
/**
* @return the points
*/
public int getPoints() {
return points;
}
/**
* @param points the points to set
*/
public void setPoints(int points) {
this.points = points;
}
/**
* @return the currentAnswer
*/
public String getCurrentAnswer() {
return currentAnswer;
}
/**
* @param currentAnswer the currentAnswer to set
*/
public void setCurrentAnswer(String currentAnswer) {
this.currentAnswer = currentAnswer;
}
/**
* @return the gameFile
*/
public File getGameFile() {
return gameFile;
}
/**
* @param gameFile the gameFile to set
*/
public void setGameFile(File gameFile) {
this.gameFile = gameFile;
}
//To String Method
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return "TriviaGame [player=" + player + ", points=" + points
+ ", currentAnswer=" + currentAnswer + ", gameFile=" +
gameFile
+ ", getClass()=" + getClass() + ", hashCode()=" + hashCode()
+ ", toString()=" + super.toString() + "]";
}
}
followed by the tester.....
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
import javax.swing.JOptionPane;
public class TriviaGamePlayer {
/**
* @param args
*/
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
File gameFile = new File ("trivia.txt");
ArrayList<String> triviaQuestion = new ArrayList<String>();
Scanner infile = new Scanner(gameFile);
String line;
while(infile.hasNext()){
line = infile.nextLine();
triviaQuestion = line.split();
}
}
}
finally the text file that accompanied it..... note that after the
category it goes to the next line for the question, then the next line for
the answer, the blank line goes in between the categories. It doesnt seem
to format that way on here when I pasted it.
Arts & Literature
What are bongo drums traditionally held between for playing?
The knees
The Hugo Awards are given for the best literature in which genre?
Science fiction
What four-letter girl's name gave Jane Austen the title of a comic novel?
Emma
Andy Warhol was born in what US city?
Pittsburgh
Who wrote the novel "The Chocolate War"?
Robert Cormier
What surname for John in "The Importance of Being Earnest" did Oscar Wilde
take from the seaside town he vacationed at?
Worthing
Geography
What is the modern day equivalent of Dacia?
Romania
What is the capital of Ontario?
Toronto
Which island boasts of being Napoleon's birthplace?
Corsica
What nationality is a Breton?
French
A person from North Carolina is properly known as a what?
North Carolinian
In which country would you find St. Basil's cathedral?
Russia
Entertainment
How old was Marilyn Monroe when she died?
36
Who created the TV series "Twin Peaks"?
David Lynch and Mark Frost
Who was Charlie's roommate in the 1989 movie "Dead Poets Society"?
Richard
What country singer recorded a popular album at Folsom Prison?
Johnny Cash
In a 2003 movie, Diane Lane plays a writer who buys a villa in what region
of Italy?
Tuscany
What country singer recorded a popular album at Folsom Prison?
Johnny Cash
History
What was John F. Kennedy called by his friends?
Jack
In which country do parts of Hadrian's Wall still remain?
Great Britain
How many dogs survived the sinking of the Titanic?
Two
What were the first words Edison spoke into the phonograph he had just
invented?
Mary had a little lamb
When did construction of the Berlin Wall begin?
1961
What did Benjamin Franklin do on April 17, 1790?
He died
Science & Nature
What is February's birthstone?
Amethyst
What occurs when the Sun and the Moon are in conjunction as viewed from
Earth?
A solar eclipse
What is February's birthstone?
Amethyst
What potentially fatal disease is also known as "rabbit fever"?
Tularemia
How many eyelids does a cat have on each eye?
Three
What kind of poisoning is known as plumbism?
Lead poisoning
Hyperopia is the scientific name for what eye condition?
Farsightedness
Miscellaneous
"Lorgnette" is the proper term for a pair of glasses with what?
A handle
What is a Dubbel?
A Belgian beer style
For what game were two jokers originally included in a standard deck of
playing cards?
Euchre
As what type of beans are chickpeas also known as?
Garbanzo
What do you get when you mix scotch, sweet vermouth and angostura bitters?
A Rob Roy
What cut of steak got its name from the New York City coach stop where it
was first served?
Porterhouse

Validation in javascript

Validation in javascript

this is the scenario, I have this form HTML
<form class="mainForm" name="eform" id="eform"
action="/itg/sc_cust_maint_pkg.cust_dml" method="get">
<div id="tab1" class="tab_content">
<div class="rowElem noborder"><label>Customer ID:</label>
<div class="formRight240">
<input type="text" name="p_cust_id_c" id="req"
class="validate[required,maxSize[30]]"/>
</div></span><div class="fix"></div>
What I have to do is validate the required input, and add asterisk to the
label,the working mode is to fix the problems using what we have, so I
have to find a solution using just this. the million question is, how to
validate if p_cust_id_c is required using that class, and once do that
then add an asterisk to the label.

reinitialize an app after reopen it

reinitialize an app after reopen it

I am wondering for a background running app, is there a way to
reinitialize the app (like terminate the app and start the app from the
beginning) when I reopen the app after a long time of suspension? I think
the OS would kill the app when the device is out of memory, so can I do
this manually?

Hibernate: Extra queries, many to many relation

Hibernate: Extra queries, many to many relation

I have a many to many relation with extra columns:
rol 0..* -------- 1..* permission
This are my models:
Rol:
@Table(name = "rol", uniqueConstraints = { @UniqueConstraint(columnNames =
"nombre") })
public class Rol implements Serializable{
@Id
@Column(name = "_id")
private String id;
@Column(name = "nombre")
@NotEmpty
private String nombre;
@Column(name = "descripcion")
private String descripcion;
@Column(name = "status")
private String status;
@NotEmpty
@OneToMany(fetch= FetchType.LAZY, mappedBy = "rolPermiso_pk.rol",
orphanRemoval = true, cascade=CascadeType.ALL)
private Set<Rol_Permiso> permisos = new HashSet<Rol_Permiso>(0);
Permiso:
@Entity
@Table(name = "permiso", uniqueConstraints = {
@UniqueConstraint(columnNames = "nombre") })
public class Permiso implements Serializable {
@Id
@Column(name = "_id")
private String id;
@Column(name = "nombre")
@NotNull
private String nombre;
@Column(name = "descripcion")
private String descripcion;
@Column(name = "status")
private String status;
@OneToMany(fetch = FetchType.LAZY, mappedBy =
"rolPermiso_pk.permiso", cascade = CascadeType.ALL)
private Set<Rol_Permiso> roles = new HashSet<Rol_Permiso>(0);
Rol_Permiso:
@Entity
@Table(name = "rol_permiso")
@AssociationOverrides({
@AssociationOverride(name = "rolPermiso_pk.rol", joinColumns =
@JoinColumn(name = "idRol")),
@AssociationOverride(name = "rolPermiso_pk.permiso", joinColumns =
@JoinColumn(name = "idPermiso"))
})
public class Rol_Permiso implements Serializable{
@EmbeddedId
private Rol_PermisoId rolPermiso_pk = new Rol_PermisoId();
@Column(name = "status")
private String status;
Rol_PermisoId:
@Embeddable
public class Rol_PermisoId implements Serializable{
@ManyToOne
private Rol rol;
@ManyToOne
private Permiso permiso;
Im trying to show a list of roles with their permissions. So I create this
query:
public List<Rol> findAllWithPermissions() {
return mySessionFactory.getCurrentSession().createQuery("select
distinct r from Rol r left join fetch r.permisos").list();
}
And this works, but extra queries are made:
DEBUG: org.hibernate.SQL - select distinct rol0_._id as column1_2_0_,
permisos1_.idPermiso as idPermis6_3_1_, permisos1_.idRol as idRol5_3_1_,
rol0_.descripcion as descripc2_2_0_, rol0_.fechaCreacion as
fechaCre3_2_0_, rol0_.fechaModificacion as fechaMod4_2_0_,
rol0_.fechaSincronizacion as fechaSin5_2_0_, rol0_.nombre as nombre6_2_0_,
rol0_.status as status7_2_0_, permisos1_.fechaCreacion as fechaCre1_3_1_,
permisos1_.fechaModificacion as fechaMod2_3_1_,
permisos1_.fechaSincronizacion as fechaSin3_3_1_, permisos1_.status as
status4_3_1_, permisos1_.idRol as idRol5_2_0__, permisos1_.idPermiso as
idPermis6_3_0__, permisos1_.idRol as idRol5_3_0__ from rol rol0_ left
outer join rol_permiso permisos1_ on rol0_._id=permisos1_.idRol
DEBUG: org.hibernate.SQL - select permiso0_._id as column1_0_0_,
permiso0_.descripcion as descripc2_0_0_, permiso0_.fechaCreacion as
fechaCre3_0_0_, permiso0_.fechaModificacion as fechaMod4_0_0_,
permiso0_.fechaSincronizacion as fechaSin5_0_0_, permiso0_.nombre as
nombre6_0_0_, permiso0_.status as status7_0_0_ from permiso permiso0_
where permiso0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 1
DEBUG: org.hibernate.SQL - select rol0_._id as column1_2_0_,
rol0_.descripcion as descripc2_2_0_, rol0_.fechaCreacion as
fechaCre3_2_0_, rol0_.fechaModificacion as fechaMod4_2_0_,
rol0_.fechaSincronizacion as fechaSin5_2_0_, rol0_.nombre as nombre6_2_0_,
rol0_.status as status7_2_0_ from rol rol0_ where rol0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 1
DEBUG: org.hibernate.SQL - select permiso0_._id as column1_0_0_,
permiso0_.descripcion as descripc2_0_0_, permiso0_.fechaCreacion as
fechaCre3_0_0_, permiso0_.fechaModificacion as fechaMod4_0_0_,
permiso0_.fechaSincronizacion as fechaSin5_0_0_, permiso0_.nombre as
nombre6_0_0_, permiso0_.status as status7_0_0_ from permiso permiso0_
where permiso0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 3
DEBUG: org.hibernate.SQL - select permiso0_._id as column1_0_0_,
permiso0_.descripcion as descripc2_0_0_, permiso0_.fechaCreacion as
fechaCre3_0_0_, permiso0_.fechaModificacion as fechaMod4_0_0_,
permiso0_.fechaSincronizacion as fechaSin5_0_0_, permiso0_.nombre as
nombre6_0_0_, permiso0_.status as status7_0_0_ from permiso permiso0_
where permiso0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 5
DEBUG: org.hibernate.SQL - select permiso0_._id as column1_0_0_,
permiso0_.descripcion as descripc2_0_0_, permiso0_.fechaCreacion as
fechaCre3_0_0_, permiso0_.fechaModificacion as fechaMod4_0_0_,
permiso0_.fechaSincronizacion as fechaSin5_0_0_, permiso0_.nombre as
nombre6_0_0_, permiso0_.status as status7_0_0_ from permiso permiso0_
where permiso0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 7
DEBUG: org.hibernate.SQL - select permiso0_._id as column1_0_0_,
permiso0_.descripcion as descripc2_0_0_, permiso0_.fechaCreacion as
fechaCre3_0_0_, permiso0_.fechaModificacion as fechaMod4_0_0_,
permiso0_.fechaSincronizacion as fechaSin5_0_0_, permiso0_.nombre as
nombre6_0_0_, permiso0_.status as status7_0_0_ from permiso permiso0_
where permiso0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 8
DEBUG: org.hibernate.SQL - select permiso0_._id as column1_0_0_,
permiso0_.descripcion as descripc2_0_0_, permiso0_.fechaCreacion as
fechaCre3_0_0_, permiso0_.fechaModificacion as fechaMod4_0_0_,
permiso0_.fechaSincronizacion as fechaSin5_0_0_, permiso0_.nombre as
nombre6_0_0_, permiso0_.status as status7_0_0_ from permiso permiso0_
where permiso0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 9
DEBUG: org.hibernate.SQL - select permiso0_._id as column1_0_0_,
permiso0_.descripcion as descripc2_0_0_, permiso0_.fechaCreacion as
fechaCre3_0_0_, permiso0_.fechaModificacion as fechaMod4_0_0_,
permiso0_.fechaSincronizacion as fechaSin5_0_0_, permiso0_.nombre as
nombre6_0_0_, permiso0_.status as status7_0_0_ from permiso permiso0_
where permiso0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 2
DEBUG: org.hibernate.SQL - select rol0_._id as column1_2_0_,
rol0_.descripcion as descripc2_2_0_, rol0_.fechaCreacion as
fechaCre3_2_0_, rol0_.fechaModificacion as fechaMod4_2_0_,
rol0_.fechaSincronizacion as fechaSin5_2_0_, rol0_.nombre as nombre6_2_0_,
rol0_.status as status7_2_0_ from rol rol0_ where rol0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 2
DEBUG: org.hibernate.SQL - select permiso0_._id as column1_0_0_,
permiso0_.descripcion as descripc2_0_0_, permiso0_.fechaCreacion as
fechaCre3_0_0_, permiso0_.fechaModificacion as fechaMod4_0_0_,
permiso0_.fechaSincronizacion as fechaSin5_0_0_, permiso0_.nombre as
nombre6_0_0_, permiso0_.status as status7_0_0_ from permiso permiso0_
where permiso0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 6
DEBUG: org.hibernate.SQL - select rol0_._id as column1_2_0_,
rol0_.descripcion as descripc2_2_0_, rol0_.fechaCreacion as
fechaCre3_2_0_, rol0_.fechaModificacion as fechaMod4_2_0_,
rol0_.fechaSincronizacion as fechaSin5_2_0_, rol0_.nombre as nombre6_2_0_,
rol0_.status as status7_2_0_ from rol rol0_ where rol0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 3
DEBUG: org.hibernate.SQL - select permiso0_._id as column1_0_0_,
permiso0_.descripcion as descripc2_0_0_, permiso0_.fechaCreacion as
fechaCre3_0_0_, permiso0_.fechaModificacion as fechaMod4_0_0_,
permiso0_.fechaSincronizacion as fechaSin5_0_0_, permiso0_.nombre as
nombre6_0_0_, permiso0_.status as status7_0_0_ from permiso permiso0_
where permiso0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 4
DEBUG: org.hibernate.SQL - select permiso0_._id as column1_0_0_,
permiso0_.descripcion as descripc2_0_0_, permiso0_.fechaCreacion as
fechaCre3_0_0_, permiso0_.fechaModificacion as fechaMod4_0_0_,
permiso0_.fechaSincronizacion as fechaSin5_0_0_, permiso0_.nombre as
nombre6_0_0_, permiso0_.status as status7_0_0_ from permiso permiso0_
where permiso0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 10
DEBUG: org.hibernate.SQL - select rol0_._id as column1_2_0_,
rol0_.descripcion as descripc2_2_0_, rol0_.fechaCreacion as
fechaCre3_2_0_, rol0_.fechaModificacion as fechaMod4_2_0_,
rol0_.fechaSincronizacion as fechaSin5_2_0_, rol0_.nombre as nombre6_2_0_,
rol0_.status as status7_2_0_ from rol rol0_ where rol0_._id=?
TRACE: org.hibernate.type.descriptor.sql.BasicBinder - binding parameter
[1] as [VARCHAR] - 4
For each rol I get extra queries. I still dont get how hibernate works.
How can I avoid this??

How to disable and enable the scrolling on android ScrollView?

How to disable and enable the scrolling on android ScrollView?

I am a android developer.I also want to use a ScrollView.This ScrollView
need to some time disable scrolling and Some time enable scrolling .But i
can no able to disable the scrolling .How to i implement it .Please help
to me.I also try to use the some code such a s
fullparentscrolling.setHorizontalFadingEdgeEnabled(false);
fullparentscrolling.setVerticalFadingEdgeEnabled(false);
or
fullparentscrolling.setEnabled(false);
But it does not work.

Highcharts - the third line is not displayed properly (jsfiddle included)

Highcharts - the third line is not displayed properly (jsfiddle included)

I have a Highcharts graph that consist of 3 lines - [fiddle here][1]. The
problem is, that the third line (the black one - New York) is not
displayed properly - the points with 0 value are not shown into the graph.
But the zero-points for those 2 previous lines are displayed properly.
Am I missing something or why is the third line incomplete?
Thanks
[1]: http://jsfiddle.net/hHJvq/

Wednesday, 18 September 2013

Interview type questions

Interview type questions

I have an interview coming up, and I was just wondering the easiest way to
explain the following questions:
What is object oriented programming? What is the difference between an
abstract and interface class? Describe an application lifecycle:
I know the "book" definitions, but not like a short interview type answer.
Any help would be appreciated!

Drupal Dropdown Menu

Drupal Dropdown Menu

I am having trouble with my drop down menus. I would like to have multiple
columns under one drop down.
http://jsfiddle.net/Ru3Zv/ here is what I am working with.
#navigation-primary > ul > li > h2, #navigation-primary > ul > li > a {
/* font-size of the first level */
font-size: 1em;
line-height: 40px;
}
#navigation-primary > ul > li > h2 > a, #navigation-primary > ul > li > a {
/* links of the first level */
/* text-transform: uppercase; */
color:white;
font-weight: bold;
text-decoration:none;
/* background: #156aa3; */
background: #1f1f1f;
}
#navigation-primary > ul > li > a.active, #navigation-primary > ul > li >
h2 > a.active {
/* active state of the first level */
background:#1f1f1f;
color:#fff;
}
#navigation-primary > ul > li > a:hover, #navigation-primary > ul > li >
h2 > a:hover, #navigation-primary > ul > li:hover > a, #navigation-primary
> ul > li:hover > h2 > a {
/* hover state of the first level */
background:#1f1f1f;
color:#fff;
}
#navigation-primary .mega a {
/* links color inside panel */
color:white;
}
#navigation-primary .mega a:hover {
/* :hover on links inside panel */
color:white;
/* text-decoration:underline; */
font-size:1.10em
}
#navigation-primary .mega ul.megamenu-2 a {
/* color:#4c4b4b;*/
/* This is the color of the submenu items */
color:#ffffff;
}
#navigation-primary h3, #navigation-primary li.menu-section-title > a {
/* primary links subsection titles */
font-size:1.0em;
/* text-transform:uppercase; */
font-weight: bold;
text-decoration:none
}
#navigation-primary li.menu-leaf-list {
/* child links inside the panel */
/* border-bottom: 1px dashed #e2e2e2;*/
}
.mega {
/* border-top: 10px solid #1f1f1f; */
border-bottom: 4px solid #1f1f1f;
border-left:1px solid #1f1f1f;
/* border-right:1px solid #ccc; */
background:#1f1f1f;
white-space:nowrap !important;
width:auto !important;
}
Under the Services menu I would like to have one column with Managed
Services then the underlined links below that then in a second column have
Consulting Services with the rest of the underlined links below that. This
is similar to http://www.workday.com/.
What would I have to change to get this?

Video Overlay for SMPTE 292m

Video Overlay for SMPTE 292m

I'm trying to find a way to add an overlay to SMPTE 292 video as it is
being transmitted.
I've never really worked with video so I'm trying to avoid making
assumptions that will ruin my day in the future.
The system is essentially like this:
A device(let's say a laptop) generates the video and sends it out on a
wire. Another device is connected at the end(a monitor) that shows the
video. The device I'm looking at making will cut into that wire and
attempt to add an overlay to the video. To be clear, I don't have access
to the source device or the receiving device, so I'll just be playing man
in the middle and manipulating the video after it has been sent out.
Now, in my mind the easiest way to do this would be to read in one frame
of the video, add on the overlay, and send the frame out.
Is this an overly naive approach? The things I've read so far seem to
indicate that video is more complicated than that, and I can understand
that on the lowest levels that it can be more complicated, but are there
software libraries that can be used to accomplish this? I'd prefer
libraries for any high level language like C++, Java, C#, etc but it
doesn't really make a difference.
Also, is there better terminology that I can use to learn more about this?
My only search terms right now are video and overlay which are pretty
ambiguous.

access 2000, sql server not in dropdown when linking

access 2000, sql server not in dropdown when linking

I have a windows 7 machine with access 2000 installed to support legacy
apps. When I try to link a table "SQL Server" is not shown in the
dropdown. I tried to link through code but the driver isn't present. I
forgot how to fix this. I did a fresh install of Office 2000 selecting
only access. Please help. Thanks

Sleeping thread when using Mono Evaluator

Sleeping thread when using Mono Evaluator

I'm doing on the fly compilation using Mono Evaluator, almost everything
is ok but I'm having an issue with Sleep in side evaluated code.
here is piece of sample code:
public class TestClass
{
public static void TestMethod()
{
System.Threading.Thread.Sleep(5000);
Console.WriteLine("Test finish."));
}
}
and here is the code I'm using to execute C# on the fly using Mono Evaluator:
var reportWriter = new StringWriter();
var consoleReport = new ConsoleReportPrinter(reportWriter);
var context = new CompilerContext(new CompilerSettings(), consoleReport);
var eval = new Evaluator(context);
eval.Run(code);
eval.Run(@"
var output = new System.IO.StringWriter();
Console.SetOut(output);
TestClass.TestMethod();");
Then doing:
string result = (string)eval.Evaluate("output.ToString();");
i'm having in "result" the return of executed code. If I dont use Sleep()
inside executed code, everything is ok. But when I do Sleep() then the
line to get "result" is executed without waiting the 5000 miliseconds.
I'm expecting that the code passed to Evaluator.Run sleep as it is
sleeping inside. why it is not happening ?
How can I achive the wait for executed code finish before evaluate result ??
thanks a lot

Extjs: Setting an object's data to be shown in a form

Extjs: Setting an object's data to be shown in a form

I currently have an object with various fields (mostly date fields) as
shown from the console log below. There are more fields than this but all
are similar. Also I am aware that they are all 1970 this is how we set
them on the .net side.
Object {
gasSafeLicenseNo: "3132571",
ngDomesticPipework: "1970-01-01T00:00:00",
lpgDomesticPipework: "1970-01-01T00:00:00"
lpgCentralHeating: "1970-01-01T00:00:00"
lpgDomesticBoats: "1970-01-01T00:00:00"
lpgDomesticCaravans: "1970-01-01T00:00:00"
I have a view with a form in holding all the date fields etc etc..
{
xtype: 'datefield',
labelWidth: 50,
name: 'ngDomesticPipework',
fieldLabel: 'NG'
},
All fields have identical names in the model, view and data object but
will not load into my form ready for editing. I am simply getting the form
element with a component query setting the data to be the object I want to
load and calling load record.
var data = record.get('engineer').gasSafeCard;
gasSafeFormCmp.loadRecord(data);
Thanks folks massive help as always.

button:gravity="right" is not working

button:gravity="right" is not working

i am desinging a xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.05"
android:background="#000000"
android:orientation="horizontal" >
<Button
android:id="@+id/btncancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left|center"
android:background="#CCCCCC"
android:text="Cancel" />
<Button
android:id="@+id/btnadd"
android:layout_width="82dp"
android:layout_height="wrap_content"
android:gravity="right"
android:background="#3399FF"
android:text="Add" />
</LinearLayout>
</LinearLayout>
for button "Add" android:gravity=right is not working.i have give a
layout:margin,then only its moving right.can anyone help me out.

Concat the resulting value in mysql

Concat the resulting value in mysql

Can i concat result value and then send the final value as output.
WHILE(LENGTH(totalexpenseamount )>0) DO
BEGIN
SET totalshipmentexpenseamount =
CONCAT(totalshipmentexpenseamount,',',indshipmentexpenseamount);
END;
END WHILE;
but at end totalshipmentexpenseamount does not have any value in it.

Tuesday, 17 September 2013

How to concatenate data from a SQL Server XML query?

How to concatenate data from a SQL Server XML query?

I have a SQL query that returns me the XML below
<row>
<urlSegment>electronics</urlSegment>
<shortenedUrlSegment>0x58</shortenedUrlSegment>
</row>
<row>
<urlSegment>phones</urlSegment>
<shortenedUrlSegment>0x5AC0</shortenedUrlSegment>
</row>
<row>
<urlSegment>curvy-simplicity</urlSegment>
<shortenedUrlSegment>65546</shortenedUrlSegment>
</row>
etc
The output that I want is is a table with two columns (Url and
ShortenedUrl) with the data concatenated in a url fashion as shown below.
Url | ShortenedUrl
electronics/phones/curvy-simplicity | 0x58/0x5AC0/65546
etc
Can anyone help?
Best of regards

MYSQL view not ordering as expected

MYSQL view not ordering as expected

I have a table of cocktail recipes and other stuff. I have another table
that shows the recipes that have been liked. I want to make a view of the
mentioned recipes in the last day, and if that result is <1000, fill in
the remaining 1000 with random recipes NOT on the FEED table.
Example
Feed: Recipe 1 liked today (1 min ago) (cocktail), Recipe 2 liked
yesterday (not cocktail), recipe 3 liked today (1 hour ago)(cocktail),
recipe 4 liked today (3 minutes ago) (not cocktail).
Recipe table: self explanatory
Category table:
recipe 1, cocktail
recipe 2, juice
recipe 3, cocktail
recipe 4 juice
recipe 3333 cocktail
recipe 4444 cocktail
recipe nnnn cocktail
My View needs to show:
Recipe 1, recipe 4,Recipe 3 (liked in most recent order). THEN to fill the
rest of the 1000, get random from the recipe table: Recipe 4444, recipe
3333, recipe nnnn.
Final result: Recipe 1, recipe 4,Recipe 3, Recipe 4444, recipe 3333,
recipe nnnn
The code below attempts to do this, but the order is wrong (the top
doesn't have recipe 1, 4, 3 in that order. They are mixed around...
CREATE
ALGORITHM = UNDEFINED
DEFINER = `XXXX`
SQL XXXX
VIEW `cocktails` AS
(select
`r`.`name` AS `name`,
`r`.`myId` AS `myId`
from
((`recipe` `r`
join `feed` `f` ON ((`r`.`myId` = `f`.`recipe_id`)))
join `category` `c` ON ((`r`.`myId` = `c`.`recipe_id`)))
where
(`c`.`name` like '%cocktails%')
group by `r`.`name`
order by (max(`f`.`timeStamp`) >= (now() - interval 1 day)) desc ,
(`r`.`myId` is not null) desc)
union
(select
`r`.`name` AS `name`,
`r`.`myId` AS `myId`
from
((`recipe` `r`
join `category` `c` ON (`r`.`myId` = `c`.`recipe_id`)))
where
(`c`.`name` like '%cocktails%')
)
limit 0,1000