Thursday, 3 October 2013

twisted reactor.spawnProcess get stdout w/o bufffering on windows

twisted reactor.spawnProcess get stdout w/o bufffering on windows

I'm running an external process and I need to get the stdout immediately
so I can push it to a textview, on GNU/Linux I can use "usePTY=True" to
get the stdout by line, unfortunately usePTY is not available on windows.
I'm fairly new to twisted, is there a way to achieve the same result on
Windows with some twisted (or python maybe) magic stuff?

Wednesday, 2 October 2013

loading data to my mainform

loading data to my mainform

studentrecords table.,.,contains IDNumber,LastName,Course,Firstname
i will login through my system using IDNumber and once i go to the
mainform iwant to display LASTname and course to the 2 textboxes in the
mainform using the IDNumber as their Primary Key.,.My code errors
Dim con As New OleDbConnection Dim cmd As New OleDbCommand
Dim da As New OleDbDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
'get connection string declared in the Module1.vb and assing it to conn
variable
con = New OleDbConnection(Get_Constring)
con.Open()
cmd.Connection = con
cmd.CommandType = CommandType.Text
sSQL = "SELECT LastName FROM studentsrecords where IDNumber like '%" &
studentslogin.[txtIDNumber].Text & "%' order by ID desc"
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
'evalutionrate.[lbllogin].Text = studentslogin.[txtIDNumber].Text
evalutionrate.[lbllogin].Text = sSQL
evalutionrate.Show()

Amazon availability zones

Amazon availability zones

I'm fairly new to Amazon services and wondering what some of the best
practices are for clustering/load balancing?
I have a load balancer in my colo (NJ) which may potentially be upgraded
to Netscaler.
The application we're hosting on Amazon is nothing crazy and don't expect
too much traffic. We're looking at 2 linux instances that would run a Node
JS application with a MongoDB replica set. From what I understand, Amazon
will evenly divide the traffic amongst the zones. The end-users location
has no effect on where they'll be distributed (ie if I have a server in
the west coast and one in the east coast, the user in the east coast could
be directed to either east or west).
If I wanted to direct users traffic based on location, a global DNS
solution would make more sense?
One server would be the master db and the other would be slave with data
replicating to each other.
Anybody have any experience with this and how is the network performance?
A question about EC2/S3
EC2 Instances and S3 buckets can only communicate if they are in the same
region, correct?

Fixed horizontal ScrollView above ListFragment

Fixed horizontal ScrollView above ListFragment

I am displaying a list using a custom ListFragment. The fragment inflates
a layout and works fine. I want to add a horizontal scrollView above the
fragment to act as a category menu. It must be fixed, so addHeaderView is
not acceptable.
I found a layout example here on SO and plugged it into my layout to how
it could be made to work. But in its current form below, it does what you
would expect - puts a horizontal scrollview in every entry on the list.
So how do I share a screen with a static view on top and the listfragment
below.
Here is the layout that does not work - as I mentioned the Scrollview part
is not mine and is only included as an example. The relativelayout at the
bottom makes the actual list
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="false" >
<HorizontalScrollView
android:id="@+id/hor_svID"
android:layout_width="wrap_content"
android:layout_height="35dip"
android:scrollbars="none"
android:fillViewport="false"
android:focusable="false" >
<!--android:background="@drawable/submenu_bg"> -->
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:orientation="horizontal"
android:focusable="false"
android:background="#FFFFFF"
android:gravity="center">
<TextView android:id="@+id/TechnologyTxtVId"
android:text="TECHNOLOGY"
android:textColor="#342D7E"
android:textSize="12sp"
android:textStyle="bold"
android:gravity="center"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
<TextView android:id="@+id/SportsTxtVId"
android:text="SPORTS"
android:textColor="#342D7E"
android:textStyle="bold"
android:textSize="12sp"
android:gravity="center"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:paddingLeft="15dip"></TextView>
<TextView android:id="@+id/EntntTxtVId"
android:text="ENTERTAINMENT"
android:textStyle="bold"
android:paddingLeft="15dip"
android:textSize="12sp"
android:gravity="center"
android:textColor="#342D7E"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
<TextView android:id="@+id/LocalTxtVId"
android:text="LOCAL"
android:textStyle="bold"
android:paddingLeft="15dip"
android:textSize="12sp"
android:textColor="#342D7E"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
<TextView android:id="@+id/WorldTxtVId"
android:text="WORLD"
android:textStyle="bold"
android:textSize="12sp"
android:paddingLeft="15dip"
android:gravity="center"
android:textColor="#342D7E"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
<TextView android:id="@+id/FeaturesTxtVId"
android:text="FEATURES"
android:textStyle="bold"
android:textSize="12sp"
android:paddingLeft="15dip"
android:gravity="center"
android:textColor="#342D7E"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
<TextView android:id="@+id/RecentTxtVId"
android:text="RECENT"
android:textStyle="bold"
android:textSize="12sp"
android:paddingLeft="15dip"
android:gravity="center"
android:textColor="#342D7E"
android:layout_width="wrap_content"
android:layout_height="wrap_content"></TextView>
</LinearLayout>
</HorizontalScrollView>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:clickable="false" >
<ImageView
android:id="@+id/imageView_thumbnail"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginRight="@dimen/default_padding"
android:contentDescription="@null"
android:focusable="false"
android:src="@drawable/ic_launcher" />
<TextView
android:id="@+id/textView_source"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/imageView_thumbnail"
android:layout_alignParentTop="true"
android:layout_marginRight="@dimen/default_padding"
android:focusable="false"
android:textAppearance="?android:attr/textAppearanceSmall" />
<TextView
android:id="@+id/textView_pubDate"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginRight="@dimen/default_padding"
android:focusable="false"
android:textAppearance="?android:attr/textAppearanceSmall"
/>
<TextView
android:id="@+id/textViewHeadline"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/imageView_thumbnail"
android:layout_alignParentRight="true"
android:layout_below="@+id/textView_pubDate"
android:layout_marginLeft="@dimen/default_padding"
android:focusable="false"
android:textAppearance="?android:attr/textAppearanceMedium"
android:textStyle="bold" />
<TextView
android:id="@+id/textViewSummary"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/textViewHeadline"
android:layout_toRightOf="@+id/imageView_thumbnail"
android:maxLines="@integer/Four"
android:layout_marginLeft="@dimen/default_padding"
android:focusable="false"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RelativeLayout>
</RelativeLayout>

How to get JSON string from Android?

How to get JSON string from Android?

I made web service server application with .Net and this is my JSON output
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://stockcluster.com/">
{
"percentageArray":[85.0,13.0,2.0]
}
</string>
I want to know how to get this string from android. I tried myself but
"cannot convert to JSONObject from string" error occured.
My code is here:
double[] percentageArray = new double[3] {
lowPersentage,
normalPersentage,
highPersentage
};
json = JsonConvert.SerializeObject(new { percentageArray });
return json;
please help me !

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();
}
}
}

Strings in C Issues

Strings in C Issues

I'm wondering what the difference is between
char* str[NUM];
char str[NUM];
char* str;
My understanding is that an array definition such as the one in the middle
points to the address of the first value, that is str[0]. But I also see
the notation represented by the first line of code, that is, a pointer to
an array. Are these three equivalent? I'm aware the array definition sets
space in the stack for NUM characters so is that probably better than just
char* str?
Thanks

One stop solution to stay up to date with new releases in SF & F – scifi.stackexchange.com

One stop solution to stay up to date with new releases in SF & F –
scifi.stackexchange.com

I don't have a bookstore nearby that carries a good selection of SF & F,
so I do all my reading shopping online. Problem is, I don't know what
there is to buy. Where do you guys find out about …

How do you not forget old math=?iso-8859-1?Q?=3F_=96_mathoverflow.net?=

How do you not forget old math? – mathoverflow.net

I am trying to not forget my old math. I finished my PhD in real algebraic
geometry a few years ago and then switched to the industry for financial
reasons. Now I get the feeling that I want to do a …

Monday, 30 September 2013

Grabbing sniffed packet data

Grabbing sniffed packet data

So I have a Fiddler2 capture. In the capture, there was a file that was
downloaded, file.dat. I am trying to extract the downloaded file from the
capture. I can't seem to find any way to do that. Any ideas?

Why can my EC2 instance no longer connect to itself using its public DNS entry?

