Saturday, 31 August 2013

Strange Stack Overflow Error in Sudoko Backtracker

Strange Stack Overflow Error in Sudoko Backtracker

(Disclaimer: There are maybe 20 different versions of this question on SO,
but a reading through most of them still hasn't solved my issue)
Hello all, (relatively) beginner programmer here. So I've been trying to
build a Sudoku backtracker that will fill in an incomplete puzzle. It
seems to works perfectly well even when 1-3 rows are completely empty
(i.e. filled in with 0's), but when more boxes start emptying
(specifically around the 7-8 column in the fourth row, where I stopped
writing in numbers) I get a Stack Overflow Error. Here's the code:
import java.util.ArrayList;
import java.util.HashSet;
public class Sudoku
{
public static int[][] puzzle = new int[9][9];
public static int filledIn = 0;
public static ArrayList<Integer> blankBoxes = new ArrayList<Integer>();
public static int currentIndex = 0;
public static int runs = 0;
/**
* Main method.
*/
public static void main(String args[])
{
//Manual input of the numbers
int[] completedNumbers = {0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,0,0,
0,0,0,0,0,0,0,3,4,
8,9,1,2,3,4,5,6,7,
3,4,5,6,7,8,9,1,2,
6,7,8,9,1,2,3,4,5,
9,1,2,3,4,5,6,7,8};
//Adds the numbers manually to the puzzle array
ArrayList<Integer> completeArray = new ArrayList<>();
for(Integer number : completedNumbers) {
completeArray.add(number);
}
int counter = 0;
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
puzzle[i][j] = completeArray.get(counter);
counter++;
}
}
//Adds all the blank boxes to an ArrayList.
//The index is stored as 10*i + j, which can be retrieved
// via modulo and integer division.
boolean containsEmpty = false;
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
if(puzzle[i][j] == 0) {
blankBoxes.add(10*i + j);
containsEmpty = true;
}
}
}
filler(blankBoxes.get(currentIndex));
}
/**
* A general method for testing whether an array contains a
* duplicate, via a (relatively inefficient) sort.
* @param testArray The int[] that is being tested for duplicates
* @return True if there are NO duplicate, false if there
* are ANY duplicates.
*/
public static boolean checkDupl(int[] testArray) {
for(int i = 0; i < 8; i++) {
int num = testArray[i];
for(int j = i + 1; j < 9; j++) {
if(num == testArray[j] && num != 0) {
return false;
}
}
}
return true;
}
/**
* If the puzzle is not full, the filler will be run. The filler is my
attempt at a backtracker.
* It stores every (i,j) for which puzzle[i][j] == 0. It then adds 1
to it's value. If the value
* is already somewhere else, it adds another 1. If it is 9, and
that's already there, it loops to
* 0, and the index beforehand is rechecked.
*/
public static void filler(int indexOfBlank) {
//If the current index is equal to the size of blankBoxes, meaning
that we
//went through every index of blankBoxes, meaning the puzzle is
full and correct.
runs++;
if(currentIndex == blankBoxes.size()) {
System.out.println("The puzzle is full!" + "\n");
for(int i = 0; i < 9; i++) {
System.out.println();
for(int j = 0; j < 9; j++) {
System.out.print(puzzle[i][j]);
}
}
System.out.println("\n" + "The filler method was run " + runs
+ " times");
return;
}
//Assuming the puzzle isn't full, find the row/column of the
blankBoxes index.
int row = blankBoxes.get(currentIndex) / 10;
int column = blankBoxes.get(currentIndex) % 10;
//Adds one to the value of that box.
puzzle[row][column] = (puzzle[row][column] + 1);
//Just used as a breakpoint for a debugger.
if(row == 4 && column == 4){
int x = 0;
}
//If the value is 10, meaning it went through all the possible
values:
if(puzzle[row][column] == 10) {
//Do filler() on the previous box
puzzle[row][column] = 0;
currentIndex--;
filler(currentIndex);
}
//If the number is 1-9, but there are duplicates:
else if(!(checkSingleRow(row) && checkSingleColumn(column) &&
checkSingleBox(row, column))) {
//Do filler() on the same box.
filler(currentIndex);
}
//If the number is 1-9, and there is no duplicate:
else {
currentIndex++;
filler(currentIndex);
}
}
/**
* Used to check if a single row has any duplicates or not. This is
called by the
* filler method.
* @param row
* @return
*/
public static boolean checkSingleRow(int row) {
return checkDupl(puzzle[row]);
}
/**
* Used to check if a single column has any duplicates or not.
* filler method, as well as the checkColumns of the checker.
* @param column
* @return
*/
public static boolean checkSingleColumn(int column) {
int[] singleColumn = new int[9];
for(int i = 0; i < 9; i++) {
singleColumn[i] = puzzle[i][column];
}
return checkDupl(singleColumn);
}
public static boolean checkSingleBox(int row, int column) {
//Makes row and column be the first row and the first column of
the box in which
//this specific cell appears. So, for example, the box at
puzzle[3][7] will iterate
//through a box from rows 3-6 and columns 6-9 (exclusive).
row = (row / 3) * 3;
column = (column / 3) * 3;
//Iterates through the box
int[] newBox = new int[9];
int counter = 0;
for(int i = row; i < row + 3; i++) {
for(int j = row; j < row + 3; j++) {
newBox[counter] = puzzle[i][j];
counter++;
}
}
return checkDupl(newBox);
}
}
Why am I calling it a weird error? A few reasons:
The box that the error occurs on changes randomly (give or take a box).
The actual line of code that the error occurs on changes randomly (it
seems to always happen in the filler method, but that's probably just
because that's the biggest one.
Different compilers have different errors in different boxes (probably
related to 1)
What I assume is that I just wrote inefficient code, so though it's not an
actual infinite recursion, it's bad enough to call a Stack Overflow Error.
But if anyone that sees a glaring issue, I'd love to hear it. Thanks!

deprecated warnings in xcode and how to handle depracation

deprecated warnings in xcode and how to handle depracation

if ([self
respondsToSelector:@selector(dismissViewControllerAnimated:completion:)])
{[[self presentingViewController] dismissViewControllerAnimated:YES
completion:nil];} //post-iOS6.0
else {[self dismissModalViewControllerAnimated:YES];} //pre-iOS6.0
I'm doing the responds to selector (above) code to handle deprecated
methods. That way my app is compatible with older versions of iOS, but I'm
getting warnings in my code stating:
"'dismissModalViewControllerAnimated:' is deprecated: first deprecated in
iOS 6.0" I personally don't like any warning in my code, but more
importantly, I read somewhere that apple will complain about warnings in
your code.
1) Will Apple complain about warnings in your code?
2) Am I handling deprecated methods correctly?
3) Is there way to turn deprecated method method warnings off?

How do you add mysql-connector-java-5.1.26 to Eclipse Android Developer Tools

How do you add mysql-connector-java-5.1.26 to Eclipse Android Developer Tools

I want the following line of code to work in Eclipse Java but apparently I
need to import/add mysql-connector-java-5.1.26 to my eclipse android
project so I can send a mySQL query via an android device.
Class.forName("com.mysql.jdbc.Driver");
How can I add the mySQL library to a current project? I've seen other
tutorials about doing this here at stack overflow but they've been kind of
unspecific and just say "just ADD it to your current project" but that's
where I'm stumped.
Most tutorials online just tell you how to start a new project from
scratch, but I'm working with an android application.
Do I go to File>Import? and then select the .zip with the mySQL files? Or
do I select the folder or something? I'm doing this on a Mac.
Thanks.

PHP update is not updating database with checkbox

PHP update is not updating database with checkbox

to all i have a weird problem when i am trying to update a table of my
database with checkboxes it takes only one value and all the rest just
ingnores them here is my php code so far
foreach ($_POST['choice'] as $id){
$price=$_POST['price'][$id];
$availability=$_POST['availability'][$id];
$result1=mysql_query("UPDATE store SET
storeid='".$id."',availability='".$availability."', price='".$price."'
WHERE productid='".$par1."'");
}

Backbone: Scroll event not firing after back button is pressed

Backbone: Scroll event not firing after back button is pressed

As you can see here, when you click on an image and then click back,
Chrome doesn't let you scroll down anymore. I'm using the following
function to change the primary view of my Backbone application:
changeView: function(view, options) {
if (this.contentView) {
this.contentView.undelegateEvents();
this.contentView.stopListening();
this.contentView = null;
}
this.contentView = view;
if (!options || (options && !options.noScroll)) {
$(document).scrollTop(0);
}
this.contentView.render();
},
This function is called every time the route changes. As you can see, I'm
resetting the scroll position every time the primary view changes (so that
the user doesn't land on the middle of a view after scrolling down on the
previous view). However, when the user presses the back button, the scroll
event isn't firing at all if you try to scroll down. If you try to scroll
up, however, then the scroll positions seems to get reset to a position
further down the page, after which scrolling works normally.
Any ideas on what the cause might be?

jQuery UI Drag n Drop failed to lock

jQuery UI Drag n Drop failed to lock

Basically I have an image (droppable) and text (draggable). They are
matched by the data-pair attribute I've set on them. However, when I try
to console.log($(this).data('pair')) inside the drop callback, it gives
undefined. This is my code.
function handleDrop(event, ui, cb) {
console.log( $(this).data('pair') );
console.log( $(this).attr('data-pair') );
console.log( ui.draggable.data('pair') );
var dropped = $(this).data('pair');
var dragged = ui.draggable.data('pair');
var match = false;
if(dragged === dropped) {
//Match - Lock in place and increment found
match = true;
$(this).droppable( 'disable' );
ui.draggable.addClass( 'correct' );
ui.draggable.draggable( 'disable' );
ui.draggable.draggable( 'option', 'revert', false );
ui.draggable.position({
of: $(this),
my: 'left top',
at: 'left top'
});
} else {
ui.draggable.draggable( 'option', 'revert', true );
}
cb(match);
}
//Create Droppables (image + droppable div)
//imgContainer = #imgWrapper
var tempImgContainer = $('<div id="imgContainer' + i + '"></div>');
$('<img id="img' + i + '" src="' + key + '">').appendTo(tempImgContainer);
$('<div id="textForImg' + i + '" data-pair="' + i + '"></div>').droppable({
accept: '#textWrapper div',
hoverClass: 'hovered',
drop: function(event, ui) {
handleDrop(event, ui, callback);
}
}).appendTo(tempImgContainer);
$(imgContainer).append(tempImgContainer);
//Create Draggable
//textContainer = #textWrapper
var tempTextContainer = $('<div id="textContainer' + i + '" data-pair="' +
i + '">' + val + '</div>').draggable({
//quizContainer is a wrapper for both imgWrapper and textWrapper.
Example #quizContainer1
containment: quizContainer,
stack: '#textWrapper div',
cursor: 'move',
revert: true,
snap: true
});
$(textContainer).append(tempTextContainer);
i += 1;

Efficient use of sockets in c#

Efficient use of sockets in c#

I am using Sockets in C#.
I am using this to connect:
client = new Socket(AddressFamily.InterNetwork, SocketType.Stream,
ProtocolType.Tcp);
client.Connect(remoteEP);
I send a message using client.send...
I receive a message using client.receive...
I have read to maximise the performance of using sockets I should use
Ayscn Sockets.
Is this true and is there an optimised buffer number to use? e.g
buffer[256] (etc).
Also, on the Server side I assign a thread to an incoming client request.
Once the work is completed i close the socket. I have found this a good
way to manage clients but I have also found suggestions that this is not
the best way to go. Really just need advice on the best way to go and why.
thanks..

get sales_quote model in sales/Ordercontroller magento backend

get sales_quote model in sales/Ordercontroller magento backend

Hi how to get sales_quote model in ordercontroller magento backend?
i need to get the quote details in the ordercontroller.so, im using the
follwing code.
$quote= Mage::getModel('sales/quote')->load($quoteid);
.Above query returns empty data.
Mage_Sales_Model_Quote Object ( [_eventPrefix:protected] => sales_quote
[_eventObject:protected] => quote [_customer:protected] =>
[_addresses:protected] => [_items:protected] => [_payments:protected] =>
[_errorInfoGroups:protected] => Array ( )
[_preventSaving:protected] =>
[_resourceName:protected] => sales/quote
[_resource:protected] =>
[_resourceCollectionName:protected] => sales/quote_collection
[_cacheTag:protected] =>
[_dataSaveAllowed:protected] => 1
[_isObjectNew:protected] =>
[_data:protected] => Array
(
)
[_hasDataChanges:protected] =>
[_origData:protected] =>
[_idFieldName:protected] =>
[_isDeleted:protected] =>
[_oldFieldsMap:protected] => Array
(
)
[_syncFieldsMap:protected] => Array
(
)
) is there any possiblities to get quote? Help Me..

Friday, 30 August 2013

Prevent inclusion of mean in boxplot legend

Prevent inclusion of mean in boxplot legend

In ggplot2 boxplot with added mean, is there a way to prevent the mean
from being included with the legend? I must use a large point size and
find its inclusion in the legend distracting. The conceptually closest
problem I could find, for removing the slash from the legend of outlined
bar charts, is at
http://www.cookbook-r.com/Graphs/Legends_%28ggplot2%29/#modifying-the-legend-box
That solution uses geom_bar twice to overlay one plot on another, the
second, outlined bar chart, without a legend. But is there a solution for
preventing the mean from appearing in the boxplot legend?
ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) +
geom_boxplot() +
stat_summary(fun.y=mean, colour="darkred", geom="point", shape=18, size=3) +
# idea from above website
geom_boxplot(show_guide=FALSE)
Thank you.