Why can my EC2 instance no longer connect to itself using its public DNS
entry?

One of our Amazon EC2 instances can no longer connect to itself using its
public DNS . It says "unknown host". Previously, when used from within
EC2, the public DNS resolved to the current internal IP. This is still the
case for another instance we also use.
This has worked for the previous 8 months. Last week, our continuous
integration server on that machine ran into the problem a few times. After
the instance was started today, connecting via public DNS no longer works
at all, even though the elastic IP is definitively attached to the
instance.
Pinging that public DNS entry from elsewhere - both from inside and
outside EC2 - works perfectly fine. The instance can ping itself using the
elastic IP, but we want to connect directly. The instance can also ping
itself using its current internal IP or internal DNS entry, but as that
changes on startup, it is not a solution.
As we did not change the machine configuration in any way for the past two
months, I am reasonably sure this is a problem on Amazon's end. Can anyone
confirm this, has experienced similar issues or a suggestion what to do to
fix this?
Note: we only have the "basic" AWS suppport level, so I can't file an
issue with Amazon about this. I did post this question on the AWS forums,
though.

create a JavaScript object dinamic

create a JavaScript object dinamic

I want to create a calendar using AngularJS, and my model is an object
like this:
$scope.model = {
weeks: [
{
days: [
null,
{
name: "3 dec",
toDoItems: [{ name: "Task 1" }, { name: "Task 2"}]
},
{
name: "4 dec",
toDoItems: [{name: "Task 1"}, {name: "Task 2"}]
}
]
},
{
days: [
null,
{
name: "5 dec",
toDoItems: [{ name: "Task 1" }, { name: "Task 2"}]
},
{
name: "6 dec",
toDoItems: [{name: "Task 1"}, {name: "Task 2"}]
}
]
}
]
}
But I want to create the object dinamicaly. I've tried something like
this, but it gives me the following error: TypeError: Cannot call method
'push' of undefined.
$scope.fillMonth = function () {
var gap = dayInWeek($scope.year.value, $scope.month, 1),
nrOfDays = daysInMonth($scope.year.value, $scope.month);
$scope.model = {};
for (var i = 0; i < (nrOfDays + gap) % 7; i++) {
for (var j = 0; j < 7; j++) {
if (j === 0)
$scope.model.weeks.push([]);
if (i === 0 && j < gap)
$scope.model.weeks[i].days.push(null);
else
$scope.model.weeks[i].days.push([{ name: i + ' ' + j,
toDoItems: [{ name: "Task 1" }, { name: "Task 2"}]}]);
}
}
}
function daysInMonth(year, month) {
var d = new Date(year, month, 0);
return d.getDate();
}
function dayInWeek(year, month, day) {
var d = new Date(year, month, day);
return d.getDay();
}
Can anyone help me with this?

How to make a toggle element close when clicking off it?

How to make a toggle element close when clicking off it?

I have a group of classes which toggle. The code is this:
$(".form-btn").click(function(event) {
event.preventDefault();
$(this).next().toggle(0);
});
With the HTML as so:
<div class="form-btn-wrapper">
<div class="form-btn" id="buy-or-rent">Buy or Rent <i
class="icon-caret-down"></i></div>
<div class="form-popup radio">
<input id="check1" type="radio" name="buy-or-rent"
value="To Buy">
<label for="check1">To Buy</label>
<input id="check2" type="radio" name="buy-or-rent"
value="To Rent">
<label for="check2">To Rent</label>
</div>
</div>
<div class="form-btn-wrapper">
<div class="form-btn" id="price">Price <i
class="icon-caret-down"></i></div>
<div class="form-popup">
<input type="text" name="min-price" class="small
price-input" placeholder="Min" /> to <input type="text"
name="max-price" class="small price-input"
placeholder="Max" />
</div>
</div>
This works fine but to close each toggle (form-popup) you must click again
its respective form-btn. How can I change the jquery so that the
form-popups close when you click anywhere?
Thanks

Sunday, 29 September 2013

How to display records from database in select onchange event

How to display records from database in select onchange event

I'm a beginner in coding of PHP, just want to ask how to display records
using the script below?

$option = '';
while($row = mysql_fetch_assoc($get))
{
$option .= '<option value = "'.$row['rfq'].'">'.$row['rfq'].'</option>';
}
?>
<form>
<select>
<option value="ALL">ALL</option>
<?php echo $option; ?>
</select>
</form>

ALL option is load when the page runs and displays all the record in
table, and when I choose 13-001 I want to display the record of 13-001.
How to do that?

in curl what is the load time for url request

in curl what is the load time for url request

i am finding Load Time for the url request using curl and using
$info=curl_getinfo($handle);
print_r($info);
which is the load time
pretranver time
namelook time
connect time
start transvertime
look up time
if not in these then how do i find and also primary_ip is the ip address
of the url

Using objects and object functions through variables

Using objects and object functions through variables

Background of the program: the user is able to input a string of two words
only - a verb and a noun. I tokenize this string into a vector and compare
tokens[0] with a vector of allowed verbs, and tokens[1] with a vector of
allowed nouns.
Now, I'm trying to find a way to allow only certain verbs to be performed
on certain nouns. For example, writing "take book" will give a message (or
whatever) saying it's allowed, but writing "take door" would not be. I
have so far created a class Object with bool values for each possible verb
(eg. within the class Object, I can create an Object book for which m_take
= true, or false for an Object door).
However, I'm having trouble associating these objects with the user input.
For example, I would like to be able to do something like this:
1) User inputs "verb noun", which go into the tokens vector as tokens[0]
and tokens[1].
2) Program checks if the input contains acceptable words (individually).
3) Considering getstat() to be the function to retreive the bool value of
the possible action doable on an object, the program retrieves
tokens[1].getstat(tokens[0]) and, if true, executes tokens[0].tokens[1]()
(eg. book.take()). This way I could have only one if cycle in my main(),
which can be used by all legal verbs and nouns, without making an infinite
list of if, else if, etc, considering every single option manually.

Sorry if this is at all confusing. I know it is not possible to use a
variable as an object name, but I'm sure there's a better way to do this
than doing cycles within cycles of considering every single mix and match
of verb and noun. I'm experimenting with like 3 each at the moment, but
once I get this working I plan on expanding it and it would be a nightmare
to keep track of every change if I have to hard-code every possible verb
and noun multiple times within the source code. (Also, sorry for not
posting the whole source - it's a really long file just now!) Thanks for
any help/hint in the right direction!

Libgdx Render method

Libgdx Render method

I have a question on libgdx render method, I am currently designing a game
that requires me to draw different type of images to the screen upon the
user request. However I am having this issue where by the game screen will
get blank out after 4-5 tries, I realised the render method is somehow a
endless loop. So my question is how does the render method actually works
? need some explanation on that, had checked the documentation for it but
dont really understand.
Much help is appreciated, Thanks!!!
leDon

Saturday, 28 September 2013

DCT code Matlab

DCT code Matlab

I work on a function in matlab that calcul the DCT of an image. I don't
know what is not work in my code, but i got an output image with the same
number. I want to use this formula for my DCT.
Any ideas please.
function image_comp = dctII(image, b)
[h w] = size(image);
image = double(image) - 128;
block = zeros(b,b);
image_t=zeros(size(image));
for k=1:b:h
for l=1:b:w
image_t(k:k+b-1,l:l+b-1)= image(k:k+b-1,l:l+b-1);
for u=1:b
for v=1:b
if u == 0
Cu = 1/sqrt(2);
else
Cu = 1;
end
if v == 0
Cv = 1/sqrt(2);
else
Cv = 1;
end
Res_sum=0;
for x=1:b;
for y=1:b
Res_sum = Res_sum +
((image_t(x,y))*cos(((2*x)+1)*u*pi/(2*b))*cos(((2*y)+1)*v*pi/(2*b)));
end
end
dct= (1/4)*Cu*Cv*Res_sum;
block(u,v) = dct;
end
end
image_comp(k:k+b-1,l:l+b-1)=block(u,v);
end
end
end

Verify that Winform drawing has been done correctly?

Verify that Winform drawing has been done correctly?

The reason I ask about this:
I'm studying programming in college and I have two mates here, who are
blind. We have a class called basic computer graphics, and we use GDI+ (C#
winform, System.Drawing classes).
As far as I know, there is no notification method built in .NET to let the
user know if the drawing has been done correctly. Are there any
alternative ways, or do you have any ideas of what should I look for to
solve this problem? This is a serious thing, these guys can write any
code, but they need somebody near to check the results every time they're
debugging.
I'm willing the code the whole thing, only I don't know where would be the
best point to start. Thanks!

In which memory segment a program global and local static variables are saved

In which memory segment a program global and local static variables are saved

As far as I know global static variables are stored in .Data and .Bss
segment.
(global) static int i; ---> .BSS
(global) static int i=10; ---> .Data
If this is the case how multiple files which have same global staic
variables access the variables from a memory location which is common to
whole program.
Ex.
test.c
static int i=10;
void fun(){
printf("%d", i );
}
test1.c
static int i=20;
void fun1(){
printf("%d", i);
}
How test.c and test1.c resolve i from .Data segment?
My second question is in which segment of the program memory local static
variables defined inside a functions are stored?

How to autoOpen jquery UI dialog at a specific time

How to autoOpen jquery UI dialog at a specific time

Is there a way i can use jquery UI dialog to autoOpen after 5 second when
the page finish loading, not just to autoload on page load. I used
autoOpen: true Its working but on page load. my question is how can i set
the time in second to pop out the dialog.

Friday, 27 September 2013

Convert numbers into decimal, hex, and binary using an applet

Convert numbers into decimal, hex, and binary using an applet

Write an applet that converts between decimal, hex, and binary numbers.
When you enter a decimal value in the decimal-value text field and press
the Enter key, its corresponding hex and binary numbers are displayed in
the other two text fields. Likewise, you can enter values in the other
fields and convert them accordingly.
Please help me. So far, I have this:
import java.applet.Applet;
import java.awt.*;
import java.awt.Event;
import javax.swing.*;
import java.lang.Integer;
public class ConvertNumber extends Applet
{
Table aTable;
boolean allowUserInput = true;
@Override
public void init()
{
aTable = new Table();
this.add( aTable );
}
}
class Table extends JPanel
{
int decNumber = 0;
String hexNumber = Integer.toHexString(decNumber);
String biNumber = Integer.toBinaryString(decNumber);
public Table()
{
Object[][] cellData = {
{"Decimal", decNumber},
{"Hex", hexNumber},
{"Binary", biNumber}};
String[] columnNames = {"col1", "col2"};
add( new JTable(cellData, columnNames) ) ;
}
}
I'm not quite sure how to include keyListener.

Nested list in angular.js filters

Nested list in angular.js filters

I'm trying to create a simple pagination filter for angular, to be used
like so:
<ul>
<li ng-repeat="page in items | paginate: 10">
<ul>
<li ng-repeat="item in page">{{ item }}</li>
</ul>
</li>
</ul>
I've written simple function:
angular.module('app.filters', [])
.filter('paginate', function() {
return function(input, perPage) {
var pages = [],
perPage = perPage || 10;
for (i=0; i < input.length; i += perPage)
pages.push(input.slice(i, i + perPage));
return pages;
};
});
And it caused angular to crash with quite cryptic (for me at least) error
messages. I figured out that the problem is in nested lists in filter
results. To reproduce the problem, it's enough to do like this:
angular.module('app.filters', [])
.filter('paginate', function() {
return function(input, perPage) {
return [[1,2,3],[4,5,6]];
};
});
Can you please tell me:
why nested lists are a problem to angular filters?
where can i read about it in documentation?
how can i eventually write a filter in correct way?
You can see all code in this plunker:
http://plnkr.co/edit/gUIJcJg0p5LqKGH10B8t?p=preview After running the
code, open the console, you'll see error messages.
Thank you

link a Kiln commit to a fogbugz ticket

link a Kiln commit to a fogbugz ticket

I have a kiln repo and a FB system. They are integrated, so that when I
commit something, if I include "Case 333" in the commit message, it will
link to Fogbugz ticket 333.
How do I do this from the other side? If I forgot to add the case number,
how do I make the connection from the fogbugz side? I looked at the
fogbugz help, and they only tell you how to do the Case 333 method, which
doesn't help after you've already committed, because you can't edit commit
messages.

C: String Element of Struct not retaining assigned value

C: String Element of Struct not retaining assigned value

I'm having a bit of a bizarre issue with C.
I have a .c file implementing a structure, and another using it. The
structure in question is basic info about a student (name and grade). The
Implementation file has the functions
initialize
read name
read grade
free memory (delete instance)
the main file goes as follows:
int main (void){
char inBuff[30];
char* name = NULL;
int grade;
Student Stu;
printf("main: Please enter the name\n");
fgets(inBuff, 30, stdin);
name = malloc((sizeof(char)+1)*strlen(inBuff));
strncpy (name, inBuff, 20);
printf("main: Please enter the grade\n");
scanf("%d", &grade);
InitializeStudent (name, grade, &Stu);
/*value testing*/
printf("main: %s\n", Stu.name);
printf("main: %d\n", Stu.grade);
printf ("main: The student's name is %s\n", NameOfStudent(Stu));
printf ("main: The student's grade is %d\n", GradeOfStudent(Stu));
FreeStudent(&Stu);
free (name);
return 0;
}
printf statements in the InitializeStudent function seem to show the
values being assigned correctly. However, both Stu.name and
NameOfStudent(Stu) return "ASCII", and Stu.Grade and GradeOfStudent(Stu)
return 2675716 (which seems to be a memory address) regardless of input.
Of note is the fact that it has been specified that NameOfStudent and
GradeOfStudent be pass-by-value rather than using a pointer (ie a copy of
the struct should be made and passed in to the functions) and have char*
and int return types respectively, whereas InitializeStudent is passed a
pointer and is a void function.
Also possibly important, the name field of Student is initialized as
char name[20];
rather than
char* name;

SQL JOIN, Replace id with value

SQL JOIN, Replace id with value

I have a query that is giving me trouble, im not sure how to do this
I have to retrieve records from a TICKETS table and join it together with
2 others,, That is not the problem, i need to replace one of the values in
the record for a value in another table.... For Eg:
Table tickets:
numint user_id type desc attach priority status date assignation
Table users
numint company_id name email username password ps security token date
Table companies
numint name
Example Record
company_name - user_name - type - title - priority - status - date -
assignation
"someCompany" - "someUser" - "someTitle" - 1 - "open" - "yyy/mm/dd" -
2(user_id)
in the assignation field of the returned record i need to replace it with
the correspondant value from the users table IF it's NOT 0 (zero)
This is my Query so far
SELECT tickets.numint, tickets.type, tickets.title, tickets.description,
tickets.priority, tickets.status, tickets.date,
users.name AS user_name, companies.name AS company_name,
CASE WHEN tickets.assignation=0 THEN 'not-assigned'
ELSE ????????? END AS assignation
FROM tickets
LEFT JOIN users ON tickets.user_id = users.numint
LEFT JOIN companies ON users.company_id = companies.numint
i dont know how to replace that value, or if the CASE should after the
joins...

How to remove a script if browser is IE10

How to remove a script if browser is IE10

How can I remove a script if the browser is IE10?
I tried to do it like this:
<!--[if !IE]-->
<script type="text/javascript" src="js/script.js"></script>
<!--[endif]-->
But since IE10 doesn't support conditional comments anymore, it still
loads the script.
Any ideas?

Java have superclass code act on object

Java have superclass code act on object

My question is about basic java inheritance and code structure, but I am
actually very confused about how invoking void superclass methods on an
object has a effect on that object.
For example, in my code I declare a CritterTest object as outlined in the
superclass Critter. I understand how to call functions on this object that
return a value, because then I can work in the subclass with that returned
value. However, when the method I attempt to call on the CritterTest
object does not have a return value (a void method) I am not sure how to
make the code in the super class act on the CritterTest object.
For an idea of how my code is structured, I have the class I am working
in, called TestingHarness, where I declare an object of the CritterTest
class.
Sorry if this question is too vague.

Thursday, 26 September 2013

Automatically start godoc localhost server in OS X?

Automatically start godoc localhost server in OS X?

In Go, you can start HTTP server and then browse through the Go document
via the specific port. For example, when you type in godoc -http=:3333,
then the localhost server starts working with port 3333 and you can use it
to view the official Go document.
However, I'd like to make it start automatically whenever I log in to the
OS X system, since it is so powerful and convenient to write in Go code
with even when I'm off the Wi-Fi connection. So is it feasible to use such
daemon in OS X?
I've implemented and utilized the exact functionality in MongoDB from an
example here, and it's exactly this kind of service that I want to
achieve...
Thanks.

Wednesday, 25 September 2013

Rhomobile: Not able to post the update on twitter

Rhomobile: Not able to post the update on twitter

I am using Rhomobile (for Android) to post status update on Twitter. For
that, following the steps of Oauth implementation I am able to get logged
in with Twitter but after login, when trying to post the status update
everytime I got HTTP Response as {"errors":[{"message":"Could not
authenticate you","code":32}]}.
Below is the relevant code for making the request to post status update.
def post_to_twitter(comment)
$rnd = rand(36**32).to_s(36)
$post_status_url = "https://api.twitter.com/1.1/statuses/update.json"
$oauth_token1 = @account_set.tt_oauth_token
$oauth_token_secret1 = @account_set.tt_oauth_token_secret
@oauth_nonce = $rnd
@oauth_timestamp = Time.now.to_i.to_s
@http_port = System.get_property('rhodes_port')
@url_param = "oauth_consumer_key="+ $oauth_consumer_key + "&" +
"oauth_nonce=" + @oauth_nonce + "&" +
"oauth_signature_method=" + $oauth_signature_method + "&" +
"oauth_timestamp=" + @oauth_timestamp + "&" +
"oauth_token=" + $oauth_token1 + "&" +
"oauth_version="+ $oauth_version + "&" +
"status=" + Rho::RhoSupport.url_encode("Test")
$oauth_sign = get_auth_signature($post_status_url, @url_param, "")
@auth_header = "OAuth oauth_consumer_key="+ $oauth_consumer_key + ", " +
"oauth_nonce=" + @oauth_nonce + ", " +
"oauth_signature=" + $oauth_sign + ", " +
"oauth_signature_method=" + $oauth_signature_method + ",
" +
"oauth_timestamp=" + @oauth_timestamp + ", " +
"oauth_token=" + $oauth_token1 + ", " +
"oauth_version="+ $oauth_version + ", " +
"status=" + Rho::RhoSupport.url_encode("Test")
postTTres = Rho::AsyncHttp.post(
:url => $post_status_url,
:headers =>{"Content-Type" => "application/x-www-form-urlencoded",
"Authorization" => @auth_header }
)
p postTTres
end
The signature generation function is as follows:
def get_auth_signature (url, url_param, secret)
signature = "POST&" + Rho::RhoSupport.url_encode(url).to_s +
"&" + Rho::RhoSupport.url_encode(url_param).to_s
key = $oauth_consumer_secret + "&" + secret
hmac = HMAC::SHA1.new(key)
hmac.update(signature)
$signature = Base64.encode64("#{hmac.digest}")
$signature = Rho::RhoSupport.url_encode("#{$signature.gsub(/\n/,'')}")
return $signature
end
The parameters values when traced are as follows:
@url_param before generating signature ---------
oauth_consumer_key=2ChmEzWBe5Y9hMYODqA1IQ&oauth_non
ce=iyb9502vspjnhj9orb87sriych16678b&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1380117614&oauth_token=244586214-M6A2jMlR7vZiqwAMrfuSj7I7XFzFTRd4
6nV6aTLK&oauth_version=1.0&status=Test
Passing @url_param to get_auth_signature() to generate signature.
Generated signature url and signature is
Signature string ----------
POST&https%3A%2F%2Fapi.twitter.com%2F1.1%2Fstatuses%2Fupdate.
json&oauth_consumer_key%3D2ChmEzWBe5Y9hMYODqA1IQ%26oauth_nonce%3Diyb9502vspjnhj9orb87sriych16678b%26oauth_signature_method%3DHMAC-SHA1%26oauth_timesta
mp%3D1380117614%26oauth_token%3D244586214-M6A2jMlR7vZiqwAMrfuSj7I7XFzFTRd46nV6aTLK%26oauth_version%3D1.0%26status%3DTest"
Base64 string ------- gjdXuU3qoGNt90Q2dRhNM3IXaBI%3D
Passing all these values as header Authorization to
https://api.twitter.com/1.1/statuses/update.json
and got
Http Response as {"errors":[{"message":"Could not authenticate
you","code":32}]}.
Also tried passing it as post parameters in :body but no luck.
postTTres = Rho::AsyncHttp.post(
:url => $post_status_url,
:headers =>{"Content-Type" => "application/x-www-form-urlencoded"},
:body => @url_param + "&oauth_signature=" + $oauth_sign
)
Checked the system timings with Twitter server timings and thats fine.
Also tried with static oauth_token that we can get from Twitter account
but then too same response.
Please help me to fix this. I am unable to trace what I am missing or
where I am going wrong.
Thanks

Thursday, 19 September 2013

is there are any way to stop rendering current page using HTML

is there are any way to stop rendering current page using HTML

I want to stop rendering the page and exit when the user's browser doesn't
have JavaScript enabled or support, I want it like how exit() works in
PHP. Is it possible via HTML?

Combine factors with NAs

Combine factors with NAs

I have a matrix of characters and there are numerous NAs. I would like to
create a new variable which combines all (non-NA) strings into one. So
that from
(df = data.frame(matrix(c("A", "B", "C", NA, NA, "E", NA, "D", "A", "C",
"B", "C", NA, "C", "A"), ncol = 3)))
X1 X2 X3
1 A E B
2 B <NA> C
3 C D <NA>
4 <NA> A C
5 <NA> C A
then I would have
X1 X2 X3 newvar
1 A E B A:B:E
2 B <NA> C B:C
3 C D <NA> C:D
4 <NA> A C A:C
5 <NA> C A A:C
Notice that the individual letters alphabetize so I don't get "A:C" and
"C:A" in the last two rows.
I've tried
within(df, newvar <- factor(X1:X2:X3))
which gives
X1 X2 X3 newvar
1 A E B A:E:B
2 B <NA> C <NA>
3 C D <NA> <NA>
4 <NA> A C <NA>
5 <NA> C A <NA>
but the presence of NAs overrides the aggregation.

Form1_KeyDown calling button1_Click

Form1_KeyDown calling button1_Click

I have such piece of code:
private void button1_Click(object sender, EventArgs e) {
// Do something...
}
private void Form1_KeyDown(object sender, KeyEventArgs e) {
if (e.KeyData == Keys.A) {
// Call button1_Click.
}
}
How do I manage to call the Click event? What should I write instead of
// Call button1_Click.
Thank you!

Ajax post equivalent in C#

Ajax post equivalent in C#

I have inherited a web app and I need to convert a client side ajax post
into server side asp.net code ( C#). I am not sure what the best approach
is to accomplish this, I am pretty new to ajax posts but this code seems
to be posting info to a page in the same project so I am assuming there is
a much easier way to accomplish this server side just wanted to have
someone confirm that I am not crazy...
Code
$.ajax({
// type: "POST",
// url: '<%= ResolveUrl("~/default.aspx") %>/Login',
// data: parameters,
// contentType: "application/json; charset=utf-8",
// dataType: "json",
// success: function (msg) {
// if (msg.d == "success") {
// $.modal.autoResize = false;
// ResizeModal();
// var redirectUrl = $('#<%= btnSubmit.ClientID
%>').attr('data-redirecturl');
// if (redirectUrl != null && redirectUrl.length > 0) {
// window.location = redirectUrl;
// }

Generate an JSON array from a hash in JBuilder

Generate an JSON array from a hash in JBuilder

Given the following Ruby data structure:
data = { :a => 1, :b => 2 }
... I want to create the following JSON:
{"result":[
{"letter":"a","number":"1"},
{"letter":"b","number":"2"}
]}
How do I accomplish this using Rails' JBuilder?

PHP if statement using session data to display different content for different users

PHP if statement using session data to display different content for
different users

I checked other threads on this site but none of the solutions proposed
worked for me.
I want to check session data for a user, and depending on the output
display different data for different ranks. The code I currently have is
below:
<?php
if($_SESSION['user']['rank'] == founder)
{
echo "Yay";
}
?>

Usage of JSTL Function fn:length

Usage of JSTL Function fn:length

I am working on a defect in which by default all check-box need to be
selected, if multiple channels are used. However, currently in case of
multiple channels selects the fist channel check-box remains unselected
only
THE JSTL code is
<label data-use-main="#"
class="left-align form-inline checkbox
${fn:length(messageForm.configuredChannels) > 1 ? '' : 'hidden'}">
<form:checkbox path="emailMessageForm.useMainMessageEmail"
/>&nbsp;&nbsp;
<label>
<spring:message
code="message.use.main.content.email"></spring:message>
</label>
</label>
I m not able to understand how ${fn:length(messageForm.configuredChannels)
> 1 ? '' : 'hidden'}"> works as the checkbox checked condition depends on
it.

Wednesday, 18 September 2013

object cannot be cast from dbnull to other types[ADO.net]

object cannot be cast from dbnull to other types[ADO.net]

I have a stored procedure which will return flag values based on certain
conditions.The stored procedure does not return a null value,It returns
1,2,3 based on condition .But in my ADO.Net code,when I DEBUG, it throws
an exception and the "execute scalar" is returning null. Here is my
ADO.NET code
SqlCommand cmd = new SqlCommand("sp_checkifexists", con);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@Name",name);
cmd.Parameters.AddWithValue("@Regno",regno);
cmd.Parameters.Add("@flag", System.Data.SqlDbType.VarChar, 40);
cmd.Parameters["@flag"].Direction =
System.Data.ParameterDirection.Output;
con.Open();
//Error occcurs here
int NoOfRows = Convert.ToInt16(cmd.ExecuteScalar());
con.Close();
int flag = (int)cmd.Parameters["@flag"].Value;
return flag;
Any help would be much appreciated!

C++ Data Validation Issue

C++ Data Validation Issue

if (month > 0 && month <= 12)
if (day > 0 && day <= checkDays(month, year))
if (year >= 1752 || year <= 9999)
if((month != 12 && day != 31 && year != 9999))
return true;
else return false;
else return false;
else return false;
else return false;
I have the values month = 12, days = 31, and year = 2008 and the data
validation is failing at the last part, but I cannot figure out why.

Reading and writing to hadoop sequence file using scala

Reading and writing to hadoop sequence file using scala

I just started using scalding and trying to find examples of reading a
text file and writing to a hadoop sequence file. Any help is appreciated.

How to populate a database list without refreshing webpage

How to populate a database list without refreshing webpage

I'm interested in having a search form on the left side of a webpage, and
the main content being the rows returned from the database.
Example : www.kijiji.ca
What I want to avoid, is reloading the whole page. Kijiji is not a good
example of this, updating the query or changing the results page, updates
the entire browser window. Ideally when search parameters are changed, the
container with the search results will update, and nothing else. This way
the outside information is preserved, and page loading time is reduced.
Would an Iframe be ideal for this? Or perhaps Jquery/ajax can handle this
somehow ??
Thanks for the advice.

MySQL Count with several criteria coloumn one table [on hold]

MySQL Count with several criteria coloumn one table [on hold]

I have a data transaction table
Table Data (Month,Year,Type,Color)
+-------+------+-----------------------+---------------+
| Month | Year | type | Color |
+-------+------+-----------------------+---------------+
| 1 | 2013 | MATIC | BLACK |
| 1 | 2013 | MATIC | BLACK |
| 2 | 2013 | MATIC | BLACK |
| 2 | 2013 | MATIC | RED |
| 3 | 2013 | MATIC | WHITE |
| 3 | 2013 | MATIC | WHITE |
| 4 | 2013 | MATIC | WHITE |
| 4 | 2013 | MATIC | WHITE |
| 1 | 2013 | SPORT | RED |
| 1 | 2013 | SPORT | YELLOW |
| 2 | 2013 | SPORT | YELLOW |
| 2 | 2013 | SPORT | BLACK |
| 3 | 2013 | SPORT | BLACK |
+-------+------+-----------------------+---------------+
i want count number by type,color,year,month so the result like this
+-------+------+-----------------------+---------------+--------+
| Month | Year | type | Color | Number |
+-------+------+-----------------------+---------------+--------+
| 1 | 2013 | MATIC | BLACK | 2 |
| 2 | 2013 | MATIC | BLACK | 1 |
| 2 | 2013 | MATIC | RED | 1 |
| 3 | 2013 | MATIC | WHITE | 2 |
| 4 | 2013 | MATIC | WHITE | 2 |
| 1 | 2013 | SPORT | RED | 1 |
| 1 | 2013 | SPORT | YELLOW | 1 |
| 2 | 2013 | SPORT | YELLOW | 1 |
| 2 | 2013 | SPORT | BLACK | 1 |
| 3 | 2013 | SPORT | BLACK | 1 |
+-------+------+-----------------------+---------------+--------+
its group by month,year,type,color, What query to get the number ?

How to adjust or resize the background image of div dynamically based on content size

How to adjust or resize the background image of div dynamically based on
content size

I am working on Html and Css. I am trying to design a chart conversation
like web page where i need to show the messages alternatively like one
comes right another on left similar in mobile applications. For that i am
using divs to contains the message and i set a background-image for it,

Here what the problem i am facing is, message are of variable size that
means some may occupy 1 line and some other might 5 to 20 lines we cannot
estimate it. Div background-image size is 40px height only so if i got
more than 3 lines of message then it crosses the background image. Here is
my Div markup
<div style="background-image:url('some
url');padding:10px;margin:2%;word-break:break-word;width:100px;max-width:10px">Here
is my content it is variable in size</div>
I have used the css properties like overflow:hidden but it didn't help me.
Is there any way so that image or div will be automatically resized based
on the content size vertically. Or other way i can follow that is closely
related to my requirement. Please guide me.

Saving fonts and colors (delphi)

Saving fonts and colors (delphi)

My system gives the user to change the color and font of several items on
multiple forms.
I need a way to save these fonts and colors. My system uses sql so is
there a way to save them there or is there another way to save them.

Button Styling CSS - Issue with I.E

Button Styling CSS - Issue with I.E

I have this styling for a button. Working perfect on Firefox and Chrome,
but not with Internet Explorer (ALL VERSIONS)
JsFiddle DEMO : http://jsfiddle.net/Mhded/1/
Here is my Code :
HTML:
<span class="button_style">Comment</span>
CSS:
.button_style {
background:-moz-linear-gradient(top,#006666 0%,#006666 100%);
background:-webkit-gradient(linear,left top,left
bottom,color-stop(0%,#006666),color-stop(100%,#006666));
background:-webkit-linear-gradient(top,#006666 0%,#006666 100%);
background:-o-linear-gradient(top,#006666 0%,#006666 100%);
background:-ms-linear-gradient(top,#006666 0%,#006666 100%);
background:linear-gradient(top,#006666 0%,#006666 100%);
filter:progid:DXImageTransform.Microsoft.gradient(startColorstr='#006666',endColorstr='#006666',GradientType=0);
border: 1px solid #006666;
border-radius: 3px 3px 3px 3px;
color: #FFFFFF;
font-family: 'Helvetica',sans-serif;
font-size: 14px;
padding: 6px;
vertical-align: middle;
width: 70px;
cursor:pointer;
}

Tuesday, 17 September 2013

How to call a javascript in plone site

How to call a javascript in plone site

I have a html file which is under navigation portlet. I want to call a
javascript from one html file which is in the navigation portlet. I put
the javascript file under custom and registered the javascript in
portal_javascript Registry. But i still can't able to call the javascript.
this is html page :
<script language="Javascript" type="text/javascript"
src="jquery-1.9.1.mins.js">
</script>
<script language="Javascript" type="text/javascript"
src="calculatemyval.js"></script>
<form name="addition">
<tbody><tr>
<td>Value 1: <br>
</td>
<td>
<input size="5" name="v1" type="text">
in kg <br>
</td>
</tr>
<tr>
<td>Value 2 : <br>
</td>
<td>
<input size="5" name="v2" type="text">
in cm <br>
</td>
</tr>
<tr>
<td>&nbsp;<br>
</td>
<td>
<input value="calc" onclick="calcvalue()" name="button"
type="button"><br>
</td>
</tr>
<tr>
<td>Result: <br> </td>
<td><input name="result" size="5" readonly="readonly" type="text">
<br></td>
</tr>
</tbody>
</form>
Here is my script :
calculatemyval.js
<script type="text/javascript">
function calcvalue(){
var h = document.addition.v1.value;
var g = document.addition.v2.value;
var res = 0;
if (h > 0){
h = h / 100.0;
res = g / (h * h);
res = Math.ceil(res * 10) / 10
document.addition.result.value = res;
}
}
</script>
Thanks

Are Apple Mail Plugin Bundles sandboxed?

Are Apple Mail Plugin Bundles sandboxed?

I am writing some code running inside Apple Mail, via the known method of
user built bundles.
I've found that many filesystem locations seem to be unaccessible for my
code running inside Mail.app. For example, trying to do a simple fopen
call to access a file in the current user directory, or even trying to
read files in /tmp with all-access permissions (chmod 777), will fail with
ERRNO set to 1 (Operation not permitted).
However, filesystem I/O from within plugin bundle is successful with
NSTemporaryDirectoryprovided path.
I'm fairly new to the Apple development world, so my question is if those
limitations are enforced by the operating system for some kind of bundles,
by Apple Mail program or simply i'm doing the wrong things such as
potentially mixing process and filesystem permissions.
Thank you very much.

Is the this function executed twice?

Is the this function executed twice?

In the code below:
select t.id, ST_AsText(t.geom) AS tgeom, s.name,
ST_Length(ST_ShortestLine(t.geom,s.geom)) AS short,t.par
from teta t, str_lines s
Where ST_Length(ST_ShortestLine(t.geom,s.geom))<200
Is ST_Length(ST_ShortestLine(t.geom,s.geom)) executed twice ?

writing/reading from network while serving a block device request

writing/reading from network while serving a block device request

I modified a block device driver for a ramdisk (similar to the one here:
http://www.linuxforu.com/2012/02/device-drivers-disk-on-ram-block-drivers/)
so that driver reads/writes from the network. I basically removed memcpy
and replaced it with an in-kernel network socket read/write.
And here is what I get: a warning that irqs are disabled. The warning is
thrown from the line WARN_ON_ONCE(in_irq() || irqs_disabled()); inside the
function _local_bh_enable_ip.
My understanding is that what I did should work since all disk requests
are queued in the work queue supplied in the gendisk. And job handler
(supplied when blk_init_queue() is called) will be called from the typical
kernel context, where irqs should be enabled. But I guess I was wrong.
Anyone can help with a work-around?
Here is the top part of the stack trace spelled out by the kernel:
[ 697.480153] [<ffffffff8105931f>] warn_slowpath_common+0x7f/0xc0
[ 697.480159] [<ffffffff8105937a>] warn_slowpath_null+0x1a/0x20
[ 697.480166] [<ffffffff8106172a>] local_bh_enable+0x7a/0xa0
[ 697.480175] [<ffffffff815974b3>] lock_sock_nested+0x53/0x60
[ 697.480183] [<ffffffff815eedfc>] tcp_sendmsg+0x2c/0xe60
[ 697.480197] [<ffffffff8134226c>] ? vsnprintf+0x35c/0x640
[ 697.480207] [<ffffffff81618331>] inet_sendmsg+0x61/0xb0
[ 697.480216] [<ffffffff81592912>] sock_sendmsg+0xd2/0xf0
[ 697.480226] [<ffffffff8133708e>] k_send+0x6e/0x80
[ 697.480236] [<ffffffffa02b34ee>] ramdevice_read+0x5e/0xd0 [dor]
[ 697.480244] [<ffffffffa02b31a3>] rb_request+0x133/0x1b0 [dor]

How to store NSDate to DATETIME along timezone?

How to store NSDate to DATETIME along timezone?

How to format the date string to get the timezone information stored in a
MySQL DATETIME field? Does DATETIME store timezone information at all?

Error deploying war into jboss as 7 (domain mode) "Failed to process phase STRUCTURE of deployment "

Error deploying war into jboss as 7 (domain mode) "Failed to process phase
STRUCTURE of deployment "

I'm trying to reploy my war into jboss as 7 on domain mode and I'm getting
this error bellow
[Server:node02] 13:51:46,049 ERROR [org.jboss.msc.service.fail] (MSC
service thread 1-11) MSC00001: Failed to start service
jboss.deployment.unit."ROOT.war".STRUCTURE:
org.jboss.msc.service.StartException in service
jboss.deployment.unit."ROOT.war".STRUCTURE: Failed to process phase
STRUCTURE of deployment "ROOT.war"
[Server:node02] at
org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:119)
[jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
[Server:node02] at
org.jboss.msc.service.ServiceControllerImpl$StartTask.startService(ServiceControllerImpl.java:1811)
[jboss-msc-1.0.2.GA.jar:1.0.2.GA]
[Server:node02] at
org.jboss.msc.service.ServiceControllerImpl$StartTask.run(ServiceControllerImpl.java:1746)
[jboss-msc-1.0.2.GA.jar:1.0.2.GA]
[Server:node02] at
java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
[rt.jar:1.6.0_30]
[Server:node02] at
java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
[rt.jar:1.6.0_30]
[Server:node02] at java.lang.Thread.run(Thread.java:662)
[rt.jar:1.6.0_30]
[Server:node02] Caused by: java.lang.IllegalArgumentException: Given
parent is not an ancestor of this virtual file
[Server:node02] at
org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:116)
[jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
[Server:node02] at
org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122)
[jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
[Server:node02] at
org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122)
[jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
[Server:node02] at
org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122)
[jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
[Server:node02] at
org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:122)
[jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
[Server:node02] at
org.jboss.vfs.VirtualFile.getPathNameRelativeTo(VirtualFile.java:110)
[jboss-vfs-3.1.0.Final.jar:3.1.0.Final]
[Server:node02] at
org.jboss.as.server.deployment.module.ManifestClassPathProcessor.createAdditionalModule(ManifestClassPathProcessor.java:193)
[jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
[Server:node02] at
org.jboss.as.server.deployment.module.ManifestClassPathProcessor.handlingExistingClassPathEntry(ManifestClassPathProcessor.java:185)
[jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
[Server:node02] at
org.jboss.as.server.deployment.module.ManifestClassPathProcessor.deploy(ManifestClassPathProcessor.java:162)
[jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
[Server:node02] at
org.jboss.as.server.deployment.DeploymentUnitPhaseService.start(DeploymentUnitPhaseService.java:113)
[jboss-as-server-7.1.1.Final.jar:7.1.1.Final]
[Server:node02] ... 5 more
[Server:node02]
[Server:node02] 13:51:46,060 INFO [org.jboss.as.server]
(host-controller-connection-threads - 3) JBAS015870: Deploy of deployment
"ROOT.war" was rolled back with failure message {"JBAS014671: Failed
services" => {"jboss.deployment.unit.\"ROOT.war\".STRUCTURE" =>
"org.jboss.msc.service.StartException in service
jboss.deployment.unit.\"ROOT.war\".STRUCTURE: Failed to process phase
STRUCTURE of deployment \"ROOT.war\""}}
[Server:node02] 13:51:46,062 INFO [org.jboss.as.server.deployment] (MSC
service thread 1-9) JBAS015877: Stopped deployment ROOT.war in 1ms
[Server:node02] 13:51:46,063 INFO [org.jboss.as.controller]
(host-controller-connection-threads - 3) JBAS014774: Service status report
[Server:node02] JBAS014777: Services which failed to start: service
jboss.deployment.unit."ROOT.war".STRUCTURE:
org.jboss.msc.service.StartException in service
jboss.deployment.unit."ROOT.war".STRUCTURE: Failed to process phase
STRUCTURE of deployment "ROOT.war"
[Server:node02]
My jboss-deployment-structure.xml is bellow
<?xml version='1.0' encoding='UTF-8'?>
<jboss-deployment-structure xmlns="urn:jboss:deployment-structure:1.1">
<deployment>
<exclusions>
<module name="org.slf4j" />
<module name="org.slf4j.impl" />
<!-- <module name="org.hibernate" /> -->
</exclusions>
<!-- This allows you to define additional dependencies, it is the
same
as using the Dependencies: manifest attribute -->
<dependencies>
<module name="deployment.sun.jdk" />
</dependencies>
</deployment>
<!-- This is a module that re-exports the containers version of
javassist.util.proxy -->
<!-- This means that there is only one version of the Proxy classes
defined -->
<module name="deployment.sun.jdk">
<dependencies>
<module name="sun.jdk">
<imports>
<include path="com/sun/crypto" />
<include path="com/sun/crypto/provider" />
<include path="com/sun/image/codec/jpeg" />
<include
path="com/sun/org/apache/xml/internal/resolver" />
<include
path="com/sun/org/apache/xml/internal/resolver/tools"
/>
</imports>
</module>
</dependencies>
</module>
</jboss-deployment-structure>

Sunday, 15 September 2013

reactivemongo - merging two BSONDocuments

reactivemongo - merging two BSONDocuments

I am looking for the most efficient and easy way to merge two BSON
Documents. In case of collisions I have already handlers, for example if
both documents include Integer, I will sum that, if a string also, if
array then will add elements of the other one, etc.
However due to BSONDocument immutable nature it is almost impossible to do
something with it. What would be the easiest and fastest way to do
merging?
I need to merge the following for example:
{
"2013": {
"09": {
value: 23
}
}
}
{
"2013": {
"09": {
value: 13
},
"08": {
value: 1
}
}
}
And the final document would be:
{
"2013": {
"09": {
value: 36
},
"08": {
value: 1
}
}
}
There is a method in BSONDocument.add, however it doesn't check
uniqueness, it means I would have at the end 2 BSON documents with "2013"
as a root key, etc.
Thank you!

I need to write an algorithm in Java language to find the second smallest value among a,b and c

I need to write an algorithm in Java language to find the second smallest
value among a,b and c

I have been wondering how to do this correctly for a while. I understand
how to find the smallest and largest but I can't find second smallest to
save my life.

Calling ServiceStack Service from WCF

Calling ServiceStack Service from WCF

I work in a company that is only using WCF and i am trying to introduce
service stack. Now i understand we are better off using the service
stackclients that wcf clients but for some of our stuff and to keep people
happy that will not always be possible. Can anyone provide a basic example
of a ServiceStack service that can be added as a client into a VS2012
project using the add service reference inside visual studio as you
normally do for a WCF service? Basically is there a way to make
ServiceStack seem like a WCF service to people that don't know about
ServiceStack?
If i can show this i think i can convince my company to make the switch
but if not it will be difficult as everything else is WCF based. We are
already using the ServiceStack clients to hook into other online websites
so it seems a good time to try to convince them to move to the service
stack services and clients as long as they feel they can fall back to the
WCF client if needed.

How to handle HTML with javascript

How to handle HTML with javascript

i'm studying javascript but i can't find some clear reference about how
getting and treat data out of the HTML forms.
Here an example:
THE FORM:
<HTML>
<HEAD>
<TITLE>Database Lookup</TITLE>
<script src="basic.js"></script></HEAD>
<BODY>
<H1>Database Lookup</H1>
<FORM action="javascript: submitForm();">
Please enter the ID of the publisher you want to find: <BR>
<INPUT TYPE="TEXT" NAME="id">
<BR>
<INPUT TYPE="SUBMIT" value="Submit" > </FORM>
</BODY>
<HTML>
//HERE JAVASCRIPT Javascript BASIC.js:
function submitForm()
{
var idsearched=document.getElementById("id").innerHTML;
document.write("idsearched");
}
I would like to know what i'm doing wrong, because nothing happen when i
click submit. And which is the better solution for handling forms with
javascript?? Using "action"? or which of other attributes?

MySQL join same table twice on different columns without a clash

MySQL join same table twice on different columns without a clash

This is the query:
SELECT * FROM property_table AS property
INNER JOIN property_classification AS classifications
ON property.classification_id = classifications.id
INNER JOIN property_classification AS classonrequest
ON property.classonrequest_id = classonrequest.id
WHERE property.id=5000 LIMIT 1;
Notice that I'm using the same table property_classification on two fields
property.classification_id and property.classonrequest_id.
The structure of property_classification is something like:
id | a1 | a2 | a3 | ... | d1 | d2
When I execute the query above in MySQL Query Browser, I get something
like this:
id | other 'property' fields | id | a1 | a2 | a3 | ... | id | a1 | a2 | a3
| ...
But in my PHP script I am returning associated arrays, and all duplicate
field names are overwritten.
What I want is the query to return the two joined tables under the name of
their table i.e.:
classifications.id | classifications.a1 | classifications.a2 |
classifications.a3
and
classonrequest.id | classonrequest.a1 | classonrequest.a2 | classonrequest.a3
How do I do that?

logback access - no applicable action for [root]

logback access - no applicable action for [root]

I'm new for logback-access. I'm trying to work with Jetty and logback.
I set the following in Jetty.xml:
<Set name="handler">
<New id="Handlers"
class="org.eclipse.jetty.server.handler.HandlerCollection">
<Set name="handlers">
<Array type="org.eclipse.jetty.server.Handler">
<Item>
<Ref id="webapp-context" />
</Item>
<Item>
<New id="request-log-handler"
class="org.eclipse.jetty.server.handler.RequestLogHandler"/>
</Item>
</Array>
</Set>
</New>
</Set>
<Ref id="request-log-handler">
<Set name="requestLog">
<New id="requestLogImpl"
class="ch.qos.logback.access.jetty.RequestLogImpl">
<Set name="fileName">www/WEB-INF/logback-access.xml</Set>
</New>
</Set>
</Ref>
And in logback-access.xml:
<configuration>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<!-- encoders are assigned the type
ch.qos.logback.classic.encoder.PatternLayoutEncoder by default -->
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>combine</pattern>
<immediateFlush>true</immediateFlush>
</encoder>
</appender>
<appender name="FILE"
class="com.ca.spm.core.logging.ClusterRollingFileAppender">
<file>logs/[hostname]-server-access.log</file>
<rollingPolicy
class="com.ca.spm.core.logging.ClusterTimeBasedRollingPolicy">
<fileNamePattern>logs/[hostname]-server-access.%d.%i.log.gz</fileNamePattern>
<maxHistory>30</maxHistory>
</rollingPolicy>
<triggeringPolicy
class="ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP">
<maxFileSize>50KB</maxFileSize>
</triggeringPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>combine</pattern>
<immediateFlush>true</immediateFlush>
</encoder>
</appender>
<root level="TRACE">
<appender-ref ref="FILE" />
<appender-ref ref="STDOUT" />
</root>
</configuration>
I have two issues:
I got errors: a. no applicable action for [root]
b. no applicable action for [appender-ref]
The file is being created but no messages are being written to the file.
I will really appreciate any help Thanks Gidi

Where can parameters be used in SQL statements?

Where can parameters be used in SQL statements?

I'm building a search engine, and I've been experimenting with structuring
parameterized SQL statements in PHP. I was wondering what the rules are
for where parameters can be used.
e.g. This works:
$var = $unsafevar;
$stmt = mysqli_prepare($connection, "SELECT * FROM users WHERE username =
?");
mysqli_stmt_bind_param($stmt, 's', $var);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
This doesn't:
$var = 'SELECT';
$var2 = 11;
$stmt = mysqli_prepare($connection, "? * FROM users WHERE username = ?");
mysqli_stmt_bind_param($stmt, 'ss', $var, $var2);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc($result);
Where can parameters be used and where can they not be?
Or, more simply, what does paramaterization literally do to the variables?
Does it put single quotes around them? If that is the case, is there a way
to paramaterize wildcards, column names, or the SQL clauses themselves?

Saturday, 14 September 2013

NSCharacterSet - append another character set

NSCharacterSet - append another character set

I would like to create a character set that includes all of its own
characters, as well as those from another character set. Append in other
words.
I thought there'd be an obvious way, but after control-space completion in
the IDE, and then poking around the docs, I couldn't fine anything. How do
I do this?

How to delete redundant records with different dates from a MySQL table

How to delete redundant records with different dates from a MySQL table

I have a table in a MySQL database that consists of the following columns:
itemID bigint(11)
itemDate datetime
attributeID smallint(6)
value int(9)
What would be the SQL queries (?) to best delete (starting from most
recent records to the oldest):
each record in this table that has value = 0 if exists (another record
with the same itemID and same attributeID and that has a value >2 and the
itemDate is (older but also most recent) OR identical)
each record in this table if exists (another record with the same itemID
and same attributeID and same value and the itemDate is (older but also
most recent) OR identical)
I am using this in a PHP script.
Basically, I have redundant data due to a bug that I had not identified
soon enough for it not to populate around 100k entries. A very small
example below:
itemID itemDate attributeID value
28 11.09.2013 2:00 4 0
28 11.09.2013 2:00 5 0
28 11.09.2013 2:01 1 0
28 11.09.2013 2:01 2 0
28 11.09.2013 2:01 3 0
28 11.09.2013 2:01 4 0
28 11.09.2013 2:01 5 0
28 11.09.2013 2:02 1 21
28 11.09.2013 2:02 2 11
28 11.09.2013 2:02 3 4
28 11.09.2013 2:02 1 21
28 11.09.2013 2:02 2 11
28 11.09.2013 2:02 3 4
28 11.09.2013 2:02 1 21
28 11.09.2013 2:02 2 12
28 11.09.2013 2:02 3 4
28 13.09.2013 18:54 1 0
28 13.09.2013 18:54 2 0
28 13.09.2013 18:54 3 0
28 13.09.2013 18:55 1 21
28 13.09.2013 18:55 2 12
28 13.09.2013 18:55 3 6
The above should become (after multiple iterations of the deletion
algorythm):
itemID itemDate attributeID value
28 11.09.2013 2:00 4 0
28 11.09.2013 2:00 5 0
28 11.09.2013 2:01 1 0
28 11.09.2013 2:01 2 0
28 11.09.2013 2:01 3 0
28 11.09.2013 2:02 1 21
28 11.09.2013 2:02 2 11
28 11.09.2013 2:02 3 4
28 11.09.2013 2:02 2 12
28 13.09.2013 18:55 3 6
I hope I defined the problem clear enough, however, please let me know if
I should clarify anything. Thank you kindly!

Simple video processing chip

Simple video processing chip

Does anyone know of some relatively simple video processing boards (eg,
cheaper than a beagle board) that I might use with a small CMOS camera on
a swarm robot? I've considered a raspberry pi; any other ideas?

Custom Login with Github is not working

Custom Login with Github is not working

I've being following step by step the Custom Login tutorial from
Eventedmind showing in this link:
https://www.eventedmind.com/posts/meteor-customizing-login
So I've created a new App on Github and code it but while running Meteor I
still have errors and nothing shows up. I know I've got errors from the
server side, but I have no idea what is it, maybe the code is bad written
or maybe the way I am calling the login is not the proper anymore. Here is
what I've done (I guess is the same as in the tutorial)
client/index.html
<head>
<title>App</title>
</head>
<body>
{{> header}}
</body>
<template name="header">
<div class="navbar navbar-inverse">
<div class="navbar-inner">
<div class="container">
<a class="brand" href="#">Surf</a>
<form class="navbar-search pull-left">
<input type="text" class="search-query" placeholder="Search">
</form>
<div class="nav pull_right">
{{> user_info}}
</div>
</div>
</div>
</div>
</template>
<template name="user_info">
<ul class="nav pull-right">
{{#if currentUser}}
{{> user_loggedin}}
{{else}}
{{> user_loggedout}}
{{/if}}
</ul>
</template>
<template name="user_loggedin">
{{#if loggingIn}}
<li><a href="">Loggin in...</a></li>
{{else}}
<li>
<img src="{{currentUser.profile.avatar_url}}"
class="img-rounded" style="height: 32px; margin-top: 4px;">
</li>
<li class="dropdown">
<a href="#" class="dropdown-toggle" data-toggle="dropdown">
{{currentUser.profile.login}}
<b class="caret"></b>
</a>
<ul class="dropdown-menu">
<li><a href="">Accounts Settings</a></li>
<li class="divider"></li>
<li><a id="logout">logout</a></li>
</ul>
</li>
{{/if}}
</template>
<template name="user_loggedout">
<li><a id="login">Login with Github</a></li>
</template>
client/index.js
Template.user_loggedout.events({
'click #login': function (e, tmpl) {
Meteor.loginWithGithub({
requestPermissions: ['user', 'public_repo']
}, function (err) {
if (err) {
// error handling
} else {
// show alert
}
});
}
});
Template.user_loggedin.events({
'click #logout': function (e, tmpl) {
Meteor.logout(function (e, tmpl) {
if (err) {
// show err message
} else{
// show alert that says logged out
}
});
}
});
server/config.js
Accounts.loginServiceConfiguration.remove({
service: "github"
});
Accounts.loginServiceConfiguration.insert({
service: "github",
clientId: "NUMBER",
secret: "SECRET_NUMBER"
});
server/accounts.js
Accounts.onCreateUser(function (options, user) {
var accessToken = user.services.github.accessToken,
result,
profile;
result = Meteor.http.get("https://api.github.com/user", {
params: {
access_token: accessToken
}
});
if (result.error)
throw result.error;
profile = _.pick(result.data,
"login",
"name",
"avatar_url",
"url",
"company",
"blog",
"location",
"email",
"bio",
"html_url");
user.profile = profile;
return user;
});

Using C-code (Lex) inside Ruby Gem separate from Ruby

Using C-code (Lex) inside Ruby Gem separate from Ruby

I have Ruby Gem with preprocessor part written in C (Lex). I need compile
this part and use from Ruby code.
As I understand 'Gems with Extensions' is not suitable.
How this can be done in true way?

A graphic representation of occurence of numbers and letters with asteriks

A graphic representation of occurence of numbers and letters with asteriks

DISCLAIMER: THIS IS PART OF A HOMEWORK ASSIGNMENT
So i have created an array with the the count of each letter. It would
look something like this:
Array charCount
charCount[0] = 10
charCount[1] = 6
charCount[2] = 4
I know that 0 = a, 1 = b etc.
Now I want to print these results to a graphic representation using
asteriks. For example:
*
*
*
*
*
**
**
**
***
***
***
ABC
I found this rather difficult and don't really understand how to do this.
- I've made a function to check the max value of my array.
for (int i = 0; i < charCount.length; i++) {
if (letterCount[i] > maxInt) {
maxInt = charCount[i];
}
}
Then I've made a for loop to check if there are any matches.
My next part of code is:
for (int i = 0; i < letterCount.length; i++ ) {
for (int j = 0; j <= maxInt; j++) {
if (letterCount[i] == maxInt) {
System.out.println("*");
} if (letterCount[i] == maxInt - j ) {
System.out.println("*");
} if (letterCount[i] != maxInt ) {
System.out.println(" ");
}
}
But here it where I got stuck.
How do i print asteriks all the way down and next to each other? Should I
work with spaces?
How do i know when to stop printing? Does my maxInt - j makes sense?
Can someone point my in the right direction?
I have to come up with a solution using for loops and arrays, So i cant
use any fancy methods yet :)
Thank you :)

How do I do this slider

How do I do this slider

I am still a beginner in programming and I am creating an object that
behaves more or less like a slider.
The slider goes this way. The dragger slides horizontally from the
coordinate x = -180px (full left) to + 180px (full right).
When the slider is full left, it has to represent the value defined by the
user and stored on the variable minValue. When the slider is full right it
has to represent tha value stored on the variable maxValue.
So, while the dragger slides from -180 to 180 pixels, it must return a
value from minValue to maxValue.
Suppose the slider is on position -32. How do I calculate the value of the
slider in the minValue/maxValue range?
Sorry about the question, but I am a beginner.
thanks.

Friday, 13 September 2013

JavaScript's session history management using S3 static hosting?

JavaScript's session history management using S3 static hosting?

I am currently developing a website that dominantly uses JavaScript (JS)
history.
Now the problem is, this history uses pathname of the URL. So for example
if I use S3 as static hosting, and for the first time would like to
request a URL like www.example.com/about, the S3 would redirect it to
/about folder instead of loading the root (www.example.com) and have the
JS to handle the /about. Of course, this behavior is absolutely normal in
case of static hosting, so it is tricky.
I am just wondering if it is possible that it would work in my case, using
S3, where every link based on the root (www.example.com/) would always
refer to the root website? In short, I'm expecting S3 would ignore the
pathname at all. So if I request for www.example.com/about, it will load
just the index.html located in www.example.com/index.html, while retaining
the URL (www.example.com/about).
If this is still not clear, think about JS's location.hash (#). Browser
will ignore that hash when making request to the static web server, then
when the web is loaded, the JS contained in it will handle the given hash.
So my case can be exactly solved by using "#" in my URL, but this time I
want to use a clean URL, which is without "#".
Thank you for your help. :)