Thursday, 29 August 2013

PHP + Mysql and memcache or phpsessions

PHP + Mysql and memcache or phpsessions

I currently manage a game that handles around 8K daily users, the current
server setup is
VPS: 16GB+8cores+ 160GBSSD.
Handles 8K daily users that are generating 600K daily direct calls to the
mysql DB;
The situation is: The game is growing, and server response is slowing down.
So! I'm looking for options to avoiding having an incredibly slow server,
and saw Memcache as a viable solution, and studying it I came up with 2
questions, which are:
Is it safe to store ONE Key value per user, that contains all user data,
perhaps as a concatenated string that would be around 100 characters long,
and then update the DB every once in a while? ->that would mean having
thousands of keys at the same time.
The idea is not to replace mysql, just to aid it in the users session and
be able to update the DB every so often, for this situation would Sessions
or Memcache be the right way to go?
thank you very much :)

Wednesday, 28 August 2013

How can I find the ecj version in eclipse?

How can I find the ecj version in eclipse?

I'm having a small issue where some java classes compiled in eclipse are
slightly different from the classes compiled by a standalone ecj (from the
same source code). How can I find the version of ecj that is being used by
eclipse? (I'm assuming that's where the difference is)

design pattern(GoF patterns) implementation in c++

design pattern(GoF patterns) implementation in c++

What are the elegant design pattern(GoF patterns) implementation in c++ ?
Can anyone give me some examples of design pattern implementations based
on template(which can be reused) ?
Example(Template based Singleton) :-
template<typename T>
class Singleton : public boost::noncopyable
{
public:
static Singleton& GetInstance()
{
boost::call_once(&CreateInstance, m_onceFlg);
return *m_pInstance;
}
virtual ~Singleton()
{
}
protected:
Singleton ()
{
}
static void CreateInstance()
{
m_pInstance.reset(new T());
}
private:
static boost::once_flag m_onceFlg;
static boost::scoped_ptr<T> m_pInstance;
};

can I get the parent job name which triggered a child job on autosys

can I get the parent job name which triggered a child job on autosys

Can I get the parent job name which triggered a child job on autosys
Lets say the condition for job J is as below J-> Suc(J1) and Suc(J2) and
Suc(J3)
If there is a job run for job 'J', How can I get to know if it was
triggered by J1 or J2 or J3 ?

Regarding a memory dump of 32-bit process on 64-bit Windows 7

Regarding a memory dump of 32-bit process on 64-bit Windows 7

I used 64-bit Windows 7's normal task manager (taskmgr) to dump the memory
of chrome processes, which are 32-bit, but then I read an article that
says it will mess up the dump. If 64-bit taskmgr does mess up the memory
dump of 32-bit processes, is there a way to convert the already-done
memory dump so that it will be properly analyzed?
Also, if you have full memory dump available, can a person re-create
processes and programs running before crash occurred?
http://www.devopsonwindows.com/memory-dumps-done-right/
http://blogs.msdn.com/b/tess/archive/2010/09/29/capturing-memory-dumps-for-32-bit-processes-on-an-x64-machine.aspx

Admob ad crops on nexus 7 device on landscape - android

Admob ad crops on nexus 7 device on landscape - android

i've implemented admob ad on my project.
its successfully loaded on all devices.
When testing on nexus 7 device on landscape mode , the ad crops on bottom.
nexus 7 device only have that problem, in other devices its fine.
How to solve this?

iOS Static library for unity with App switching issue Facebook integration

iOS Static library for unity with App switching issue Facebook integration

These days i am writing a iOS static library for unity games facebook
integration. Static library functionality is done and it works perfect.
One issue i am facing is dont have any appdelegate inside my static
library code so i cant add
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
NSLog(@"openURL");
return [FBSession.activeSession handleOpenURL:url];
}
Anywhere. This method needed to control app switching when app switch to
get read or publish permissions. I created a demo project and added this
method to the app delegate of demo project and it works Perfect but if i
dont add this method to Appdelegate of demo project app switching does not
happen. I dont want the plugin user to add this method manually after
getting output from unity.
Is there any way to figure it out. So that app switching works perfect. Do
i need add an appdelegate to static library classes or something else.

Tuesday, 27 August 2013

What's wrong with the facebook login?

What's wrong with the facebook login?

Whenever I log-in to Facebook I always go to this URL
("https://www.facebook.com/common/invalid_request.php"). Normally, when I
log-in it would take me directly to my main news feed. This started
happening about 2 days ago.

Android - Coding onActivityResult for embedded startActivityresult in custom CursorAdapter

Android - Coding onActivityResult for embedded startActivityresult in
custom CursorAdapter

Within my project I have an activity with a multi-column ListView. This
ListView draws its data from a custom CursorAdapter that I've implemented
in a separate java module. I have listeners on a couple of the views
within the ListView's rows, and these are implemented within the
CursorAdapter. One of the listeners needs to edit the view content that
called it and save the data back to the underlying database.
Based on advice received here I've managed to code the
startActivityForResult. However, I can't find how or where to code the
onActivityResult routine in order to process the response from the dialog
activity. Has anyone any advice?
public class CustomCursorAdapter extends CursorAdapter {
private static final String TAG = CustomCursorAdapter.class.getSimpleName();
private static final int EDIT_TIME_REQUEST_CODE = 11;
protected static class RowViewHolder {
public Button btnLap;
public TextView tvTime;
public Context ctx;
}
public CustomCursorAdapter(Context context, Cursor c) {
super(context, c);
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View retView = inflater.inflate(R.layout.single_row_item, parent, false);
RowViewHolder holder = new RowViewHolder();
holder.btnLap = (Button) retView.findViewById(R.id.btn_lap);
holder.tvTime = (TextView) retView.findViewById(R.id.tv_time);
holder.ctx = context;
holder.btnLap.setOnClickListener(btnLapOnClickListener);
holder.tvTime.setOnClickListener(tvTimeOnClickListener);
retView.setTag(holder);
return retView;
}
...
private OnClickListener tvTimeOnClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
TextView tv = (TextView) v;
String strTime = tv.getText().toString();
// get the RowViewHolder
RowViewHolder holder = new RowViewHolder();
holder = (RowViewHolder) ((View) v.getParent()).getTag();
Intent intentTimeEdit = new Intent(holder.ctx,
TimeEditDialog.class);
intentTimeEdit.putExtra("Time", strTime);
// Set up intent to pass to dialog
((Activity)holder.ctx).startActivityForResult(intentTimeEdit,
EDIT_TIME_REQUEST_CODE);
}
}
};
}

Nodejs, phantomjs, heroku

Nodejs, phantomjs, heroku

I used following buildpack to build a phantomjs / nodejs application on
herouku, with no success:
http://github.com/heroku/heroku-buildpack-nodejs.git
and http://github.com/heroku/heroku-buildpack-nodejs
http://github.com/stomita/heroku-buildpack-phantomjs
phantom stderr: execvp(): Permission denied
/app/web.js:127
return ph.createPage(function(err, page) {
^
TypeError: Cannot call method 'createPage' of undefined
at phantom.create.phantomPath (/app/web.js:127:18)
my webjs is:
app.get('/', function(req, res){
// If there is _escaped_fragment_ option, it means we have to
// generate the static HTML that should normally return the Javascript
if(typeof(req.query._escaped_fragment_) !== "undefined") {
phantom.create(function(err, ph) {
return ph.createPage(function(err, page) {
// We open phantomJS at the proper page.
return page.open("http://myurl.com/#!" +
req.query._escaped_fragment_, function(status) {
return page.evaluate((function() {
// We grab the content inside <html> tag...
return document.getElementsByTagName('html')[0].outerHTML;
}), function(err, result) {
// ... and we send it to the client.
res.send(result);
return ph.exit();
});
});
});
},{phantomPath:"/app/vendor/phantomjs/bin"});
}
else
// If there is no _escaped_fragment_, we return the normal index
template.
//res.render('index');
res.sendfile(__dirname + '/app/index.html');
});
if I run it locally on a macbook it works, I use node-phantom-simple
without socket.io and cluster support. I can't change the permissions on
the phantomjs binary, they stay always 700, and heroku support told me,
that i'm responsible for the permissions on the files via buildpack.
Any suggestions?
Thanks, Patrick

How to "unzip" then slice and find max for elements in a list of lists in Python

How to "unzip" then slice and find max for elements in a list of lists in
Python

I have a list of lists and need to find a way to find the max of the
numerical portion of element [0] of each list. I know it'll involve
slicing and finding max and think it'll involve the zip(*L) function but
don't really know how to get there. For example, what I have is a list of
lists that looks like this:
L = [['ALU-001', 'Aluminum', 50], ['LVM-002', 'Livermorium', 20],
['ZIN-003', 'Zinc', 30]]
and need to find the largest numerical portion (ex. 001) of the first
elements.

Disassembling an Asus S56CB to expose its msata disk

Disassembling an Asus S56CB to expose its msata disk

I bought an msata SSD disk to replace the crappy U100 that comes with this
laptop.
Now I can't figure out how to disassemble and install it.
Usually google is very generous with hints, but not this time.

Could not load an entity in hibernate

Could not load an entity in hibernate

Can any one tell me why I'm getting this exception in my project.
org.hibernate.exception.GenericJDBCException: could not load an entity:
[com.expo.esf.model.HouseBL#22344]
I can save records to database but whenever i try to load the entity for
edit. it shows the above message.
Below is the entity definition:
package com.expo.esf.model;
import java.util.Date;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.persistence.Transient;
/**
*
* @author tanvir.rahman
*
*/
@Entity
@Table(name = "invoice_house")
public class InvoiceHouse extends BaseModel {
@Id
@GeneratedValue
@Column(name = "id")
private Long id;
@JoinColumn(name = "company_id", referencedColumnName = "id")
@ManyToOne
private Company company;
@JoinColumn(name = "carrier_mode_id", referencedColumnName = "id")
@ManyToOne
private CarrierMode carrierMode;
@JoinColumn(name = "inv_type_id", referencedColumnName = "id")
@ManyToOne
private InvoiceType invType;
@Column(name = "invoice_no")
private String invoiceNo;
@JoinColumn(name = "house_id", referencedColumnName = "id")
@ManyToOne
private HouseBL houseBL;
@Column(name = "ref_invoice_no")
private String refInvoiceNo;
@Column(name = "debit_credit_no")
private String debitCreditNo;
@JoinColumn(name = "shipper_id", referencedColumnName = "id")
@ManyToOne
private Shipper shipper;
@JoinColumn(name = "consignee_id", referencedColumnName = "id")
@ManyToOne
private Consignee consignee;
@JoinColumn(name = "buying_house_id", referencedColumnName = "id")
@ManyToOne
private BuyingHouse buyingHouse;
@Column(name = "inv_open_date")
private Date invOpenDate;
@Column(name = "inv_issue_date")
private Date invIssueDate;
@JoinColumn(name = "currency_id", referencedColumnName = "id")
@ManyToOne
private Currency currency;
@Column(name = "exchange_rate")
private float exchangeRate;
@JoinColumn(name = "issued_user_id", referencedColumnName = "id")
@ManyToOne
private User user;
@Column(name = "total_inv_amount")
private float totalInvAmount;
@Column(name = "total_cost_amount")
private float totalCostAmount;
@Column(name = "profit")
private float profit;
@Column(name = "status_id")
private long status;
@Column(name = "total_debitcredit_amount")
private float totalDebitCreditAmount;
@Column(name = "reff_inv_tamount")
private float reffInvTamount;
@Column(name = "diff_amount")
private float diffAmount;
@Column(name = "description", length = 500)
private String description;
@Column(name = "authorization_remarks", length = 500)
private String authorizationRemarks;
@Column(name = "authorized_by", length = 128)
private String authorizedBy;
private boolean authorized;
@Transient
private String houseBlNo;
@Transient
private String exchangeRateStr;
@Transient
private String partyType;
@Transient
private String button;
@Transient
private List<ShipmentChargeDetails> houseChargeDetailsList;
@Transient
private List<ShipmentChargeDetails> houseCostDetailsList;
@Transient
private List<InvoiceHouseDetails> invoiceHouseChargeDetailsList;
@Transient
private List<InvoiceHouseDetails> invoiceHouseCostDetailsList;
@Transient
private List<InvoiceHouseDetails> invoiceHouseDetailsList;
@Transient
private String errorCharge;
@Transient
private String errorCost;
public List<ShipmentChargeDetails> getHouseChargeDetailsList() {
return houseChargeDetailsList;
}
public void setHouseChargeDetailsList(List<ShipmentChargeDetails>
houseChargeDetailsList) {
this.houseChargeDetailsList = houseChargeDetailsList;
}
public InvoiceHouse() {
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
public CarrierMode getCarrierMode() {
return carrierMode;
}
public void setCarrierMode(CarrierMode carrierMode) {
this.carrierMode = carrierMode;
}
public InvoiceType getInvType() {
return invType;
}
public void setInvType(InvoiceType invType) {
this.invType = invType;
}
public String getInvoiceNo() {
return invoiceNo;
}
public void setInvoiceNo(String invoiceNo) {
this.invoiceNo = invoiceNo;
}
public HouseBL getHouseBL() {
return houseBL;
}
public void setHouseBL(HouseBL houseBL) {
this.houseBL = houseBL;
}
public String getRefInvoiceNo() {
return refInvoiceNo;
}
public void setRefInvoiceNo(String refInvoiceNo) {
this.refInvoiceNo = refInvoiceNo;
}
public String getDebitCreditNo() {
return debitCreditNo;
}
public void setDebitCreditNo(String debitCreditNo) {
this.debitCreditNo = debitCreditNo;
}
public Shipper getShipper() {
return shipper;
}
public void setShipper(Shipper shipper) {
this.shipper = shipper;
}
public Consignee getConsignee() {
return consignee;
}
public void setConsignee(Consignee consignee) {
this.consignee = consignee;
}
public BuyingHouse getBuyingHouse() {
return buyingHouse;
}
public void setBuyingHouse(BuyingHouse buyingHouse) {
this.buyingHouse = buyingHouse;
}
public Date getInvOpenDate() {
return invOpenDate;
}
public void setInvOpenDate(Date invOpenDate) {
this.invOpenDate = invOpenDate;
}
public Date getInvIssueDate() {
return invIssueDate;
}
public void setInvIssueDate(Date invIssueDate) {
this.invIssueDate = invIssueDate;
}
public Currency getCurrency() {
return currency;
}
public void setCurrency(Currency currency) {
this.currency = currency;
}
public float getExchangeRate() {
return exchangeRate;
}
public void setExchangeRate(float exchangeRate) {
this.exchangeRate = exchangeRate;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public float getTotalInvAmount() {
return totalInvAmount;
}
public void setTotalInvAmount(float totalInvAmount) {
this.totalInvAmount = totalInvAmount;
}
public float getTotalCostAmount() {
return totalCostAmount;
}
public void setTotalCostAmount(float totalCostAmount) {
this.totalCostAmount = totalCostAmount;
}
public float getProfit() {
return profit;
}
public void setProfit(float profit) {
this.profit = profit;
}
public long getStatus() {
return status;
}
public void setStatus(long status) {
this.status = status;
}
public float getTotalDebitCreditAmount() {
return totalDebitCreditAmount;
}
public void setTotalDebitCreditAmount(float totalDebitCreditAmount) {
this.totalDebitCreditAmount = totalDebitCreditAmount;
}
public float getReffInvTamount() {
return reffInvTamount;
}
public void setReffInvTamount(float reffInvTamount) {
this.reffInvTamount = reffInvTamount;
}
public float getDiffAmount() {
return diffAmount;
}
public void setDiffAmount(float diffAmount) {
this.diffAmount = diffAmount;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getHouseBlNo() {
return houseBlNo;
}
public void setHouseBlNo(String houseBlNo) {
this.houseBlNo = houseBlNo;
}
public String getExchangeRateStr() {
return exchangeRateStr;
}
public void setExchangeRateStr(String exchangeRateStr) {
this.exchangeRateStr = exchangeRateStr;
}
public String getPartyType() {
return partyType;
}
public void setPartyType(String partyType) {
this.partyType = partyType;
}
public String getButton() {
return button;
}
public void setButton(String button) {
this.button = button;
}
public List<ShipmentChargeDetails> getHouseCostDetailsList() {
return houseCostDetailsList;
}
public void setHouseCostDetailsList(
List<ShipmentChargeDetails> houseCostDetailsList) {
this.houseCostDetailsList = houseCostDetailsList;
}
public List<InvoiceHouseDetails> getInvoiceHouseChargeDetailsList() {
return invoiceHouseChargeDetailsList;
}
public void setInvoiceHouseChargeDetailsList(
List<InvoiceHouseDetails> invoiceHouseChargeDetailsList) {
this.invoiceHouseChargeDetailsList = invoiceHouseChargeDetailsList;
}
public List<InvoiceHouseDetails> getInvoiceHouseCostDetailsList() {
return invoiceHouseCostDetailsList;
}
public void setInvoiceHouseCostDetailsList(
List<InvoiceHouseDetails> invoiceHouseCostDetailsList) {
this.invoiceHouseCostDetailsList = invoiceHouseCostDetailsList;
}
public List<InvoiceHouseDetails> getInvoiceHouseDetailsList() {
return invoiceHouseDetailsList;
}
public void setInvoiceHouseDetailsList(
List<InvoiceHouseDetails> invoiceHouseDetailsList) {
this.invoiceHouseDetailsList = invoiceHouseDetailsList;
}
public String getErrorCharge() {
return errorCharge;
}
public void setErrorCharge(String errorCharge) {
this.errorCharge = errorCharge;
}
public String getErrorCost() {
return errorCost;
}
public void setErrorCost(String errorCost) {
this.errorCost = errorCost;
}
public String getAuthorizationRemarks() {
return authorizationRemarks;
}
public void setAuthorizationRemarks(String authorizationRemarks) {
this.authorizationRemarks = authorizationRemarks;
}
public boolean isAuthorized() {
return authorized;
}
public void setAuthorized(boolean authorized) {
this.authorized = authorized;
}
public String getAuthorizedBy() {
return authorizedBy;
}
public void setAuthorizedBy(String authorizedBy) {
this.authorizedBy = authorizedBy;
}
}
}
Below is the method in which i'm getting error:
@Override
public InvoiceHouse getInvoiceHouse(long invoiceHouseId) {
InvoiceHouse invoiceHouse = null;
Query query = em.createQuery(" FROM InvoiceHouse ih WHERE ih.id =
:invoiceHouseId ");
query.setParameter("invoiceHouseId", invoiceHouseId);
try {
invoiceHouse = (InvoiceHouse) query.getSingleResult();
} catch (Exception e) {
log.debug("Error in getInvoiceHouse()------> "+e.getMessage());
}
return invoiceHouse;
}
Table definition:
Name Null? Type
ID NOT NULL NUMBER(19)
CREATED_BY VARCHAR2(128 CHAR)
CREATED_DATE TIMESTAMP(6)
UPDATED_BY VARCHAR2(128 CHAR)
UPDATED_DATE TIMESTAMP(6)
VERSION NOT NULL NUMBER(10)
DEBIT_CREDIT_NO VARCHAR2(255 CHAR)
DESCRIPTION VARCHAR2(500 CHAR)
DIFF_AMOUNT FLOAT(126)
EXCHANGE_RATE FLOAT(126)
INV_ISSUE_DATE TIMESTAMP(6)
INV_OPEN_DATE TIMESTAMP(6)
INVOICE_NO VARCHAR2(255 CHAR)
PROFIT FLOAT(126)
REF_INVOICE_NO VARCHAR2(255 CHAR)
REFF_INV_TAMOUNT FLOAT(126)
STATUS_ID NUMBER(19)
TOTAL_COST_AMOUNT FLOAT(126)
TOTAL_DEBITCREDIT_AMOUNT FLOAT(126)
TOTAL_INV_AMOUNT FLOAT(126)
BUYING_HOUSE_ID NUMBER(19)
CARRIER_MODE_ID NUMBER(19)
COMPANY_ID NUMBER(19)
CONSIGNEE_ID NUMBER(19)
CURRENCY_ID NUMBER(19)
HOUSE_ID NUMBER(19)
INV_TYPE_ID NUMBER(19)
SHIPPER_ID NUMBER(19)
ISSUED_USER_ID NUMBER(19)
AUTHORIZATION_REMARKS VARCHAR2(500 CHAR)
AUTHORIZED NUMBER(1)
AUTHORIZED_BY VARCHAR2(128 CHAR)

Grid collapsing Bootstrap 3

Grid collapsing Bootstrap 3

made a grid of goods Bootstrap 3, all good, but when the name of the
product does not fit on one line, the entire grid flies and get this:

How can I fix this?
A living example with code here

Monday, 26 August 2013

Android keyboard and remapping the CTRL key

Android keyboard and remapping the CTRL key

I have an Samsung Galaxy 10.1 running Android version 4.1.2. I am using
ssh to remotely connect to my main machine which runs Ubuntu 12.04 LTS.
Once I am connected I do all my work in emacs 24.3. I also have a
bluetooth keyboard.
My question is about remapping the Caps-Lock key to function as the Ctrl
key. I do this with my main machine by changing a setting in the terminal
options. I checked the options in juiceSSH and there appears to be no
equivalent. Perhaps there is a general way to do this with Android or the
Bluetooth Keyboard.
How can I remap the Caps-Lock character to function as the Ctrl character?
If you need more information let me know. Thanks in advance!

Ajax Posts but does not call Django View

Ajax Posts but does not call Django View

The Problem
After posting to my django view, the code seems to just stop halfway through.
I have an ajax post to a Django view that is hard coded to render a
specific response (see below). When I post to that view it should always
return that response, but for some reason the view out puts all of the
print statements, but not the query or the render. I know I'm being
redirected by my sever log (shown below).
Any idea what could be causing this behavior?
Server log:
127.0.0.1 - - [26/Aug/2013 21:27:23] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [26/Aug/2013 21:27:23] "GET /static/css/style.css HTTP/1.1"
304 -
127.0.0.1 - - [26/Aug/2013 21:27:23] "GET /static/js/map.js HTTP/1.1" 200 -
127.0.0.1 - - [26/Aug/2013 21:27:23] "GET /static/js/home_jquery.js
HTTP/1.1" 304 -
127.0.0.1 - - [26/Aug/2013 21:27:23] "GET
/static/js/jquery_cookie/jquery.cookie.js HTTP/1.1" 304 -
127.0.0.1 - - [26/Aug/2013 21:27:23] "GET /favicon.ico HTTP/1.1" 404 -
I've been posted. Here are my values
<QueryDict: {u'name': [u'Mission Chinese Food'], u'address': [u'154
Orchard Street Manhattan']}>
Mission Chinese Food
154 Orchard Street Manhattan
127.0.0.1 - - [26/Aug/2013 21:27:32] "POST /results/ HTTP/1.1" 200 -
Simple Django View:
def results(request):
if request.method == 'POST':
print "I've been posted. Here are my values"
print request.POST
print request.POST.get('name')
print request.POST.get('address')
restaurant = Restaurant.objects.filter(name='Fish', address='280
Bleecker St')[0]
return render(request, "stamped/restaurant.html", {'restaurant':
restaurant}
Simple ajax post:
var send_data = { 'name': place.name, 'address': address};
var csrftoken = $.cookie('csrftoken');
alert(csrftoken);
alert(send_data);
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
crossDomain: false, // obviates need for sameOrigin test
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type)) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
$.ajax({ url: '/results/',
type: 'POST',
data: send_data,
success: function(response) {
console.log("everything worked!");
},
error: function(obj, status, err) { alert(err); console.log(err); }
});
});

How to evaluate this statement? (uses #define)

How to evaluate this statement? (uses #define)

If I defined the absolute value of a number as
#define ABS(X) X >= 0 ? X : (-1) * X
what would
ABS(2) + ABS(-3)
evaluate to? My friend claims it evaluates to 2.

POST data and redirect to the same page CakePHP

POST data and redirect to the same page CakePHP

I am using 'HttpSocket', 'Network/Http' and am using new
HttpSocket()->post('uri','dataToBePassed)
It does post the data but, I want user to be redirected to the page. I
tried passing array('redirect'=>true), no go...
any ideas>

Associate specific SLF4J logger with Jetty embedded

Associate specific SLF4J logger with Jetty embedded

I'm trying to assign a specific SLF4J logger instance to my Jetty embedded
server using the following lines of code:
Logger myLogger = LoggerFactory.getLogger("Web Server");
Log.setLog((org.eclipse.jetty.util.log.Logger) myLogger)
where myLogger is an instance of org.slf4j.Logger. This returns a
ClassCastException since
org.slf4j.impl.Log4jLoggerAdapter cannot be cast to
org.eclipse.jetty.util.log.Logger`
How then can I go about this process?

Progromatically hide overflow button in Android

Progromatically hide overflow button in Android

I have a searchView widget in the action bar. I've seen a few guides to
hiding particular action bar buttons progromatically. However I want to
keep one other button there but hide the overflow button if I could to
conserve action bar space, and the overflow button isn't covered in any of
these other questions.
It would have to come back after the searchview is closed as well. I hope
to do this with a searchview listener.
Any ideas?

Hi, I was wondering how to create a navigation menu, like the one at the bottom of your site. I want the list style navigation

Hi, I was wondering how to create a navigation menu, like the one at the
bottom of your site. I want the list style navigation

using wordpress and there is a place to create a custom code. I want to
make a navigation footer like the one at the bottom of your website. Can
anyone send me info on how to create a navigation menu like that. I want
the stacked list style navigation for a website I am working on and cant
find any info anywhere to do such a thing.
Thanks, Lucas

Powershell How to exlude a directory

Powershell How to exlude a directory

i'm a beginner on powershell scripting so keep cool ^^
I would like to delete file on directory d:\test I delete only file more
15 days but I'don't want to delete files on another directory in directory
d:\test.
My script
#----- define parameters -----#
#----- get current date ----#
$Now = Get-Date
#----- define amount of days ----#
$Days = "15"
#----- define folder where files are located ----#
$TargetFolder = "d:\test"
#----- define extension ----#
$Extension = "*.bak"
#----- define LastWriteTime parameter based on $Days ---#
$LastWrite = $Now.AddDays(-$Days)
#----- get files based on lastwrite filter and specified folder ---#
$Nomatch = "d:\test\ZZ - Archives","d:\test\ZZ - Cloture Paye"
$Files = Get-Childitem $TargetFolder -Include $Extension -Recurse | Where
{$_.LastWriteTime -le "$LastWrite"} |
Where-Object {$_.FullName -notmatch "$Nomatch"}
foreach ($File in $Files)
{
if ($File -ne $NULL)
{
write-host "Deleting File $File" -ForegroundColor "DarkRed"
Remove-Item $File.FullName | out-null
}
else
{
Write-Host "No more files to delete!" -foregroundcolor "Green"
}
}

Cocos2d - HTML5 Sprite Sheet - Sprite not displayed

Cocos2d - HTML5 Sprite Sheet - Sprite not displayed

1 )I'm preloading intro1.plist
{type:"plist",src:"intro1.plist"},
2) In the main class I'm adding sprite frames like that:
var cache = cc.SpriteFrameCache.getInstance();
cache.addSpriteFrames("intro1.plist", "intro1.png");
3) I'm creating sprite
var sp = cc.Sprite.createWithSpriteFrameName("boat0016.png");
sp.setAnchorPoint(cc.p(0.5, 0.5));
sp.setPosition(new cc.Point(100,100));
console.log("x",sp.getPositionX());
console.log("y",sp.getPositionY());
console.log("wid",sp.getContentSize().width);
console.log("hei",sp.getContentSize().height);
console.log("visible?",sp.isVisible());
this.addChild(sp,1);
i'm getting x,y,width,height of this sprite but the sprite isn't visible.
I event hided all other elements to be sure it's not covered by another
graphics and I see only black screen. If I create the sprite using normal
PNG file it works.

Sunday, 25 August 2013

How do I correctly proxy https traffic?

How do I correctly proxy https traffic?

I'm trying to set up a proxy server that can handle both http and https
traffic without prompting the browser about certificates (just like
tunlr.net).
So far I've tried to use Squid and Nginx.
While handling regular http traffic is a walk in the park, https is
proving very difficult.
Can anybody point me in the right direction?

[ PDAs & Handhelds ] Open Question : Downloading Apps for a Samsung Smartphone (Ireland)?

[ PDAs & Handhelds ] Open Question : Downloading Apps for a Samsung
Smartphone (Ireland)?

What website can I download Apps for a Samsung smartphone without the
phone being registered? It was made/bought in Korea so I can't register it
with Vodafone, they've told me. But I'd rather not buy a new phone. Its a
Galaxy Ace.

What is called Base in Dojo?

What is called Base in Dojo?

The kernel of Dojo is Base, an ultra-compact, highly optimized library
that provides the foundation for everything else in the toolkit.
I'm quite new to dojo toolkit. In the above context what's the meaning of
kernal of Dojo?
What is called Base in Dojo?

Saturday, 24 August 2013

how to query logged in user using ion auth with codeigniter

how to query logged in user using ion auth with codeigniter

I asked a similar question a while back but i dont think im doing it
correctly.
im creating a control panel, and the control panel needs to know who's
logged in and if he is an admin, on just about ever page of this project.
right now to get this to work i have this in my header of every page:
$user = $this->ion_auth->user()->row();
$fname = $user->first_name;
$lname = $user->last_name;
$email = $user->email;
$uid = $user->id;
$avatar = $user->avatar;
however, im now thinking i should be able to do this in the model ya?
maybe using a helper or library? if im thinking correctly could someone
give me a rough step by step on how to do that? Ive never created a helper
or library in codeigniter.

How to disable an eventHandler in pyqt?

How to disable an eventHandler in pyqt?

I need to disable the textChanged()-Signal of a QTextBrowser if I need to.
I want to do this because of this: Typing in a qtextbrowser, then through
the connection of textChanged() in realtime formating the content, and
re-setting it into the qtextbrowser triggers textChanged() and this again
the realtime formatting ... infinite loop. So I need to disable that the
formatting triggers textChanged().
How do I do this in pyqt4?

How do I create a list of user inputs?

How do I create a list of user inputs?

I am coding in Java and I have to create a program that accepts user
input, which I have done. But I am confused as to what statement I can use
to list those integer input by the user.
This is what I have so far:
//Biker's Journey Program
import java.util.Scanner;
public class lab2
{
public static void main( String[] args )
{
Scanner input = new Scanner( System.in);
int w;
int x;
int y;
int z;
int result;
System.out.print("Please enter the first day's traveled miles: ");
w = input.nextInt();
System.out.print("Please enter the second day's traveled miles: ");
x = input.nextInt();
System.out.print("Please enter the third day's traveled miles: ");
y = input.nextInt();
System.out.print("Please enter the last day's traveled miles: ");
z = input.nextInt();
System.out.print("The number of miles traveled was: ");
System.out.println()
result = (w + x + y + z) / 4;
System.out.printf("The average miles per day traveled is %d\n", result);
}
}
And this segment of code does the computing, I just can not figure out how
to get the integers listed like this this picture:
http://imgur.com/KFNkWEd

Calling a click event or JQuery function from the code behind VB.NET

Calling a click event or JQuery function from the code behind VB.NET

I have a JQuery (v1.8) which handles the code after clicking a hyperlink.
I would like to call that click or do anything else (as the clicking of
the link would) to enforce the JQuery to run from the code behind. Any
ideas?
JQuery code:
<script type="text/javascript">
jQuery(document).ready(function (){
jQuery('#lnkShowModule').toggle(
function (){
jQuery(this).html('Hide the Module');
jQuery('.hide-element').toggle();
},
function (){
jQuery(this).html('Show the Hidden Module');
jQuery('.hide-element').toggle();
}
);
});
and this is my link on the ascx control:
<a id="lnkShowModule" href="#"> show the hidden module</a>
any ideas?

How to break symbol (displaystyle) into two lines

How to break symbol (displaystyle) into two lines

How can we break formula mentioned below into into two lines?
$\displaystyle \boldsymbol{{\left( {x\log x} \right)^{\log \log x}}\left\{
{\frac{1}
\left( {\log x + \log \log x} \right) + \left( {\log \log x} \right)\left(
{\frac{1}{x} + \frac{1}} \right)} \right\} }$
FYI: I'm using two column layout and this symbol is getting overlapped
over next column.

Connect 4 game javascript diagonal checking from Southeast to Northwest

Connect 4 game javascript diagonal checking from Southeast to Northwest

This is related to the post "algorithm connect four javascript" answered
by user:462803 Koviko. I just used the codes of Koviko in my connect 4
javascript. But I encountered issue.
This is the codes of Koviko:
function isVictory(placedX, placedY) {
var i, j, x, y, maxX, maxY, steps, count = 0,
directions = [
{ x: 0, y: 1 }, // North-South
{ x: 1, y: 0 }, // East-West
{ x: 1, y: 1 }, // Northeast-Southwest
{ x: 1, y: -1 } // Southeast-Northwest
];
// Check all directions
outerloop:
for (i = 0; i < directions.length; i++, count = 0) {
// Set up bounds to go 3 pieces forward and backward
x = Math.min(Math.max(placedX - (3 * directions[i].x), 0),
circle.length );
y = Math.min(Math.max(placedY - (3 * directions[i].y), 0),
circle[0].length );
maxX = Math.max(Math.min(placedX + (3 * directions[i].x),
circle.length ), 0);
maxY = Math.max(Math.min(placedY + (3 * directions[i].y),
circle[0].length ), 0);
steps = Math.max(Math.abs(maxX - x), Math.abs(maxY - y));
for (j = 0; j < steps; j++, x += directions[i].x, y += directions[i].y) {
if (circle[x][y] == circle[placedX][placedY]) {
// Increase count
if (++count >= 4) {
return true;
break outerloop;
}
} else {
// Reset count
count = 0;
}
}
}
//return count >= 4;
}
I slightly edit the code. But that is the final code that is working with
my connect four game. The only problem is the Southeast to Northwest
traverse is not working, and it will only win this coordinates
Southeast-Northwest 6,0 5,1 4,2 3,3.
Though I have completed this in a hardcode way but I just want to finish
this game that using javascript math object for better runtime. Here is
the demo: http://jsfiddle.net/iahboy/Cwp8x/.
Thank you so much. Hope someone will help me.

JQuery onclick execute event of input field

JQuery onclick execute event of input field

I don´t know if it´s possible do this , in this case i want when click
over input text field activate function in jQuery and after of this action
execute the code of jQuery - inside onclick - , i put my example :
<input type="password" name="password" value=""
class="input_text_register" id="pass" onclick="jQuery("#list").show();"/>
I can´t do this works , i supose i have some error because no get works
finally , in this case the activation from input text field open other div
for show informations
Thank´s , Regards !

starting sshd: /etc/ssh/sshd_config: permission denied

starting sshd: /etc/ssh/sshd_config: permission denied

I am running a Centos machine in Amazon cloud. Suddenly, I can't ssh into
it. Fortunately, there is R Studio running that includes an ability to run
BASH shell. So, I see in /var/log/boot.log that sshd failed to start.
When I run it from the command line sudo service sshd start I get an error
that Starting sshd: /etc/ssh/sshd_config: Permission denied. I tried to
set sshd_config permissions to either 644 or 600 - but I get the same
error. Also I tried sudo su - and then start service.
And it is not the limitation of the shell itself: I can start httpd
without any problems.
I don't even know what else to try...

Friday, 23 August 2013

My geddy model isn't creating objects and failing silently

My geddy model isn't creating objects and failing silently

I'm running a standard geddy setup with mongo.
Routes:
router.get('/submit').to('Urls.add');
router.post('/create').to('Urls.create');
Controller:
// invokes the form for submitting a new url
// sends form output to the create function
this.add = function (req, resp, params) {
this.respond({params: params});
};
// creates a new url object and saves it to the database
this.create = function (req, resp, params) {
var self = this;
var timestamp = new Date().getTime();
var url = geddy.model.Url.create({
title: params.title,
url: params.url,
score: 0,
created: timestamp
});
url.save(function(err, data) {
if (err) {
params.errors = err;
self.transfer('add');
} else {
this.redirect({controller: 'Url.index'});
}
});
};
Model:
var Url = function () {
this.defineProperties({
title: {type:'string', required:true},
url: {type:'string', required:true},
score: {type:'int', required:true},
created: {type:'datetime', required:true}
});
this.validatesPresent('title');
this.validatesPresent('url');
};
Url = geddy.model.register('Url', Url);
View:
<div class="row">
<form class="form-horizontal" role="form" action="/create" method="POST">
<div class="form-group">
<label for="title" class="col-lg-1 control-label">Title</label>
<div class="col-lg-7">
<input type="text" class="form-control" id="title"
placeholder="title">
</div>
</div>
<div class="form-group">
<label for="url" class="col-lg-1 control-label">URL</label>
<div class="col-lg-7">
<input type="text" class="form-control" id="url"
placeholder="url">
</div>
</div>
<div class="form-group">
<div class="col-lg-offset-1 col-lg-7">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</div>
When I visit /submit and fill out the form, I just get redirected to the
same form again. Nothing gets inserted in the database. This is my first
time using geddy so I'm probably missing something.

python: cooperative supercall of __getattr__

python: cooperative supercall of __getattr__

I'm working with somethign similar to this code:
class BaseClass(object):
def __getattr__(self, attr):
return lambda:'1'
class SubClass(BaseClass):
suffix = '2'
def foo(self):
return super(SubClass, self).foo() + self.suffix
class SubClass2(SubClass):
suffix = '3'
def foo(self):
return super(SubClass2, self).foo() + self.suffix
o = SubClass2()
print o.foo()
I'd expect to see output of '123', but I instead I get an error
AttributeError: 'super' object has no attribute 'foo'. Python isn't even
attempting to use the base class's __getattr__.
Without modifying the base class, and keeping the two super calls similar,
I'm not able to get the output I want. Is there any cooperative supercall
pattern that will work for me here?
I understand that super() overrides getattr in some way to do what it
needs to do, but I'm asking if there's any reasonable workaround that
allows a subclass's __getattr__ to be called when appropriate.

Install Ruby 2.0.0-p247 with rbenv and erro in /tmp/ruby

Install Ruby 2.0.0-p247 with rbenv and erro in /tmp/ruby

I'm trying to install Ruby 2.0.0-p247 with rbenv and I keep getting the
same error no matter what I do. Here's the command and response:
&#10140; ~ rbenv install 2.0.0-p247
Downloading ruby-2.0.0-p247.tar.gz... ->
http://stackoverflow.com/ftp://ftp.ruby-lang.org/pub/ruby/2.0/ruby-2.0.0-p247.tar.gz
Installing ruby-2.0.0-p247...
BUILD FAILED
Inspect or clean up the working tree at
/tmp/ruby-build.20130823153529.15739 Results logged to
/tmp/ruby-build.20130823153529.15739.log
Last 10 log lines: from ./tool/rbinstall.rb:242:in each' from
./tool/rbinstall.rb:242:ininstall_recursive' from
./tool/rbinstall.rb:397:in block in <main>' from
./tool/rbinstall.rb:758:incall' from ./tool/rbinstall.rb:758:in block (2
levels) in <main>' from ./tool/rbinstall.rb:755:ineach' from
./tool/rbinstall.rb:755:in block in <main>' from
./tool/rbinstall.rb:751:ineach' from ./tool/rbinstall.rb:751:in `' make:
** [do-install-all] Erro 1

Dealing with CORS and Cookie domain across subdomains

Dealing with CORS and Cookie domain across subdomains

I'm having difficulty reconciling some conflicting information from
StackOverflow and other sources regarding the use of calls across
sub-domains. Consider these two independent sites that share a common
domain:
site #1: www.myDomain.com
site #2: sub.myDomain.com
Requirements:
(1) Site #1 must be able to execute an AJAX call to site #2 by way of
sub.myDomain.com/handler.ashx.
(2) Site #1 and Site #2 must be able to read each other's cookies.
These requirements lead me to the following questions:
(1) Does the handler code located at sub.myDomain.com/handler.ashx need to
alter its response headers to allow CORS? I know that I can write a call
like this:
resp.Headers.Add("Access-Control-Allow-Origin","*");
…but from what I read, this will expose the handler to all domains. I just
want to limit the calls to those originating from *.myDomain.com. What if
I don't include the CORS header at all? What's the default behavior?
(2) Do Site #1 and/or Site #2 need to tweak the Domain property of
HttpCookie in order for the two sites to read each other's cookies?
What if I don't touch the Domain properties at all? What's the default
behavior? Some forum responses suggest that cookie scope will be limited
to the subdomain, while others suggest the entire domain is in scope
(which is what I want) in which case no action would be required on my
part.
Thanks.

Front end development: where to start?

Front end development: where to start?

I'm very sorry if that question has been asked already, couldn't find
anything closely related though.
By now I've pretty much learned HTML/HTML5, CSS/3, learned using JQuery
(not saying there's nowhere to improve, obviously there is). I really want
to start learning front-end dev (client MVC, etc). I've started learning
backbone.js, but it turns out i'm having difficulties learning it. Am I
missing something? I've read "JS: Good Parts" and Javascript Garden is
basically my go-to source yet I still get confused.
I'd appreciate any recommendations as to what I should learn/practice
first, thanks :)

Cannot call .authenticate method in has_secure_password

Cannot call .authenticate method in has_secure_password

Sessions controller:
class SessionsController < ApplicationController
def new
end
def create
user = User.find_by_email(params[:email])
if user && User.authenticate(params[:password])
session[:user_id] = user.id
redirect_to products_path, notice: 'Logged in successfully'
else
flash.now.alert = "Email or password is invalid"
render 'new'
end
end
def destroy
end
end
User model:
class User < ActiveRecord::Base
has_secure_password
attr_accessible :email, :password, :password_confirmation
validates_uniqueness_of :email
end
Log in form:
<h1>Login form</h1>
<%= form_tag sessions_path do %>
<%= label_tag :email %><br/>
<%= text_field_tag :email, params[:email] %><br/>
<%= label_tag :password %><br/>
<%= password_field_tag :password, params[:password] %><br/>
<%= submit_tag "Login" %>
<% end %>
When I try to use my login form a NoMethodError is raised stating that
authenticate is undefined.
I thought that the authenticate method was provided by putting
has_secure_password in the user model? Am I wrong here?
Any help appreciated!

Thursday, 22 August 2013

Oh-My-Zsh rails3 plugin aliases fail in rails 4

Oh-My-Zsh rails3 plugin aliases fail in rails 4

My rails version is 4.0.0. I'm using Oh-My-Zsh and I like it for it's hugh
plugin repository and intelligence. However, I've activated the rails3
plugin which is supposed to give me aliases mentioned in this oh-my-zsh
wiki. I have tried several of them like rg, rgbm, rgbm, rs but all of them
shows this error:
ruby: No such file or directory -- script/rails (LoadError)
Is this an incompatibility error of rails 4 environment and rails3 plugin
of oh-my-zsh? Is there a way to fix it? Thanks in advance.

Sticky Footer Creating Infinite Scrolling

Sticky Footer Creating Infinite Scrolling

Just what the title says! Feel free to have a look here at this WordPress
(Genesis) site we created a while back. The sticky footer plugin I created
(with some generous assistance from all you fine folk here) is working
well, but it keeps creating this weird infini-scroll effect.
Any idea what's happening here? I'm stumped, though I suspect there's
something in the jQuery I'm not knowledgeable enough about to fix.
Thanks for any assistance you can offer!
http://kangabloo.com/aboutus/

ddf standard xml format returns no records

ddf standard xml format returns no records

I am using the code below to query the CREA DDF/RETS to retrieve listings
in the XML format. When I specify the Standard-XML format, I get no
records with no errors.
If I do not specify the format, PHRETS defaults to Compact-Decoded format
and records are returned.
code
require('phrets.php');
$rets = new phRETS;
$criteria = 'LastUpdated=2012-01-01';
$limit = 10;
$options = array('Limit' => $limit, 'Format' => 'Standard-XML'); # also
tried STANDARD-XML - wasn't sure if it was case sensitive
$search = $rets->SearchQuery('Property', 'Property', $criteria, $options);
$total_records = $rets->TotalRecordsFound();
$error_info = $rets->Error();
echo "error (code {$error_info['code']}): {$error_info['text']}\n";
echo $total_records." - total_records\n";
$rets->FreeResult($search);
$rets->Disconnect();
results
error (code ):
0 - total_records

Python (NumPy): Collections can only map rank 1 arrays

Python (NumPy): Collections can only map rank 1 arrays

I'm running into the following error and I'm not sure why...
>>> x = np.matrix([[1,2,3,4]])
>>> x
matrix([[1, 2, 3, 4]])
>>> pcolor(x)
<matplotlib.collections.PolyCollection object at 0x108bb1810>
>>> show()
Traceback (most recent call last):
File
"/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/artist.py",
line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File
"/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/figure.py",
line 1006, in draw
func(*args)
File
"/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/artist.py",
line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File
"/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/axes.py",
line 2086, in draw
a.draw(renderer)
File
"/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/artist.py",
line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File
"/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/collections.py",
line 755, in draw
return Collection.draw(self, renderer)
File
"/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/artist.py",
line 54, in draw_wrapper
draw(artist, renderer, *args, **kwargs)
File
"/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/collections.py",
line 244, in draw
self.update_scalarmappable()
File
"/usr/local/Cellar/python/2.7.5/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/matplotlib/collections.py",
line 609, in update_scalarmappable
raise ValueError('Collections can only map rank 1 arrays')
ValueError: Collections can only map rank 1 arrays

PEAR Install out of memory

PEAR Install out of memory

I am trying to install PEAR into WAMP on Windows Server 2008.
When I do:
V:\wamp\bin\php\php5.4.12>php go-pear.phar
I get:
PHP Fatal error: Allowed memory size of 262144 bytes exhausted (tried to
alloca
te 91 bytes) in Unknown on line 0
Fatal error: Allowed memory size of 262144 bytes exhausted (tried to
allocate 91
bytes) in Unknown on line 0
I have tried to solve the error via Googling but all I get is people
saying to increase PHP memory limit. This is not the problem.
I have two php.ini files, one in Apache one in PHP. I don't know why there
is two but regardless I have set the memory_limit in both to 4096MB, and I
still get the error.
How can this be fixed so I can install PEAR?

Wednesday, 21 August 2013

Sitecore ECM how to track the same user's activities in different target audiences

Sitecore ECM how to track the same user's activities in different target
audiences

We are using Sitecore 6.5, and the Email Campaign Manager 1.3.3 rev.130212
is installed.
Currently, when i add a Sitecore user, for example 'UserA' to multiple
target audiences, lets say 'TargetAudience_A' and 'TargeAudience_B', after
I send out these two target audiences, 'UserA' clicks the link in the
email which comes from 'TargetAudience_A', then the link will bring user
to the site, user visits several pages, Sitecore Analytics will be able to
track 'UserA' VisitPageCount and Value, and creates the corresponding
campaign of 'TargetAudience_A' with that data.
When the user open the email send from 'TargetAudience_B' and clicks the
link, visits the site, NO campaign is created for 'TargetAudience_B' in
the database, I can see all the data should use to create a new campaign
for 'TargeAudience_B' is used to update campaign of 'TargetAudience_A'.
All the link in the sent email has been modified by Sitecore, the
corresponding campaign id is added, which make the link looks like
this:'httP:xx.domain.com/?ec_camp=xxxx&ec_as=xxxx'.
Seems Sitecore just adds a Id to the url, but not create a campaign for
the 'TargeAudience_B' with that Id.
I use this sql query to check the visits data:
Select * From Visits join Automations on Visits.CampaignId =
Automations.CampaignId
Where Automations.data = '{EmailTemplateId}'
the data column on Automations table is the email template id of the
target audience.
Does any one know how to track one user's activities for multiple
campaigns, is that possible to do? Or is this something which needs to be
fix by Sitecore?
Any help will be much much appreciated.
Thanks

Porting cocos2d-x win32 application to android/ Cygwin generating .o & .a files

Porting cocos2d-x win32 application to android/ Cygwin generating .o & .a
files

So, I followed the tutorial to win32 app to android; change .mk file, ran
build_native.sh and I got this on cygwin:
NDK_ROOT = /cygdrive/D/adt-bundle-windows-x86_64-20130219/android-ndk-r8
COCOS2DX_ROOT = /cygdrive/e/cocos2d-2.1rc0-x-2.1.3/die/proj.android/../..
APP_ROOT = /cygdrive/e/cocos2d-2.1rc0-x-2.1.3/die/proj.android/..
APP_ANDROID_ROOT = /cygdrive/e/cocos2d-2.1rc0-x-2.1.3/die/proj.android
Using prebuilt externals
make: Entering directory
`/cygdrive/e/cocos2d-2.1rc0-x-2.1.3/die/proj.android'
/cygdrive/D/adt-bundle-windows-x86_64-20130219/android-ndk-r8/build/core/add-application.mk:128:
Android NDK: WARNING: APP_PLATFORM android-14 is larger than
android:minSdkVersion 8 in ./AndroidManifest.xml
Compile++ thumb : game_shared <= main.cpp
Compile++ thumb : game_shared <= AppDelegate.cpp
In file included from jni/../../Classes/LevelManager.h:4:0,
from jni/../../Classes/OpenWindow.h:5,
from jni/../../Classes/AppDelegate.cpp:6:
jni/../../Classes/Level.h:16:8: warning: extra tokens at end of

When are TTBR0 and TTBR1 used together in ARM

When are TTBR0 and TTBR1 used together in ARM

What is the use of TTBR1. I cant find an example to illustrate its use.
Moreover what is the use case where TTBR1 and TTBR0 are used together.
Can someone please add some points
thanks

Blender points moving each other

Blender points moving each other

I am making a model of a boat in Blender. However, whenever I try to move
just one point, all of the points near it are moving too. What setting do
I need to change to fix this?

Passing system properties that contains spaces to Tomcat through JAVA_OPTS

Passing system properties that contains spaces to Tomcat through JAVA_OPTS

I need to pass multiple system properties to Tomcat 6 through the
JAVA_OPTS environment variable. I can't seem to pass system properties
that contain spaces:
JRE_HOME=/root/jre1.6.0_34/ JAVA_OPTS="-DsysProp1=foo -DsysProp2=bar with
spaces" ./catalina.sh run
Fails with:
Using CATALINA_BASE: /root/apache-tomcat-6.0.37
Using CATALINA_HOME: /root/apache-tomcat-6.0.37
Using CATALINA_TMPDIR: /root/apache-tomcat-6.0.37/temp
Using JRE_HOME: /root/jre1.6.0_34/
Using CLASSPATH: /root/apache-tomcat-6.0.37/bin/bootstrap.jar
Exception in thread "main" java.lang.NoClassDefFoundError: with
Caused by: java.lang.ClassNotFoundException: with
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
Could not find the main class: with. Program will exit.
I looked around on SO and the answers don't seem to help. Tried all of
these with no success:
JRE_HOME=/root/jre1.6.0_34/ JAVA_OPTS="-DsysProp1=foo -DsysProp2=\"bar
with spaces\"" ./catalina.sh run
JRE_HOME=/root/jre1.6.0_34/ JAVA_OPTS='-DsysProp1=foo -DsysProp2="bar with
spaces"' ./catalina.sh run
JRE_HOME=/root/jre1.6.0_34/ JAVA_OPTS='-DsysProp1=foo -DsysProp2=bar\
with\ spaces' ./catalina.sh run

Adjective displaced applied to an object

Adjective displaced applied to an object

Can I apply the adjective displaced to an object, when I mean it is being
used out of its typical environment?
For instance: the displaced ball floats around. (Assuming we're talking
about a ball used in a football match played on the moon. Typical usage
would be on earth, with gravity.)

Tuesday, 20 August 2013

Viewpager with fragments And Another Fragmnet replace

Viewpager with fragments And Another Fragmnet replace

viewpager with multiple fragment in activity,but i hope switch another
simple fragment replace this viewpager, how do I replace it, I usually
switch fragments, I don't known how to switch a fragment and a viewpager
with fragments. if someone have solve method , please tell me or give me
some hint ,thank you.

IMDB API to search based on country of origin

IMDB API to search based on country of origin

As mentioned on the title, is there such API from IMDB that allows
developer to search a certain movie title / person based on the country of
origin.
For example:
I want to query the person John Doe, but only if he/she is German. Or if,
i want to search the title Snickers but only if such movie is German
movie.
I know there are several API that fetch data from IMDB such as:
[1]: http://www.imdb.com/xml/find?json=1&nr=1&tt=on&q=transformer
[2]: http://developer.rottentomatoes.com/docs
[3]: http://api.themoviedb.org/2.1/
Unfortunately, none of them provide options to search based on country of
origin.
Does anyone know any reliable data source which provide this option? Thx.

PHP regex to find value of Apache Tile attribute

PHP regex to find value of Apache Tile attribute

I want to use PHP to search a directory of files (views.xml files) and
pull out values from any attributes named "window_title_key".
The attributes look like this:
<put-attribute name="content" value="/WEB-INF/views/login/content.vm"
type="velocity" />
<put-attribute name="window_title_key" value="window_title_login_page"
type="string"/>
For each file, I want to ignore all lines except those that start with
<put-attribute name="window_title_key".
Then, on those lines, I want to extract the value of that attribute. In
this example, the value would be window_title_login_page.
I want the result to be an array of all of the values of all
window_title_key attributes.
What is the regex pattern I should use?
It should be flexible enough to allow for variable whitespace.

Can't find action bar (Sherlock) inside root view

Can't find action bar (Sherlock) inside root view

I'm trying to find my activity's Action Bar's spinner so I can selectively
show and hide it (setNavigationMode does not work for my purposes). I
tried this code, but the Action Bar doesn't appear to be in my activity's
(which is an extension of SherlockFragmentActivity) root view.
private View findActionBarSpinner() {
View rootView = findViewById(android.R.id.content).getRootView();
List<View> spinners = traverseViewChildren( (ViewGroup) rootView );
return findListNavigationSpinner(spinners); // implement according to
your layouts
}
All I get for rootView is a FrameLayout containing the RelativeLayout
defined in my layout file (with only the elements within). I don't see
anything that looks like an Action Bar or a spinner, and and sure enough
traverseViewChildren (in the link above) returns an empty list.
I also tried, in the spirit of this answer, View rootView =
getWindow().getDecorView().findViewById(android.R.id.content).getRootView();.
The result was the same.
I'm making the call to findActionBarSpinner inside onOptionsItemSelected.
(Though I can't access it, the action bar is fully visible and working
properly at this point, so I doubt it's an issue of trying to access it at
the wrong part of lifecycle.)
Any ideas?

Run Automator App conditionally at system startup

Run Automator App conditionally at system startup

i have build an Automator app working every time at system startup. But
sometime i wish to do not run it. There is a way to avoid (like holding a
key at boot for example) Automator App runs when it do not need?

Decorating the ng-click directive in AngularJs

Decorating the ng-click directive in AngularJs

I've been looking into modifying the AngularJS ng-click directive to add
some additional features. I have a few different ideas of what to use it
for, but a simple one is to add Google Analytics tracking to all
ng-clicks, another is to prevent double clicking.
To do this my first thought was to use a decorator. So something like this:
app.config(['$provide', function($provide) {
$provide.decorator('ngClickDirective', ['$delegate', function($delegate) {
// Trigger Google Analytics tracking here
return $delegate;
}]);
}]);
But this won't work as decorators are fired on instantiation, not when the
expression in the directive is met. So in this case it would do the
analytics when an element with the directive loads, not when the element
is clicked.
So on to the real question. Is there some way for a decorator to get at
the element that the directive is instantiated on? If I could, from the
delegate, get to the element I could bind my own click event on it to
trigger in addition to the ng-click.
If not, how would you go about adding something on all ng-clicks?

C# - How to Doublebuffer Controls via Bufferimage?

C# - How to Doublebuffer Controls via Bufferimage?

I've read lots of attempts to double buffer C# Controls. But they just
don't work. I'm trying to do that with a TextBox. The background is
erased, the text drawn and the flickering is visible. So I thought the
only true way of doublebuffering is to use an off-screen image. I can't
paint everything by myself so I need to make my Control / TextBox paint
itself to the image ? How do I do that ? All I have is a hdc from the
image and I have somehow to smuggle it in a PAINTSTRUCT or PaintEventArgs
right ?
// protected override void WndProc(ref Message m)
// protected override void OnPaint(PaintEventArgs e)
// ...


These double buffering techniques were NOT working:
setting DoubeBuffered via reflection
SendMessage with WM_SETREDRAW
SuspendLayout / ResumeLayout
Anyways I would like to know how to double buffer in C# with an image. And
maybe someone else needs to use this technique as well.

Monday, 19 August 2013

Diameter protocol CCR request not routable

Diameter protocol CCR request not routable

I am using the jdiameter stack from http://i1.dk/JavaDiameter/ for my
diameter implementation. The initial CER request goes through fine but on
sending a CCR request i get a error as "not routable". Can anyone help me
out with this?. Also I am looking to build a Diameter call charging client
and have gone through mobicents, but am unable to get started on the same
due to lack of basic tutorials as to how to go about it. P.S. there is
already a similar question posted some time back but that failed to
resolve my query.

Draw a dashed and dotted bezier curve in QML

Draw a dashed and dotted bezier curve in QML

I've seen there is an example implementation of Bezier curvein QML, but
I'm looking for a hint how to implement dashed or dotted bezier curve
line. As far as I see, tha authors of Bezier curve example are using
QSGGeometryNode to store inside QSGGeometry with a QSGFlatColorMaterial
material applied on it. Then they simply create list of points and draw
segments between them.
Is it possible to store more than one QSGGeometry inside QSGGeometryNode?
(to be able to draw each "dashed" segment separately, or is there a
possibility to write a shader, which will be applied to
QSGFlatColorMaterial and will render this line as dashed?
Any hint would be highly appreciated! :)

Search for string and convert it to date

Search for string and convert it to date

Hello i have in one table string which looks like this xxxxxxxxx
day.month.year xxxxxxxxx. For date format is not used DD.MM.YYYY but is
used also D.M.YYYY, depends hov many numbers date has. Question is how to
search for string: left max 2 characters before first . then search for
cahracters between . and . and then search for 4 characters after second .
This will by numbers for day, month and year. When this values will be
know then those numbers convert to date. example: text 1.1.2013 text -
find particular numbers and create from this date. I have no possibility
to create separate column with date.
Any suggestion will be mostly welcome

Adding multiple Loopback Alsa devices in ubuntu

Adding multiple Loopback Alsa devices in ubuntu

I need to create virtual loopback alsa sinks in my ubuntu setup. I can
create one by adding the following to /etc/modprobe.d/sound.conf
alias snd-card-0 snd-aloop
options snd-aloop index=21 pcm_substreams=40
I need to create multiple of these but I can't seem to find documentation
on how to distinguish between the virtual cards. I would like to create
20.

WPF Login GUI for MySql Server

WPF Login GUI for MySql Server

Hi all I'm new to the C# world & visual studio 2012.....i've created a
database in MySql & have created several users with different permissions
to the only database on the server. I want to create a login GUI with WPF
which will allow any of the users i've created in MySql server to login.
Is this possible without writing the connection string with all the
usernames and passwords in the code? Any help will be appreciated.

Socket does not accept connections

Socket does not accept connections

I have a server socket accepting client socket connections. Accept is in a
thread
socket creation
int ServerSocket::CreateSocket(int port)
{
listenfd = 0;
struct sockaddr_in serv_addr;
unsigned long iMode = 1;
listenfd = socket(AF_INET, SOCK_STREAM, 0);
memset(&serv_addr, '0', sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
serv_addr.sin_addr.s_addr = htonl(INADDR_ANY);
serv_addr.sin_port = htons(port);
ioctlsocket(listenfd, FIONBIO, &iMode);
if (bind(listenfd, (struct sockaddr*)&serv_addr, sizeof(serv_addr)) < 0)
{
return 0;
}
if (listen(listenfd, 20) < 0)
{
return 0;
}
return listenfd;
}
Socket Accept
void ServerSocket::AcceptClients_1(void * p)
{
struct sockaddr_in cli_addr;
// get a pointer to the ServerSocket object
ServerSocket * pThis = (ServerSocket *)p;
int iResult, cli_len;
cli_len = sizeof(cli_addr);
struct timeval tv = { 0, 1000 };
SOCKET s = pThis->GetSocket();
fd_set rfds;
FD_ZERO(&rfds);
FD_SET(s, &rfds);
while (!pThis->ShutDownRequested)
{
iResult = select(s+1, &rfds, (fd_set *) 0, (fd_set *) 0, &tv);
if(iResult > 0)
{
// never comes here
SOCKET sclient = accept(s, (struct sockaddr *)&cli_addr,
&cli_len);
}
else if (iResult == 0) /// timeout
{
continue;
}
// error comes here are going to accept 2nd time
DWORD dwError = GetLastError();
return;
}
}
The code comes on select(). Returns 0 the first time but second time
always returns -1 with error 10022. I don't understand why. Please help.

Sunday, 18 August 2013

Max recursion error depth exceeded, python(2.7.5)

Max recursion error depth exceeded, python(2.7.5)

So I am trying to find the least common multiple of the numbers 1 - 20.
For some reason my code exceeds the max recursion depth but I don't
understand why. I just don't see where it gets stuck in the while loop.
def checking(i,q,w,e):
q = q * w
while i < 20:
if q % i != 0:
w += 1.0
checking(1.0, 20.0, w, [])
if q % i == 0 and i < 19:
i += 1
if q % i == 0 and i == 19:
e.append(q)
break
checking(1.0, 20.0, 1.0, [])

Node JS, createServer, and the Event Loop

Node JS, createServer, and the Event Loop

Behind the scenes in node, how does the http module's createServer method
(and its callback) interact with the event loop? Is it possible to build
functionality similar to createServer on my own in userland, or would this
require a change to node's underlying system code?
That is, my general understanding of node's event loop is
Event loop ticks
Node looks for any callbacks to run
Node runs those callbacks
Event loops ticks again, process repeats ad-infinitum
What I'm still a little fuzzy on is how createServer fits into the event
loop. If I do something like this
var http = require('http');
// create an http server and handle with a simple hello world message
var server = http.createServer(function (request, response) {
//...
});
I'm telling node to run my callback whenever an HTTP request comes in.
That doesn't seem compatible with the event loop model I understand. It
seems like there's some non-userland and non-event loop that's listening
for HTTP requests, and then running my callback if one comes in.
Put another way — if I think about implementing my own version version of
createServer, I can't think of a way to do it since any callback I
schedule will run once. Does createServer just use setTimeout or
setInterval to constantly recheck for an incoming HTTP request? Or is
there something lower level, more efficient going on. I understand I don't
need to fully understand this to write efficient node code, but I'm
curious how the underlying system was implemented.
(I tried following along in the node source, but the going is slow since
I'm not familiar with the node module system, or the legacy assumptions
w/r/t to coding patterns deep in the system code)

How to distinguish responses by mime-type in Django class-based view?

How to distinguish responses by mime-type in Django class-based view?

In class based view I can define method for GET or for POST. Can I somehow
define special methods for different mime-types of responses?
Use case is - make AJAX site usable even if JS is turned off.

Everything Up to Date but really isn't github

Everything Up to Date but really isn't github

I git cloned a repo down to my local machine. I forked that repo to my
github account. I made changes in my local files in sublime I removed the
original repo's origin because I want to push to my now forked repo and
then continue to alter my local files
when I do git diff you see the files I altered when I do git remote -v I
successfully see my forked repo
when I do git push -u origin master I get Everything is up to date but it
isn't ...
and when I do git branch I am in my master branch.

ModalPopupExtender from Server Side Code in c#

ModalPopupExtender from Server Side Code in c#

I had a nightmare getting this going.
Adding the ModalPopupExtender to a form is easy, you drop it on and tell
it the two required controls parameters
PopupControlID="MyModalPanel" TargetControlID="ButtonToLoadIt" And it just
works fine, but is triggered by a client side click of the Target Control.
If you want to do some server side code behind??? how to do it ?

Parsing XML in Groovy with namespace and entities

Parsing XML in Groovy with namespace and entities

Parsing XML in Groovy should be a piece of cake, but I always run into
problems.
I would like to parse a string like this:
<html>
<p>
This&nbsp;is a <span>test</span> with <b>some</b> formattings.<br />
And this has a <ac:special>special</ac:special> formatting.
</p>
</html>
When I do it the standard way new XmlSlurper().parseText(body), the parser
complains about the &nbsp entity. My secret weapon in cases like this is
to use tagsoup:
def parser = new org.ccil.cowan.tagsoup.Parser()
def page = new XmlSlurper(parser).parseText(body)
But now the <ac:sepcial> tag will be closed immediatly by the parser - the
special text will not be inside this tag in the resulting dom. Even when I
disable the namespace-feature:
def parser = new org.ccil.cowan.tagsoup.Parser()
parser.setFeature(parser.namespacesFeature,false)
def page = new XmlSlurper(parser).parseText(body)
Another approach was to use the standard parser and to add a doctype like
this one:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
This seems to work for most of my files, but it takes ages for the parser
to fetch the dtd and process it.
Any good idea how to solve this?
PS: here is some sample code to play around with:
@Grab(group='org.ccil.cowan.tagsoup', module='tagsoup', version='0.9.7')
def processNode(node) {
def out = new StringBuilder("")
node.children.each {
if (it instanceof String) {
out << it
} else {
out << "<${it.name()}>${processNode(it)}</${it.name()}>"
}
}
return out.toString()
}
def body = """<html>
<p>
This&nbsp;is a <span>test</span> with <b>some</b> formattings.<br />
And this has a <ac:special>special</ac:special> formatting.
</p>
</html>"""
def parser = new org.ccil.cowan.tagsoup.Parser()
parser.setFeature(parser.namespacesFeature,false)
def page = new XmlSlurper(parser).parseText(body)
def out = new StringBuilder("")
page.childNodes().each {
out << processNode(it)
}
println out.toString()
""

Saturday, 17 August 2013

RESTful routing in Zend 1.x

RESTful routing in Zend 1.x

I am new to Zend Framework and am trying to implement a RESTful controller
in Zend and trying to write unit tests for my controller. I am following
the REST API available at:
https://github.com/codeinchaos/restful-zend-framework but for every kind
of test, PHPUnit always hits 404 (observable by asserting the response
codes - the one I expect and the one that PHPUnit receives), thus failing
the tests.
I have added all code in respective files as this REST API's readme
instructs:
• I have added a module specific for REST: /application/modules/api. • In
my application.ini, I have the following:
autoloaderNamespaces[] = "REST_"
rest.default = "xml"
rest.formats[] = "json"
rest.formats[] = "xml"
resources.frontController.plugins.ErrorHandler.class =
"Zend_Controller_Plugin_ErrorHandler"
resources.frontController.plugins.ErrorHandler.options.module = "default"
resources.frontController.plugins.ErrorHandler.options.controller = "error"
resources.frontController.plugins.ErrorHandler.options.action = "error"
resources.router.routes.rest.type = Zend_Rest_Route
• In my application/bootstrap.php:
public function _initREST()
{
$frontController = Zend_Controller_Front::getInstance();
// set custom request object
$frontController->setRequest(new REST_Request);
$frontController->setResponse(new REST_Response);
$frontController->addModuleDirectory(APPLICATION_PATH . '/modules');
// Add the REST route for the API module only
$restRoute = new Zend_Rest_Route($frontController, array(),
array('api'));
$frontController->getRouter()->addRoute('rest', $restRoute);
}
• In my /application/modules/api/Bootstrap.php:
public function _initREST()
{
$frontController = Zend_Controller_Front::getInstance();
// Register the RestHandler plugin
$frontController->registerPlugin(new
REST_Controller_Plugin_RestHandler($frontController));
// Add REST contextSwitch helper
$contextSwitch = new REST_Controller_Action_Helper_ContextSwitch();
Zend_Controller_Action_HelperBroker::addHelper($contextSwitch);
// Add restContexts helper
$restContexts = new REST_Controller_Action_Helper_RestContexts();
Zend_Controller_Action_HelperBroker::addHelper($restContexts);
}
• Out of my own experiments, I have also added a line
$autoloader->registerNamespace('REST_') to my /public/index.php where
$autoloader refers to an instance of Zend_Loader_Autoloader.
• My test's location:
/tests/application/modules/api/controllers/RestClassTest.php • This is my
one of my tests for getAction():
public function testGetAction()
{
$this->request->setMethod('GET');
// Have tried other variations of URI too but all bear same result
(getting 404) in tests indicating that routing is not set at the
fundamental level.
$this->dispatch('/api/learn-to-rest?id=51fc287fc55ffc4006410bca');
$body = $this->getResponse()->getBody();
$json = json_decode($body, true);
$this->assertEquals('John Doe', $json['name']);
$httpResponse = $this->getResponse()->getHttpResponseCode();
$this->assertEquals(200, $httpResponse);
}
• And this is my getAction():
public function getAction()
{
$request = $this->getRequest();
$objectId = $request->getParam('id');
// Validation for ID
$this->_validateMongoObjectIdAction($objectId);
// Perform DB record selection
$records = new Db_Collection_Class(new Db_Mongo_Class);
$result = $records->findInCollection(array('_id' => new
MongoId($objectId)));
if ($result === null) {
// Source: http://www.w3.org/Protocols/HTTP/HTRESP.html
$this->getResponse()->setHttpResponseCode(404);
}
// Dispatch records in JSON format
$this->_helper->json($result);
}
It is true that I am setting a 404 for no-result-found situation but
confining specifically at getAction, it is hitting 404 with test for a
recognized valid ID as well.
I checked numerous resources (including the example provided by this API
and Matthew O'Phinney's post:
http://www.mwop.net/blog/228-Building-RESTful-Services-with-Zend-Framework.html)
and all instruct to follow the same things that I am already doing. It is
evident that I am missing something they are telling or am not
comprehending some factor. I'll be obliged if anyone guides me where I'm
doing what wrong.
Thanks in advance.