Monday, 30 September 2013

Intersection of compact sets in the unit interval – mathoverflow.net

Intersection of compact sets in the unit interval – mathoverflow.net

Let $\mathscr K$ be an uncountable set such that every $K\in\mathscr K$ is
a compact subset of $[0,1]$ with positive Lebesgue measure. Does it then
follow that there exists an uncountable $\mathscr …

sudo visudo question

sudo visudo question

I am attempting to add the entry to 'visudo:
admin ALL=(ALL) /bin/kill
I have attempted to make changes to this in the past but crashed the
visudo file. Can someone assist in telling me where exactly the command
above should be placed?

Firefox retina support for background images (mediaqueries)

Firefox retina support for background images (mediaqueries)

I developped several websites using mediaqueries for making them retina
ready. On firefox I now see that all background images (managed by
mediaqueries) are blurry, not retina ready.
Is this normal? Why firefox does not support the mediaqueries for
pixel-ration yet?
Ex:
@media only screen and (-webkit-min-device-pixel-ratio: 2),
only screen and (min-device-pixel-ratio: 2) { ... }
Thanks for your help.

Sunday, 29 September 2013

Why IntelliJ builds Android APK that is incompatible with x86 architecture

Why IntelliJ builds Android APK that is incompatible with x86 architecture

Further to this post INSTALL_FAILED_CPU_ABI_INCOMPATIBLE on device using
intellij my IntelliJ 12.1.4 builds an Android APK that is incompatible
with the Samsung Galaxy Tab 3 10.1 as the CPU architecture for that device
is x86 rather than ARM.
I successfully got a build running by building on the command line (ant
clean debug) and installing the resulting APK via adb.
I'm trying to understand why IntelliJ is building an incompatible APK. I
searched the bug tracker and couldn't find an existing bug so I'm also
wondering how many people are also having this issue.

Inheritance in CSS properties

Inheritance in CSS properties

Here, In this example I have two divisions where one is nested within
another. I'm calling the outer division a parent and the division which is
nested a child.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Untilted</title>
<style type="text/css">
/* for parent div tag*/
#parent{
width: 500px;
height: 300px;
z-index: 1;
background-color: #CCC;
border:thin solid black;
margin:25px;
padding:20px;
}
/* for child div tag */
#child{
border:thin solid #F00;
height:50px;
background-color:#FFC;
}
</style>
</head>
<body>
<!-- Start of parent tag -->
<div id="parent">
<p> This is parent div tag. </p>
<!-- Child div tag -->
<div class="box">
<p> This is child div tag. </p>
</div>
<!-- End of parent tag. -->
</div>
</body>
</html>
It looks like this in the web browser:

My question is: How does the child div tag gets it's the size of it's
width? Is it because of inheritance from the parent div tag or is it just
by default behavior that it will expand up to the parent div container if
you don't specify a width?

How to import an XEN disk.raw VM into OracleVM

How to import an XEN disk.raw VM into OracleVM

I have two virtual machines running on an OpenSuse 12.3 Linux with XEN.
These VMs has disk.raw files with Linux running inside them. I'm trying to
use Oracle VM and want to get the two XEN disk.raw files imported to
Oracle VM hypervisor with OracleVM Manager and I couldn't do it. Whem I
google about this I found that Oracle VM is based on XEN. But I can't find
how to put my XEN VMs into Oracle VM.
Anyone could help me?
Thanks.
IOSJRUS

Thread Pool Executor

Thread Pool Executor

I am working on changing legacy design with Thread Pool Executor. The
details are as follows:-
Legacy:- In case of legacy design 600 threads are created at the time of
application start up. and are placed in various pools, which are then
picked up when required and task is assigned to the corresponding thread.
New:- In new design i replaced the thread pool by executor service as
ThreadPoolExecutor thpool = new ThreadPoolExecutor(coreSize,poolsize,...);
What i am observing is that in case of Executor no threads are created at
the time of start up. They are created when request is fired from the
client. As a result of which threads created in memory are quite less as
compared to previous one.
But what my question is that is it right way because Thread creation is
also a overhead which is happening at the time of call is triggered.
Please tell which is more hevay process Thread creation at the time of
call from client or Idle threads being there in memory as per legacy
approach.
Also suggest which Executor pool to use in order to get best results in
terms of performance.
Thanks & Regards, Tushar

Saturday, 28 September 2013

Creating a "database" in rails

Creating a "database" in rails

I have a rails 4 application where users define for example a tools
database and creates fields that store items like brand, year, etc. Then a
CRUD interface is presented before them, based on the fields they defined.
Right now I have a Database model that looks like this:
class Database < ActiveRecord::Base
has_many :fields
and a Field Model that looks like this:
class Field < ActiveRecord::Base
belongs_to :database
Basically, right now on the Add Fields page (which is after you have a
created a database and defined the fields), I'm creating a unique id and
storing that with all the fields on that page, which I then use to group
fields into a "row" (using a rails groupby statement).
I have two questions: 1. Is the most efficient way to implement a
"database"? 2. I can't figure out how to best link the field names you
define when you create the database with the fields in the CRUD interface.
So for example, If I create a name field when I'm initially defining all
of the fields, how can I have it associated with fields in the CRUD
interface?
Thanks for all help! If I need to clarify more, please tell!

Normals inversion because of gluPerspercitve?

Normals inversion because of gluPerspercitve?

Just fooling around with opengl and glut. I was trying to make cube full
visibe so I decided that I could make it with gluPerspective(); So here's
the code
#include <iostream>
#include <GL/glut.h>
#include <GL/gl.h>
using namespace std;
float _angle = 0.1f;
void render(){
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluPerspective(90.0, 1, 0.1, 100.0);
gluLookAt(1, 1, 1, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0);
glPushMatrix();
glRotatef(_angle, 0.0f,0.0f,1.0f);
glColor3f(1.0f,0.0f,0.0f);
glutSolidCube (1.0);
glPopMatrix();
_angle +=0.03f;
// check OpenGL error
GLenum err;
while ((err = glGetError()) != GL_NO_ERROR) {
cerr << "OpenGL error: " << err << endl;
}
glutSwapBuffers();
glutPostRedisplay();
}
void init(){
glutInitDisplayMode(GLUT_DEPTH | GLUT_DOUBLE | GLUT_RGBA);
glutInitWindowPosition(100,100);
glutInitWindowSize(640, 480);
glutCreateWindow("test");
glClearColor(0.2,0.2,0.2,0.0);
glEnable(GL_COLOR_MATERIAL);
glEnable(GL_LIGHTING);
glEnable(GL_LIGHT0);
glutDisplayFunc(render);
glutMainLoop();
}
int main(int argc, char * argv[]) {
glutInit(&argc, argv);
init();
return 0;
}
and that is result:

how part of cube looks without gluPerspective():
How can I make it looks normal?

Direct link to app-store application in iOS 7

Direct link to app-store application in iOS 7

I have a free version of app. And there is a link to a full version in
free app. The link works fine in iOS 6. But in iOS 7 it shows a blank
page. Any help is appreciated!
The link I use:
- (void) getFull
{
[self hideAnimated];
NSString *iTunesLink =
@"http://phobos.apple.com/WebObjects/MZStore.woa/wa/viewSoftware?id=604760686&mt=8";
[[UIApplication sharedApplication] openURL:[NSURL
URLWithString:iTunesLink]];
}

What is wrong with this insertion sort using linked list code in c?

What is wrong with this insertion sort using linked list code in c?

I am getting error while executing this. Compiler does not give any error
but when executed it give random output. Any help ? What am i doing is
taking input from user & storing them to linked list & then implimenting
insertion sort.
#include<stdio.h>
#include<stdlib.h>
struct node
{
int info;
struct node *next;
};
typedef struct node *NODEPTR;
NODEPTR getnode();
NODEPTR insertionSortLinkedList(NODEPTR head);
int main()
{
int i,n,temp;
NODEPTR head,lptr,prevlptr;
printf("No of input integers to be sorted\n");
scanf("%d",&n);
if (n<2){printf("n should be atleast 2 \n");return 0;}
printf("\nType space-separated array of %d integers\n",n);
scanf("%d",&temp);
head=getnode();
head->info=temp;
head->next=NULL;
prevlptr=head;
for (i=0;i<n-1;i++)
{
scanf("%d",&temp);
lptr=getnode();
lptr->info=temp;
prevlptr->next=lptr;
lptr->next=NULL;
prevlptr=lptr;
}
head=insertionSortLinkedList(head);
lptr=head;
while(lptr!=NULL)
{
printf("%d ",lptr->info);
prevlptr=lptr;
lptr=lptr->next;
free(prevlptr);
}
return 0;
}
NODEPTR getnode()
{
NODEPTR p;
p=(struct node*)malloc(sizeof(struct node));
return p;
}
NODEPTR insertionSort(NODEPTR head)
{
NODEPTR listptr,tempptr,prevptr,prevtempptr;
prevptr=head;
listptr=prevptr->next;
while(listptr!=NULL)
{
while (listptr->info < prevptr->info)
{
prevptr->next=listptr->next;
tempptr=head;
prevtempptr=head;
while(tempptr->info <= listptr->info)
{
prevtempptr=tempptr;
tempptr=tempptr->next;
}
if(tempptr->info == prevtempptr->info)
{
listptr->next=head;
head=listptr;
}
else
{e
listptr->next=prevtempptr->next;
prevtempptr->next=listptr;
}
listptr=prevptr->next;
if (listptr==NULL)
break;
}
prevptr=prevptr->next;
if (prevptr=NULL)
break;
listptr=prevptr->next;
}
return(head);
}

Friday, 27 September 2013

C# Parking Fee Program [on hold]

C# Parking Fee Program [on hold]

I have to write a program for my Comp Prog I class. Below is the
assignment and the code I have written so far. Any help would be
appreciated. It runs but I am having trouble determining the best way to
do the calculations. I am attempting to get the long term portion
completed and then I was going to attempt to apply that to the short term
solution as well.
The Greater Providence Airport asks you to design a C# console application
program to calculate parking charge for their customers. The program can
be used to calculate either long-term parking or short-term parking. The
charge is calculated according the following rules:
Long-term Parking:
Input : Total number of hours (an integer)
The minimum charge is one full day (24 hours) $4.50 Any additional full
day (24 hours) is $4.00 each day If the last day's parking is less than 24
hours, the charge is prorated according to the number of hours parked,
i.e., if only 4 hours are parked, the charge is $4.00 * (4/ 24)
If you are a Greater Providence Airport employee, you get 75% discount.
Short-term Parking:
Input : Total number of minutes (an integer)
For each 24-hour period: The first ½ hour: $1.50 The next three ½ hour:
$1.25 each ½ hour Each ½ hour afterward $0.75 each
A fraction of ½ hour is counted as a whole ½ hour.
For each 24-hour period, the maximum charge is $12.00. That is if the
total amount exceeds $12.00, only $12.00 will be charged.
If you are a Greater Providence Airport employee, you pay only $1.25 for
each time you park at Short-term parking as long as the duration is no
more than 24 hours. Otherwise the charge will repeat for each 24-hour
period.
Output: Receipt should be nicely designed. For example:
Greater Providence Airport Parking Charge Short-term Parking: 148 minutes
Total Charge: $6.00 or Greater Providence Airport Parking Charge Long-term
Parking: 68 hours Total Charge: $11.83 Employee Discount: $ 8.87 Actual
Charge: $ 2.96
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace parking
{
class Program
{
static void Main(string[] args)
{
double minCharge = 4.50;
int hours = 0;
int id = 0;
double discount = 4.50*.75;
double calculateCharge;
Console.WriteLine("Enter hours parked:");
hours = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("Are you an Employee? Enter 1 for yes and 0
for no:");
id = Convert.ToInt32(Console.ReadLine());
if (hours <= 24)
{
calculateCharge = minCharge;
Console.WriteLine("The cost is {0}",
Convert.ToDecimal(calculateCharge));
}
if (hours <= 24 && id >= 1)
{
calculateCharge = (minCharge-discount);
Console.WriteLine("The cost is {0}",
Convert.ToDecimal(calculateCharge));
}
if(hours >24) {
calculateCharge = (((hours%24)/24)*4);
Console.WriteLine("The cost is {0}", calculateCharge);
}
if (hours > 24 && id >=1)
{
calculateCharge = (((minCharge+hours % 24) / 24) * 4)-0.75;
Console.WriteLine("The cost is {0}", calculateCharge);
}
Console.ReadKey(true);
}
}
}

How do I make a HTML form using and ?

How do I make a HTML form using and ?

I have made a form in HTML using a table and that worked fine, however, my
teacher told me that making forms from tables is not the proper way to do
it anymore, instead I should use:
<form>
<label></label>
<input>
</form>
but he also mentioned something about using <span></span> and I'll guess
it is just about this point where I got a bit confused, because where
should I use it - ie. should I put the <label> and the <input> in between
<span></span> ?
A few of the reason I ask is:
I don't consider myself very savvy when it comes to HTML
I would just have used a <div></div> to wrap around the <label> and the
<input> and then use css to put it where I want it to appear on the
webpage.
Regarding the form I want to create then I want it to look like this:
[Firstname] [lastname]
[textfield] [textfield]
[Street] [zip-code] [city]
[textfield] [textfield] [textfield]
[E-mail] [Phone]
[textfield] [textfield]
[message]
[textarea]
I hope the layout of my form makes sense to the majority of you !

Changing eventClick to occur on right click in jquery FullCalendar plugin

Changing eventClick to occur on right click in jquery FullCalendar plugin

is it possible for the eventClick to happen on a right click?
I don't know of ways in which I can do this.
thanks for your help

Cachemanager replication with ehcache on manager level or cache level

Cachemanager replication with ehcache on manager level or cache level

I am working on ehcache replication to share chache in a clustered JBoss
environment. We use Cache manager singletopn object to create dynamic
caches. Here is my problem. If i create a cache using cache manager, is it
expected to be replicated where I can just query for the cache in other
node(where it is not created). I am able to access the caches when I
create them with same names on all other nodes. e.g. If I create caches
with same name in other nodes I am able to see replication.
Does ehcache provide manager level replication ?
Here is my spring configuration for manager
<cacheManagerPeerProviderFactory
class="net.sf.ehcache.distribution.RMICacheManagerPeerProviderFactory"
properties="peerDiscovery=automatic, multicastGroupAddress=230.0.0.1,
multicastGroupPort=4446, timeToLive=32" />
<cacheManagerPeerListenerFactory
class="net.sf.ehcache.distribution.RMICacheManagerPeerListenerFactory"
properties="port=40001, socketTimeoutMillis=2000" />
Any help is much appreciated.

how to insert new div generated by javascript into existing one?

how to insert new div generated by javascript into existing one?

JAVASCRIPT
for (var i = 0; i < surveyResults.resultsOfSurvey.length; i = i + 1) {
debugger;
var answer =
surveyResults.resultsOfSurvey[i].correct;
var qId = surveyResults.resultsOfSurvey[i].id;
var newElement = document.createElement('div');
newElement.id = surveyResults[i];
newElement.className = "answer";
newElement.innerHTML = "Antwort ist: " + answer +
"! Fragen ID ist: " + qId + ".";
document.body.appendChild(newElement);
}
HTML
<div id="contentForSurvey">
<div id="answers"></div>
how to insert div from LOOP into div id="answers"????

How to run an php application without installing xampp on client system?

How to run an php application without installing xampp on client system?

In my application i have to deploy my application on client system. So is
there any way to run my php application without installing xampp...
Because the client should access it as a readymade app without installing
anything...

Breaking id statement PHP

Breaking id statement PHP

I need to break an if statement somehow. Here is the code
public function userData($data) {
//checks if user is in the database
if (self::checkUserExist($data)==false) {
$userInfo = array();
$userInfo['id'] = (isset($data->id)) ? $data->id : break;
$userInfo['email'] = (isset($data->email)) ? $data->email : break;
$this->conn->insert($userInfo, $Table); // inserts data!
}
}
The break doesn't work here. I need to return some kind of error. I could
say that the input data is invalid or something, the main point for this
is to avoid data insertion in database if the data is invalid.

Thursday, 26 September 2013

Php Regular expression to find question mark in an array

Php Regular expression to find question mark in an array

I want to check whether the array value contains '?' or not. If yes, then
the character succeeding question mark has to be extracted. Thank you.

Wednesday, 25 September 2013

what are the image sizes of an app for all Android devices

what are the image sizes of an app for all Android devices

I did a lot search but I didn't get any answer. I am new to android and
now I am confused with the background images and splash screen size, I
want my app run perfectly on all android device such as from small handset
to larger tablet. and I am also confuse with the buttons images. please
help me thank I will wait for your kind reply.

Thursday, 19 September 2013

Why doesn't PostgreSQL give a warning when calling a volatile function from a stable function?

Why doesn't PostgreSQL give a warning when calling a volatile function
from a stable function?

For example:
CREATE TABLE x (
val double);
CREATE FUNCTION g() RETURNS boolean AS $$
INSERT INTO x SELECT rand() RETURNING val>0.5;
$$ LANGUAGE SQL VOLATILE;
CREATE FUNCTION f() RETURNS boolean AS $$
SELECT g(); -- this is where the stability-violation happens
$$ LANGUAGE SQL STABLE; -- this is a lie
According to the documentation, f() should be marked VOLATILE also, since
calling f() produces side effects. PostgreSQL does not give a warning (or
better yet, an error), this leads me to believe there must be some reason
why this "obvious" mistake is allowed to exist.

Multi-terminal terminal apps?

Multi-terminal terminal apps?

Are there any terminal-based apps that support using multiple terminals in
the same way that an app like Photoshop supports using multiple windows,
with each window or terminal housing a different section of the app's UI?
Alternatively, are there any apps that can add some kind of remote-control
or multi-terminal-coordination functionality to existing terminal apps, or
shell sessions??

Java do/while loop offsetting first two questions

Java do/while loop offsetting first two questions

I am writing a program in my programming class in java. The program is a
simple do/while loop that asks some questions using scanner class and a
priming read with a Boolean value. When the loop iterates the first time,
it works properly, but when it iterates a second time, it displays the
first question and second question at once and only allows me to answer
the second. I hope this is clear. Anyone have any insight? Code:
/*
* Programmed By: Cristopher Ontiveros
* Date: 9/19/13
* Description: Compute weekly salary and witholding for employees
*/
package project.one.cristopher.ontiveros;
import java.util.Scanner;
public class ProjectOneCristopherOntiveros {
static Scanner sc = new Scanner(System.in);
public static void main(String[] args) {
String fName, lName;
double rate=0, wPay=0, withholding=0;
int option = 0;
boolean badval = true;
System.out.println("Welcome to the Pay Calculator");
do{
System.out.println("Enter employee first name: ");
fName = sc.nextLine();
System.out.println("Enter employee last name: ");
lName = sc.nextLine();
System.out.println("Enter employee hourly rate: ");
rate = sc.nextDouble();
wPay = (rate * 40);
withholding = (wPay * .20);
System.out.println("Employee " + fName + " " + lName + "\nHourly
Rate: " + rate + "\nWeekly Pay: " + wPay + "\nWithholding Amount:
" + withholding);
System.out.println("Would you like to enter another employee? (1
= yes, 2 = no)");
option = sc.nextInt();
if(option == 1){
badval = true;
} else {
badval = false;
}
}while(badval);
}
}

Can multiple smartimage xtypes appear on one dialog tab in AEM?

Can multiple smartimage xtypes appear on one dialog tab in AEM?

The out of the box (OOTB) page properties dialog in Adobe Experience
Manager (AEM) (CQ5) provides an Image tab. I would like to add a couple
more images to the dialog, but I don't want to create a separate tab for
each one.
For instance, is there a way to include an image on the "Advanced" tab
within a dialogfielset? I tried this, but it does not seem to render
properly.
One thing I am considering is to extend the slideshow xtype and each image
would be a separate "slide"
Are there better approaches?

jQuery Plug-in Backstretch not working

jQuery Plug-in Backstretch not working

I am trying this jQuery plug-in called Backstretch for full screen image.
I've followed as instructed on their website but it's not working. Nothing
is displayed.
I've first tried with local copies but it didn't work so I found CDN link
but it didn't work either.
Having them inside head tag or just before the end of body didn't make
difference.
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script
src="//cdnjs.cloudflare.com/ajax/libs/jquery-backstretch/2.0.4/jquery.backstretch.min.js"></script>
<script>
$.backstretch("http://dl.dropbox.com/u/515046/www/garfield-interior.jpg");
</script>
Does anyone have experience with this plug-in and have anything to share?

MySQL table structure for task manager app with task dependencies

MySQL table structure for task manager app with task dependencies

I need to design a 'task manager' table structure where task can be
dependent on other tasks. For example I can have following tasks:
TASK A: independent
TASK B: independent
TASK C: can not start before TASK B is finished
TASK D: independenet
TESK E: can not start before TASK C and TASK E are finished
Each task has standard properties (started_by, assigned_to, due_date,
description, status). I want to have a table structure that would allow me
to do this query easily:
Select all user's open tasks, but select only those who can already be
started (meaning in above scenario TASK C and E can not be selected here
until dependency tasks are completed).
Currently my solution is to have 2 tables:
tasks: table that hold tasks records
task_dependencies: table that holds task to task dependencies (id,
task_id, dependent_task_id)
My current query for above scenario and my current table structure goes
like this:
SELECT description, from_unixtime( date_due )
FROM tasks
WHERE
assigned_user_id = 751
AND status_id = 'Q'
AND id NOT
IN (
SELECT TD.task_id
FROM task_dependencies TD
INNER JOIN tasks T ON TD.dependent_task_id = T.id
AND T.status_id = 'Q')
ORDER BY date_due
-- status 'Q' = new uncompleted task
This get's me the right result, but is this the right way to go or should
I make better table structure and/or query?
Here is also SQL fiddle for above scenario.

Wednesday, 18 September 2013

not converting ÷ to � in some system with internet browsert

not converting ÷ to &#65533; in some system with internet browsert

we are using flash file to create questions and user input is pass into
our asp .net web page by calling external javascript method. example user
has entered the input string as "7 × 8 ÷ 9" and click on flash file submit
button the external javascript method is called and string is passed in to
webpage is as same as entered in flash file "7 × 8 ÷ 9". in most of all
system with all browser works fine, but one particular system in IE
browser returning string as "7 × 8 Õ 9" (Unicode UTF 8 format) other
browsers are working fine in this system .
Operating System: Windows 8 (The same OS installed in other system also
works fine) Internet Explorer: IE 10 (version 10.0.9200.16618) the some IE
version work in other system
Please suggest any specific system configuration required to work Unicode
UTF 8 format or required any Unicode font's to install for the system
Thank you in advance

Can I replace existing image in a same folder?

Can I replace existing image in a same folder?

I have developing a metro app, I have a page that save user selected
image. The thing is when I choose the image in the pictures folder error
will occur "Error HRESULT E_FAIL has been returned from a call to a COM
component" but if I choose from other folder it will proceed smoothly and
save the image name into the database. Here is the snippet:
if (file != null)
{
StorageFolder documentsFolder =
KnownFolders.PicturesLibrary;
output = await file.CopyAsync(documentsFolder,
file.Name.ToString(),
NameCollisionOption.ReplaceExisting);
}

Jquery 1.10.2 $.each function not working

Jquery 1.10.2 $.each function not working

Ok, first let me describe my HTML.
I have a select list name and ID as upload_Gcat that has three options. I
then have a select list name and ID as upload_album. What I want is as
upload_Gcat is changed upload_album changes its options according to what
was selected. I have gotten my query to work as far as removing the old.
But when it reaches my $.each function it does not work.
I have tried various different code lines inside the $.each function, even
tried the bad debug way of alerts, no alert showed up while inside of
$.each.
var new_options = new Array();
new_options["album1"] = "album1";
new_options["album2"] = "album2";
new_options["album3"] = "album3";
var select = $('upload_album');
if(select.prop){
var options = select.prop('options');
}
else{
var options = select.attr('options');
}
$('option', select).remove();
$.each(new_options, function(key, value) {
options[options.length] = new Option(value, value);
});

How would my code convert to fixstr?

How would my code convert to fixstr?

How would this piece of code change to fixstr? the code:
user.title = '".$db->sql_escape($db->sql_escape($id))."'
How I have it written is this way but it is not finished. The code:
user.title='" . fixstr($db->sql_escape($id)) ."'
fixstr:
function fixstr($str){
$str = trim($str);
$str = str_replace("'", "''", $str);
return $str;
}
How would this code be written correctly?

Wordpress: Displaying posts of category PHP error

Wordpress: Displaying posts of category PHP error

I'm working on a WordPress site and am trying to display posts of a
certain type through a page template. I have searched around and
technically the following code should work but doesn't... PHP must throw
an error, because it does not display any output from this code:
<?php
$args = array( 'post_type' => 'gazette',
'posts_per_page' => 10 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post();
echo '<div class="row-fluid newsPost">';
echo '<div class="span3">';
if ( has_post_thumbnail() ) {
the_post_thumbnail();
}
echo '</div>';
echo '<div class="span9">';
echo '<span class="newsTitle">';
the_title();
echo '</span>';
echo '<span class="newsDate">';
the_date();
echo '</span>';
echo '<em>';
the_excerpt();
echo '</em>';
echo '</div>';
echo '</div>';
endwhile;
?>
Anyone have any idea why this isn't working? The post_type correlates to
my custom post type "gazette" ...

visual c++ released code exe file screen broken

visual c++ released code exe file screen broken

I have got a problem when I make exe file of my c++ code via Visual studio
2008 trial version with SP1. When I run a debug my code with release mode
in VS2008, output is good. After that when i run the exe file which is
just made, output screen looks like broken so that cannot distinguish
which object is which one. I made code in win32 consol application
program, windows application program mode. One thing I guess why I face
this problem is cause of my VS2008 is trial version.
Please let me solve this problem.

Subplots with only ylabel

Subplots with only ylabel

I am plotting some MEG time-series stacked horizontally on top of each
other. Now I want no axis to be showing but I do want to print each
channel number on the left side. So far I've tried this:
figure;
for i=1:10
subplot(10,1,i)
plot(1:5000,PDdata{1,1}.data(:,i)) % data to be plotted
axis off
ylabel(sprintf('%d',i))
end
Giving me

Unfortunately the ylabel is suppressed by the axis off, how can I suppress
all axis options but the ylabel?

Im newbee in oracle and I try to add new column to existing type

Im newbee in oracle and I try to add new column to existing type

create or replace type employee FORCE as object
( id VARCHAR2(8), code NUMBER(11), date NUMBER(8) ) /
earlier it was
create or replace type employee FORCE as object
( id VARCHAR2(8), code NUMBER(11) ) /
Error report: ORA-22866: cannot replace a type with table dependents
22866. 00000 - "default character set is of varying width" *Cause: A
character LOB was defined but the default character set is not fixed
width. *Action: Ensure that the character set is of fixed width before
defining character LOBs.

Can't render a texture for WebGL plane

Can't render a texture for WebGL plane

I have already learned how can I add some objects in WebGL, rotate them.
But I have a problem with a texturing process.
The source code of my WebGL app: http://pastebin.com/dgpyMv0j
When I launch Chrome debugger, it gives me such an erros:
PS I've tried to search in web some info, but there isn't much information
for my issue, just few links.
[.WebGLRenderingContext]RENDER WARNING: texture bound to texture unit 0 is
not renderable. It maybe non-power-of-2 and have incompatible texture
filtering or is not 'texture complete' 192.168.1.179/plane/:1
50
WebGL: drawArrays: texture bound to texture unit 0 is not renderable. It
maybe non-power-of-2 and have incompatible texture filtering or is not
'texture complete'. Or the texture is Float or Half Float type with linear
filtering while OES_float_linear or OES_half_float_linear extension is not
enabled. 192.168.1.179/plane/:1
202
WebGL: drawArrays: texture bound to texture unit 0 is not renderable. It
maybe non-power-of-2 and have incompatible texture filtering or is not
'texture complete'. Or the texture is Float or Half Float type with linear
filtering while OES_float_linear or OES_half_float_linear extension is not
enabled. 192.168.1.179/plane/:244
WebGL: too many errors, no more errors will be reported to the console for
this context. 192.168.1.179/plane/:244

Tuesday, 17 September 2013

Why mtime of device files is not getting updated?

Why mtime of device files is not getting updated?

when I do a stat on input device files like /dev/input/event* I get mtime
of the file as the system boot. It should atleast get the key strokes and
update the file's mtime as the current time!!
Does anybody knows the reason why mtime of these input device files is not
getting updated?

Find a subset from a set of integer whose sum is closest to a value

Find a subset from a set of integer whose sum is closest to a value

As the title said, Find a subset from a set of integer whose sum is
closest to a value. The set is about 1000 items in it, the value is about
10 million, I have considered using the DP(Dynamic Programming) to solve
this problem, just as the "Bin Packing Problem", But this method is not
suitable, the set is too large and the value is too large.
What can i do, trying Heuristic Algorithm? But How and use Which?

Simple infinite while loop-- c

Simple infinite while loop-- c

I know I should debug this myself... but believe me I've tried and I'm
VERY embarrassed. I can't understand why my while loop is infinitely
looping. Can anyone help?
#include <stdio.h>
int main ( void )
{
double milesDriven;
double gallonsUsed;
double totalMilesDriven;
double totalGallonsUsed;
float milesPerGallon;
float totalMpG;
printf( "%s", " Enter the gallons used (-1 to end): " );
scanf( "%i", &gallonsUsed);
printf( " Enter the miles driven: " );
scanf( "%i", &milesDriven);
while ( gallonsUsed != -1 || milesDriven != -1)
{
totalGallonsUsed += gallonsUsed;
totalMilesDriven += milesDriven;
milesPerGallon = ( milesDriven / gallonsUsed );
printf( " The miles/gallon for this tank was %f\n", milesPerGallon );
printf( "%s", " Enter the gallons used (-1 to end): " );
scanf( "%i", &gallonsUsed);
printf( " Enter the miles driven: " );
scanf( "%i", &milesDriven);
}
totalMpG = ( totalMilesDriven / totalGallonsUsed );
printf( " The overall average miles/gallon was %.6f\n ", totalMpG);
return 0;
}

How do I make every file in a static dir have Content-Type ... using express?

How do I make every file in a static dir have Content-Type ... using express?

I have a dir that contains anywhere between zero and a few hundre files,
all without extension (generated in an unknowable nested dir structure by
another app, with the writing occurring somewhere in a library that I
can't, nor want, to modify code in), with all files containing html
content. I'd like to use express's convenient static call so I don't have
to worry about which files exist, but
app.use(express.static("..."))
does not let me say that all the content from this dir should be
Content-Type text/html. Is there a way to to serve up content from
anywhere in that dir (without knowing what's in it) with the response
header always saying the content is text/html?

segmentation fault for setting a variable equal to 0

segmentation fault for setting a variable equal to 0

I have a struct with two pointers and an int variable.For some reason i am
getting a segmentation fault if i keep the code ptr->i=0; if i take out
the statement ptr->i=0; i do not get a segmentation fault, why is that?
I'm pointing to something in the memory, i is not a pointer so it should
be legal. Can anyone please explain what is going on with this? ALSO I DID
CREATE MEMORY FOR THE STRUCT AND THE TWO CHAR POINTERS.
struct A_ {
char *a;
char *b;
int i;
};
typdef struct A_ StructA;
and then in my main() i have the following:
StructA *ptr;
ptr->i=0;

finding the length of scanf() without storing the result

finding the length of scanf() without storing the result

How would i go about finding the length of a scanf() where i am scanning
from a string up until a certain character WITHOUT actually storing it?
scanf(stringToBeTested, "%[upUntilThis]", StoreToThisString)
strlen(scanf(stringToBeTested, "%[upUntilThis]", StoreToThisString))
?

Sunday, 15 September 2013

Emai verification system testing PHP, CodeIgniter

Emai verification system testing PHP, CodeIgniter

I am currently building an online registry system and one of its modules
is the registration system.
After a user successfully register, a verification email is sent to
his/her email address. I followed every tutorial I read online and I'm
still getting the same problem.
here's what i got so far:
//this is what it looks like in my controller after validation of fields
from registration
$this->load->library('email');
$this->email->set_newline("\r\n");
$this->email->from('my_personal_email@gmail.com', 'Mike Lee');
$this->email->to($email);
$this->email->subject('Email Test');
$this->email->message('Testing the email class.');
if($this->email->send()){
//this is to check if email is sent
redirect('site/registered');
}else{
//else error
show_error($this->email->print_debugger());
}
for my configuration of email.php:
class CI_Email {
var $useragent = "CodeIgniter";
var $mailpath = "/usr/sbin/sendmail"; // Sendmail path
var $protocol = "smtp"; // mail/sendmail/smtp
var $smtp_host = "https://smtp.googlemail.com"; // SMTP
Server. Example: mail.earthlink.net
var $smtp_user = "my_personal_email@gmail.com"; // SMTP Username
var $smtp_pass = "my_personal_emailpassword"; // SMTP Password
var $smtp_port = "25"; // SMTP Port
var $smtp_timeout = 10; // SMTP Timeout in seconds
var $smtp_crypto = ""; // SMTP Encryption. Can be null, tls or ssl.
var $wordwrap = TRUE; // TRUE/FALSE Turns word-wrap on/off
var $wrapchars = "76"; // Number of characters to wrap at.
var $mailtype = "text"; // text/html Defines email formatting
var $charset = "utf-8"; // Default char set: iso-8859-1 or us-ascii
var $multipart = "mixed"; // "mixed" (in the body) or "related"
(separate)
var $alt_message = ''; // Alternative message for HTML emails
var $validate = FALSE; // TRUE/FALSE. Enables email validation
var $priority = "3"; // Default priority (1 - 5)
var $newline = "\n"; // Default newline. "\r\n" or "\n" (Use
"\r\n" to comply with RFC 822)
var $crlf = "\n"; // The RFC 2045 compliant CRLF for
quoted-printable is "\r\n". Apparently some servers,
// even on the receiving end think they
need to muck with CRLFs, so using "\n",
while
// distasteful, is the only thing that
seems to work for all environments.
var $send_multipart = TRUE; // TRUE/FALSE - Yahoo does not like
multipart alternative, so this is an override. Set to FALSE for Yahoo.
var $bcc_batch_mode = FALSE; // TRUE/FALSE Turns on/off Bcc batch feature
var $bcc_batch_size = 200; // If bcc_batch_mode = TRUE, sets max
number of Bccs in each batch
var $_safe_mode = FALSE;
var $_subject = "";
var $_body = "";
var $_finalbody = "";
var $_alt_boundary = "";
var $_atc_boundary = "";
var $_header_str = "";
var $_smtp_connect = "";
var $_encoding = "8bit";
var $_IP = FALSE;
var $_smtp_auth = FALSE;
var $_replyto_flag = FALSE;
var $_debug_msg = array();
var $_recipients = array();
var $_cc_array = array();
var $_bcc_array = array();
var $_headers = array();
var $_attach_name = array();
var $_attach_type = array();
var $_attach_disp = array();
var $_protocols = array('mail', 'sendmail', 'smtp');
var $_base_charsets = array('us-ascii', 'iso-2022-'); // 7-bit charsets
(excluding language suffix)
var $_bit_depths = array('7bit', '8bit');
var $_priorities = array('1 (Highest)', '2 (High)', '3 (Normal)', '4
(Low)', '5 (Lowest)');
here's the error:
/* A PHP Error was encountered
Severity: Warning
Message: fsockopen() [function.fsockopen]: unable to connect to
ssl://smtp.googlemail.com:25 (A connection attempt failed because the
connected party did not properly respond after a period of time, or
established connection failed because connected host has failed to
respond. )
Filename: libraries/Email.php
Line Number: 1689 */
i use my personal email acct to send test mail. but i don't know if that
will work with gmail. can you somehow enlighten me how i can test if my
code is working? or is there a software that can be used as my test server
to send mail?
thanks. :(

I'm Programming a Roguelike in Python and I need a Specific Monster Following Script

I'm Programming a Roguelike in Python and I need a Specific Monster
Following Script

I'm using libtcod and python to make a roguelike; the tutorial I'm
following the monsters only follow you if you're in their field of view.
Obviously this is insufficient; as it means you can turn a corner and they
don't follow you around the corner.
I tried something like this;
class BasicMonster:
def take_turn(self, seen):
self.seen = False
monster = self.owner
if lib.map_is_in_fov(fov_map, monster.x, monster.y):
self.seen == True
if self.seen == True:
self.move_towards(player.x, player.y)
To no avail. It returns that "TypeError: take_turn() takes exactly 2
arguments (1 given)". Not sure how to implement this.

How to organize code well in root class?

How to organize code well in root class?

So, I've been writing this software with C++ for some time. It has gui and
a gui has access to master class object, that object is responsible for
whatever task is made by the gui (when user clicks something, gui just
calls a method of that object).
Now, I don't know if this is the best way. I've never worked in any coding
company in my life, but I've came into some problems.
Actually, master class doesn't do anything. It's mostly a wrapper for
other objects located inside that class. So, for instance:
class Master {
public:
void writeSomethingToFile(const char *filename,std::string& text);
...
}
under the hood:
class Master {
...
private:
FileWriter *_writer;
}
void Master::writeSomethingToFile(const char *filename,std::string& text) {
_writer->write(filename,text);
}
So, the master class doesn't do the writing itself, it just throws the
task for writer class which should do the job.
The master class has a lot of objects like writer class, so, as far as gui
is concerned, master class is capable of ANYTHING it ever needs in
program.
However, code get's kind of clunky in master class, since it contains all
these wrapper methods it has VERY MANY METHODS.
Since it uses all these other classes, whenever I change any header of the
class master class uses the .cpp file has to be recompiled too (not too
bad for i7 processor, but I'd rather avoid it).
What now I've been using is very primitive, and by no means I defend this
way:
class Master {
public:
// FILE CHANNEL
void writeToFile(...);
void deleteFile(...);
// FILE CHANNEL
// ARITHMETIC CHANNEL
void addNumbers(...);
void multiplyNumbers(...);
// ARITHMETIC CHANNEL
...
}
I would literally, separate things I call "channels" with comments so I
could understand what belongs to what. Now, for gui, this may not be that
bad, since everything is grouped. However, when I go further developing
this class adding new inner classes to it and wrapping more methods, stuff
becomes clunky and what most bothers me, it's not rock solid. I mean, If I
would take one method from commented "channel" and put it in the other,
would I really see the difference?
I thought about couple of solutions. I've never tried it but I may create
memberspaces:
class Master {
public:
namespace file {
void writeToFile(...);
void deleteFile(...);
}
namespace arithmetic {
void addNumbers(...);
void multiplyNumbers(...);
}
...
}
This solves problem from my side, as a developer of a class, but, for gui
they now have to call methods like
master->arithmetic.addNumbers(...); // My syntax could be wrong here
// never used memberspace, corrections are appreciated
And now, as my project is 'kinda' swinging at the moment, that would mean
modifying A LOT OF CODE.
Another solution I thought about was constant inheritance from class to
class where master class in file focuses on one channel:
class Master_fileChannel {
FileHandler *_fileHandler;
void writeToFile(...);
void deleteFile(...);
}
...
class Master_arithmeticChannel : public Master_fileChannel {
ArithmeticUnit *_arithmeticUnit;
void addNumbers(...);
void multiplyNumbers(...);
}
and so on, until I inherit every "channel". This would be more solid than
the original state, and make files a lot shorter than current .cpp file
for this class. But, I would still have issue that I may use duplicate
method names and would have to make up more and more clunky names for my
methods (i.e. addNumbers(..); addThreadNumbers(..);
addThreadNumbersSeparately(..);
So, what would you suggest me to do here? I can build up that master class
to infinity, but I'm sure there's a better way. How these things are dealt
with in real decent sized code bases? Can I refactor code quickly across
all project to do these drastic changes without a sweat?

JQuery calculation after elements are shown

JQuery calculation after elements are shown

I have a form that I'm doing a few simple calculations on. I can't get the
calculation to run after I unhide the elements. I have proven that the
calculations work outside this form but I'm trying to add it to a form
that uses other libraries. I just can't figure out what I need to do to
get the calculation to bind to the id's after they are shown. Here's a
link to the a partial form with just the needed inputs to keep it simple.
testform If you click on "Yes" the elements show that I'm working with.
Thanks for any guidance. Here's the calculation script that I made.
<script>
function pottopot() {
if ($('#item78_number_1').val()>0 && $('#item76_number_1').val()>0){
totalpotgals = parseInt($('#item76_number_1').val(),10)
* parseInt($('#item78_number_1').val(),10)
/ parseInt($('#item47_number_1').val(),10);
$('#item48_number_1').val(totalpotgals.toFixed(2));
}
}
</script>

Css style in asp.net

Css style in asp.net

<style type="text/css">
.style1
{
border:2px solid #e53a6f;
box-shadow:0 0 5px 0 #e53a6f;
}
</style>
javascript
<script type="text/javascript" language="javascript">
if (Pname == "")
{
document.getElementById('<%=txtname.ClientID %>').style.border="2px
solid #e53a6f";
return false;
}
</script>
I am new to css. My question is I want to call style1 css instead of
calling .style.border="2px solid #e53a6f";in java script . Is this
possible?. Can some one help me out.

Jquery datable how to apply style

Jquery datable how to apply style

I have created a HTML table and applied the jquery daytatable to it. Is
there a way I can apply style to it. The search button comes exactly below
the display rows drop down. I want them to be placed side by side. Thanks

get minus the offset of current image

get minus the offset of current image

I'm working with a slider and the div is scrolling so its offset is having
negative value as it scrolls so I wanted to call a function when the
current image is hidden that is offset of the image is minus the current
image width so I tried the following but no luck to work....
$(window).load(function(){
var $curli = $('#navs .activenav');
var $curliclass = $curli.attr('class').split(' ')[0];
var $curlivalue = parseInt($curliclass.match(/\d+/), 10);
var $curimg = $('#banner').find('.img'+$curlivalue);
if($curimg.offset().left === -$curimg.width()){
alert('hi');
}
});

Saturday, 14 September 2013

How to suppress "unknown enum constant" warnings?

How to suppress "unknown enum constant" warnings?

The Checkers Framework references
java.lang.annotation.ElementType.TYPE_USE which was added in JDK8. When I
use it under JDK7, I get the following warning:
unknown enum constant java.lang.annotation.ElementType.TYPE_USE
This is a reasonable warning, but how do I suppress it for cases I believe
are harmless?

Binary Buffer Conversion

Binary Buffer Conversion

I am writing binary buffers which are byte aligned for network packets
that can read/write variant types. It must convert these to into an
internal unsigned char (byte) container (STL vector) and then when read
back it must reconstruct a variant type from so many bytes.
I have it partially working so far with the following code...
var test;
test = buffer_create(100, buffer_grow, 1);
show_message(string(buffer_tell(test)));
buffer_write(test, buffer_u32, 214748);
show_message(string(buffer_tell(test)));
buffer_seek(test, buffer_seek_start, 0);
show_message(string(buffer_read(test, buffer_u32)));
And the code that adds these functions in the engine...
http://pastebin.com/PqpCZVD3
Except the 214748 comes back out as 214528 :( Bye alignment is also not
the issue since it is completely ignored for right now, I am just trying
to test reading/writing an integer, string writing/reading already works.

redirect root url according to locale in Zend

redirect root url according to locale in Zend

Working in ZF: Is it possible to change the base or root url on the
www.example.com to www.example.com/$language/home, thus depending on the
(browser) locale of the users browser?
Example; If a guest manually types www.example.com I would like to change
the url automatically to a url with locale: www.example.com/en/home for
guests in en_GB region or www.example.fr/home for guests in fr_FR region.
From the root-url I have all the menu-urls and content locale aware.
Clicking a link to a menu item in the url the lang is automatically added
after the root. The content on the root url is locale aware too using
translate, so english for en_GB en french for fr_FR, etc.
Still missing though I would like to have the root url change to locale
aware right from the start of the visit to the application if only the
root is entered.
I guess something like root :to => redirect("/prepayments") in Rails 3
from what I understand from this Q&A on this forum
I have tried and implemented controller action helpers, redirects, etc.
etc. for as far as I could find on this forum, but they all don't offer
the solution.
A redirect in htaccess is not possible I think since I first need to get
the locale from the browser. Since I don't know this the redirect is
dynamic and I cannot set a redirect in htaccess.
I woud appreciate any suggestions?

How can I extract a long list of tarballs via STDIN?

How can I extract a long list of tarballs via STDIN?

I'm copying bunch of .tar backups of user home directories to a new server
and have the tarballs already copied from the old server to the new
server.
For Example;
[root@example.com /home]# ls /home |grep tar
returns:
user1.tar
user2.tar
user3.tar
[etc]
But making things a little trickier, the tarballs were created from the
root directory on the original server so a default extraction has 'home'
in the default path e.g.;
[root@example.com /home]# tar -xvf user1.tar
extracts to a new home directory relative to where your running the
command and places the extracted files at the path
/home/home/user1
The closest I believe I have come to what's required (with a few different
variations);
[root@example.com /]# ls /home |grep tar |tar -xvf -
returns;
tar: This does not look like a tar archive
tar: Exiting with failure status due to previous errors
Now I realize there's a lot of workarounds for each of the different
pieces, but if I'm going to grow up to be a super-cool sysadmin like my
friends, I should probably know super-cool tricks like this.
Thanks!

Best way to modify Excel files in C# for Windows Phone

Best way to modify Excel files in C# for Windows Phone

I`m looking for solution to modify excel files inside Windows Phone and
after that create a PDF from it:
Thats subject of my student project - Ive got personal expenses claim
(where employyes put their expenses) - thats excel file. I need to create
a WP8 app that can modify that excel file and after that create a pdf from
it.
Any suggestions ? I`m newbie in WP & Office integration - i dont know
maybe better idea is change file format from xls to some template files or
csv etc. ?

JavaScript Allow various functions to execute only if some condition is true

JavaScript Allow various functions to execute only if some condition is true

I have a list of event handlers that are attached to various elements, but
I want to disable some of them when a certain condition is true. This
condition (i.e. boolean value) changes dynamically and it is not
predictable when it changes. Here is what I do currently.
function foo () {
if (someCondition) {
return;
}
// foo does something
}
function bar () {
if (someCondition) {
return;
}
// bar does something
}
...etc
This is alright, but it's really redundant to have the if block in each
function. Is there a more concise way to manage this? I was wondering if I
can attach two event handlers to one element, and only execute one if the
other returned true.

Javascript match regex against group

Javascript match regex against group

Given the following string:
Lorem {{ipsum}} dolor {{sit}} amet
I'm trying to extract thw words ipsum and amet with the following regex:
content = 'Lorem {{ipsum}} dolor {{sit}} amet'
var regexp = /^\\\{\\\{(\w)\\\}\\\}/g;
var match = regexp .exec(content);
The match object returns null. What am I missing? Thanks!

How to execute the different set of xml nodes being detected by their respective Attribute values using c#

How to execute the different set of xml nodes being detected by their
respective Attribute values using c#

I would like to execute different set of xml nodes which are being
identified by their respective attributes values in xml. But what i am
facing is that only the set 1 xml nodes are getting executed even the
second attribute value is being identified.Here is my current code:
for (int m = 0; m < 10; m++)
{
attrVal_New =
Update_Bugs[m].Attributes["TestCondition"].Value;
//m++;
foreach (string attr in attrVal_New.Split(','))
{
//string[] vals =
XDocument.Load(FilePath_EXPRESS_API_BugAdd_CreateBugs_DataFile).Root.Element("Bugs").Attribute("TestCondition").Value.Split(',');
//Console.WriteLine(vals);
Console.WriteLine(attr);
string attributelowercase = attr.ToLower();
//Step1: Create Bugs
List<string> BugWSResponseList1 = new List<string>();
Logger.Write("\n\n" + DateTime.Now + " : " + " :
START : Creation of a set of Bugs via bug.Add
API");
BugWSResponseList1 =
CreateBugs(FilePath_EXPRESS_API_BugAdd_CreateBugs_DataFile,
newValue);
Please find the sample xml as follows:
<DrWatson>
<Bugs Name="Testing 11" TestCondition="STATE">
<Bug>
<family>ESG</family>
<product>Dr.Watson</product>
<duplicateId>Blank</duplicateId>
<note></note>
</Bug>
<Bug>
<family>ESG</family>
<product>Dr.Watson</product>
<duplicateId>Blank</duplicateId>
<note></note>
</Bug>
</Bugs>
<Bugs Name="Testing 22" TestCondition="STATUS">
<Bug>
<family>ESG</family>
<product>Dr.Watson</product>
<duplicateId>Blank</duplicateId>
<note></note>
</Bug>
<Bug>
<family>ESG</family>
<product>Dr.Watson</product>
<duplicateId>Blank</duplicateId>
<note></note>
</Bug>
</Bugs>
</DrWatson>
Please note that there are different attribute value defined under
TestCondition as 'STATE' and STATUS. when running this loop second time
the attribute value is being detected as 'STATUS' but it executes the xml
nodes which are present under 'STATE' attribute value.Please suggest.

Friday, 13 September 2013

Different versions of the same app depending on device (app store)

Different versions of the same app depending on device (app store)

I have submitted my game to the App Store and updated it, now the newest
version is the version that every one who downloads my game should get,
Right?
Now the problem is, when I download my game from the App Store on my iPad
mini I get the correct version, however when I download it from an iPad 2
I get the older version!
That's not supposed to happen, How can I fix it? Also, How can I make sure
the newest version of my app is the one everyone gets?(I don't have an
iPhone or iPod touch so I can't test to see what version I get from the
App Store)
Thank you very much in advance for your help! :)

How to use String.startWith(..) to ignore leading whitespace?

How to use String.startWith(..) to ignore leading whitespace?

Let's say I have the following that start with "needle", ignoring leading
whitespace:
String haystack = "needle#####^&%#$^%...";
String haystackWithSpace = " needle******!@@#!@@%@%!$...";
I want to capture anything that starts with "needle" or "^\s*needle.*"(if
there was a regex allowed). Is there an elegant way to do this without
calling .trim()? Or is there a way to make a regex work here? I want the
following to be true:
haystackWithSpace.startsWith("needle"); // doesn't ignore leading whitespace
haystackWithSpace.startsWith("/s*needle"); // doesn't work
Basically, is there a String s that will satisfy the following?:
haystack.startsWith(s) == haystackWithSpace.startsWith(s);

Python Monitor Directories and Subdirectories for file additions/changes

Python Monitor Directories and Subdirectories for file additions/changes

I have created this code to retrieve list paths of all the files within a
certain directory and its subdirectories:
our_dir='c:\\mydocs'
walk=os.walk(our_dir)
for path, folders, files in walk:
for f in files:
file_path=os.path.join(path,f)
print file_path
Or to write these paths into a text file.
How can I run the program on a daily basis and retrieve only the paths of
the files added or changed? I think I can use os to check every file for
the last modified, but this would be too ineffecient for 300K+ files and
hundreds of subfolders.
Any neat way of doing this? I am aware of the other answers:
Monitoring files/directories with python
How do I watch a file for changes using Python?
and of watchdong, https://pypi.python.org/pypi/watchdog
But this doesn't seem to do the exact thing that I want, because the
directory is so huge so polling and file comparison wouldn't work, and the
computer from which I run the monitoring can be turned off and so the
monitoring will be interrupted.
In a nut shell, I need:
A text file for the file paths for the first run
A new text file generated daily for the files changed since the previous run
I am using windows.

how to make kinect upload depthdata short[] as int short texture formats in shader model 3.0?

how to make kinect upload depthdata short[] as int short texture formats
in shader model 3.0?

hi there we are working on a project with Kinect and C# XNA on Windows7.
so we ran into an unexpected problem. the depth data from the kinect
camera gives us an a Short[] but we can only create texture in either
int32 formats or float16 or float32 or float64 formats.
so the problem is converting this fairly large short[] image into a int32
or float on the cpu is ridiculously slow. and there's no bitwize operation
on shadermodel 3.0 so we can't bithack the float back to an int as far as
I've understood it.
were thinking about moving into c++ now but this makes us wonder. how the
hell does xbox360 work with kinect. it should be optimized for xbox we
think? seems silly that there's so few available texture formats.

Creating smaller chunks from large file and sort the chunks

Creating smaller chunks from large file and sort the chunks

I am implementing external sort in python, and currently stuck with this
problem. I have divided a large text file containing integer numbers into
small chunks and I am trying to sort these chunks. So far I am able to
write this much.
with open(fpath,'rb') as fin:
input_iter = iter(lambda: fin.read(40 * 1024),'')
for item in input_iter:
print item
current_chunk = list(item)
# sort the buffers
current_chunk.sort(key = lambda x : int(x))
When I execute this code, I got an error
File "problem3.py", line 68, in <lambda>
current_chunk.sort(key = lambda x : int(x))
ValueError: invalid literal for int() with base 10: ''
which I guess is coming due to this line input_iter = iter(lambda:
fin.read(40 * 1024),'') Is their an alternate way to over come this
problem. Thank you

Thursday, 12 September 2013

IOS Remove CCLayer and Replace With ViewController

IOS Remove CCLayer and Replace With ViewController

I'm going to preface this question with the fact that I'm a complete
novice in IOS, and I'm trying to learn as I go here.
The app I'm working on has a single Navigation Controller containing a
Title Screen View Controller containing the app options. When I click the
start button in the Title Screen it takes me to the Main Game Screen View
Controller which has a CCLayer for doing some simple Cocos2D animation.
All of this is working very well. Here's what I'm missing. I'm trying to
programmatically go back to the title screen. I'm thinking there might be
2 options
1 - End the CCLayer somehow which will return me back to the Main Game
View Controller where I can then send a command to go to the Title View
Controller?
2 - Get a reference to the parent view controller of the CCLayer, and do
the same as above.
I've scoured the internet for a couple of days trying to find what to do,
and I'm out of ideas. I don't really have anything to show apart from I
think I need to initialize the Title View Controller again.
Any ideas will be appreciated, thanks for your time.

ld: symbol(s) not found for architecture i386 Xcode unit tests

ld: symbol(s) not found for architecture i386 Xcode unit tests

I am getting this error when I try to run my unit tests. The entire error is:
Undefined symbols for architecture i386:
"_CGImageRelease", referenced from:
_releaseImages in UIImage+animatedGIF.o
"_CGImageSourceCopyPropertiesAtIndex", referenced from:
_delayCentisecondsForImageAtIndex in UIImage+animatedGIF.o
"_CGImageSourceCreateImageAtIndex", referenced from:
_createImagesAndDelays in UIImage+animatedGIF.o
"_CGImageSourceCreateWithData", referenced from:
+[UIImage(animatedGIF) animatedImageWithAnimatedGIFData:] in
UIImage+animatedGIF.o
"_CGImageSourceCreateWithURL", referenced from:
+[UIImage(animatedGIF) animatedImageWithAnimatedGIFURL:] in
UIImage+animatedGIF.o
"_CGImageSourceGetCount", referenced from:
_animatedImageWithAnimatedGIFImageSource in UIImage+animatedGIF.o
"_kCGImagePropertyGIFDelayTime", referenced from:
_delayCentisecondsForImageAtIndex in UIImage+animatedGIF.o
"_kCGImagePropertyGIFDictionary", referenced from:
_delayCentisecondsForImageAtIndex in UIImage+animatedGIF.o
ld: symbol(s) not found for architecture i386
clang: error: linker command failed with exit code 1 (use -v to see
invocation)
I did all the instructions here:
http://twobitlabs.com/2011/06/adding-ocunit-to-an-existing-ios-project-with-xcode-4/
Also added the library to "Compile Sources" in Build Phrases of the test
target. Still no luck.

How Do I Set An HTML Attribute For a Scala List Item Using Lift CSS Selectors?

How Do I Set An HTML Attribute For a Scala List Item Using Lift CSS
Selectors?

I have some Lift code that creates table rows from a List:
".row *" #> myList.map(x => {
val rowId = x.id
".cell1" #> x.data &
".cell2" #> x.moreData
})
Based on a template like this:
<table>
<tr class="row">
<td class="cell1"></td>
<td class="cell2"></td>
<tr>
<table>
I want output like this:
<table>
<tr class="row" id="123">
<td class="cell1">stuff</td>
<td class="cell2">junk</td>
<tr>
<tr class="row" id="456">
<td class="cell1">more stuff</td>
<td class="cell2">more junk</td>
<tr>
<table>
How do I set that id attribute to be rowId for each tr based on my List
elements?

Google Charts Pie chart displaying Other 100% rather than actual values

Google Charts Pie chart displaying Other 100% rather than actual values

I'm using google charts API to draw a pie chart. The pie chart is
generated dynamically with an ajax call to an API I setup and it was
working but when I started adding more data, suddenly the pie chart went
from displaying each segment to displaying a chart with one value - Other.
Here is the json that's coming back from the server
{
"cols" : [{
"id" : "",
"label" : "Team",
"type" : "string"
}, {
"id" : "",
"label" : "Steps",
"type" : "number"
}
],
"rows" : [{
"c" : [{
"v" : "Draper",
"f" : null
}, {
"v" : "626528",
"f" : null
}
]
}, {
"c" : [{
"v" : "Sterling",
"f" : null
}, {
"v" : "539165",
"f" : null
}
]
}, {
"c" : [{
"v" : "Pryce",
"f" : null
}, {
"v" : "557399",
"f" : null
}
]
}, {
"c" : [{
"v" : "London",
"f" : null
}, {
"v" : "807470",
"f" : null
}
]
}, {
"c" : [{
"v" : "Lynx Local",
"f" : null
}, {
"v" : "428814",
"f" : null
}
]
}, {
"c" : [{
"v" : "Havas Health Software",
"f" : null
}, {
"v" : "375235",
"f" : null
}
]
}
]
}
This is my javascript to load the chart
var jsonData = $.ajax({
url: "/ChartData/OverallSteps",
async: false
}).responseText;
var pieData = new google.visualization.DataTable(jsonData);
var pieOptions = {
width: 600, height: 320, 'legend': { position:
'right',alignment:'center' },is3D: true,sliceVisibilityThreshold:
1/10000, chartArea: {left:0,top:0}
};
var pieChart = new
google.visualization.PieChart(document.getElementById('teamPieChart'));
pieChart.draw(pieData, pieOptions);
As you can see, I've tried setting the sliceVisibilityThreshold per this
Google Pie Chart not Showing All Data Rows but that doesn't seem to be the
problem either. There are only 6 series so it should be fine. Can anyone
see what's going on?

Referring to the current bookmark in mercurial

Referring to the current bookmark in mercurial

I am using bookmarks in mercurial to emulate a git branches-like workflow.
One thing I'm finding is that whenever I push, I invariably want to push
just the current bookmark. Rather than typing
hg push -B <bookmark_name>
all the time, I'd like to alias hg push to just push the current bookmark.
To do that, I need a way of referring to the current bookmark without
mentioning its name. Is there a way to do that?

JSP request.getParameter error

JSP request.getParameter error

I have a hidden parameter in a jsp page using struts.
<html:hidden property="currentDescription"></html:hidden>
It is grabbing the correct values from a properties file and being
rendered in the html.
I want to display a line of code based on this being populated, but it's
not working.
<% if(request.getParameter("currentDescription") != "") { %>
I've tried the .equals as well and that throws an exception.

Dim as Control in VBA Excel

Dim as Control in VBA Excel

I'm trying to go over check boxes in a user form and display them in a
pivot table according to the user selection
I use the following code:
Dim mthIdx As Long
Dim nm As String
Dim c As Control
With ActiveSheet.PivotTables(CakePivot2).PivotFields("month")
For mthIdx = 1 To 12
nm = "CheckBox" & mthIdx
Set c = Controls(nm)
.PivotItems(mthIdx).Visible = printing_rep.c.Value
Next
End With
It works fine when I put it in a user form privete sub but if I'm trying
to put it in a different module I get "Sub or function not defined" error
and "Controls" is highlighted in the code. Does anyone knows what am I
doing wrong?

Can someone give idea on fourth and fifth normal form for database normalization

Can someone give idea on fourth and fifth normal form for database
normalization

I Googled and read many documents, but in all places they consider a first
normal form table as third normal form and then do a second normal form on
it and specify it as fourth normal.
Same goes with fifth normal form. It would be helpful if someone gives an
example or point to a website which has good example without any
assumptions considering first as third NF.

Wednesday, 11 September 2013

Creating a query to display counts of specific results from a longtext field

Creating a query to display counts of specific results from a longtext field

Hello firstly I am a SQL newb and need a little help. I could not find a
question exactly like mine.
(select count(*) from table where Column_x like '%text1%')
(select count(*) from table where Column_x like '%text2%')
(select count(*) from table where Column_x like '%text3%')
So I want the search to return
case 1 | Case 2 | Case 3
xtimes ytimes ztimes
Any help would be great, either just display a queried result or creating
a temporary table.
Cheers,

Perl List::pairwise on Windows+ActiveState produces unexpected result

Perl List::pairwise on Windows+ActiveState produces unexpected result

I think that this Perl should produce ['c', undef] but on Windows 7,
ActiveState 5.16 it produces: [].
use List::Pairwise qw(grepp mapp);
my %k = (a=>1, b=>2, c=>undef);
say dump([grepp {!$b} %k]);

how to convert deep links to hash fragments for IE

how to convert deep links to hash fragments for IE

I'm trying to figure out how to support deep-linking for IE with a
Backbone application using restful routes. If, for example, I have a url
like:
http://domain.com/base/search/searchTerm
Once in the application, Backbone handles the conversion of these routes
to hash fragments, so the above url would be converted to:
http://domain.com/base#search/searchTerm
But the original link won't be converted to a hash fragment yet, so the
routes I have defined don't match/work for IE9 and under. I can "fix" the
pathname section of the url with a regex to make it work for IE, but I
haven't figured out how to reload that url without refreshing the page so
Backbone processes it as a route. Is this possible and if so, how is it
done?

Generic bounds, most of them are unclear

Generic bounds, most of them are unclear

It's kind of complicated to learn Scala's generic bounds. I know that:
T : Tr - T has type of Tr, meaning it implements a trait Tr
T <: SuperClass - T is subclass of SuperClass
T :> ChildClass - T is superclass of ChildClass
However, there are also many more operators:
<% and %>
=:=
<:< and >:>
<% and %>
<%< and >%>
I read about them, but as I said, there was was not comprehensible
explanations. Could you make it clearer?

How to update Primefaces components present on child window?

How to update Primefaces components present on child window?

Here is my code:
<p:commandLink actionListener="#{formBean.fillForm}"
oncomplete="window.open('#{facesContext.externalContext.requestContextPath}/forms/BP008ACT0001_fv_1.xhtml?','_blank');"
value="click"
<f:param name="stDocNo" value="#{row.get('msm006_msa001')}" />
<f:param name="stTrxNo" value="#{row.get('msm006_msa002')}" />
</p:commandLink>
I am trying to pass 'stDocNo' and 'stTrxNo' parameters to properties of
bean named formBean. These properties are then used by label components
present on 'BP008ACT0001_fv_1.xhtml' that is being opened on click of
p:commandLink. The issue that I am facing is that the labels present on
child window do not show the param values that have been passed through
<p:commandLink>.
can anybody tell me what I'm missing out here in my code?

Tuesday, 10 September 2013

Apache poi. Formula evalution. evaluteAll vs setForceFormulaRecalculation

Apache poi. Formula evalution. evaluteAll vs setForceFormulaRecalculation


[better quality]:. http://imageshack.us/photo/my-images/51/v5cg.png/
Problem: i use formulas in my workBook.xlsx. Depending on the
circumstances i change value (3,3). At this example i changed 10 to 20.
And after that i want to calculate the formula, which use this cell. When
it has finished, it will override the value of the cells, remove formula
and record the value. This cell no longer be used for the calculations
again.
Code:
public class ReaderXlsx {
public List<List<String>> ReaderXlsx(String sfilename, int
firstColumn, int columnsCount, int rowsCount, int moduleCount){
int lastColumn=firstColumn+columnsCount;
List<List<String>> rowsContent = new ArrayList<List<String>>();
try ( FileInputStream fileInputStream = new
FileInputStream("C:\\Users\\student3\\"+sfilename+".xlsx");)
{
XSSFWorkbook workBook = new XSSFWorkbook(fileInputStream);
XSSFSheet sheet = workBook.getSheetAt(0);
int firstRow = findOneInFirstColumn(sheet,50);
setModuleCount(sheet,moduleCount);
workBook.getCreationHelper().createFormulaEvaluator().evaluateAll();
toNewLine:
for (int lineId=firstRow;lineId<rowsCount;lineId++) {
List<String> columnsContent = new ArrayList<String>();
Row row = sheet.getRow(lineId);
if (row==null){continue toNewLine;}
if (row.getCell(2)==null ||
row.getCell(2).getStringCellValue().equals("") ) {continue
toNewLine;}
for (int
columnId=firstColumn+1;columnId<lastColumn;columnId++)
{
Cell cell = row.getCell(columnId-1);
if ((cell==null)) { continue toNewLine;}
cell.setCellType(Cell.CELL_TYPE_STRING);
if ((columnId==0 &
cell.getStringCellValue().equals(""))) {continue
toNewLine;}
if ((columnId==5 &
cell.getStringCellValue().equals("")) ||
(columnId==6 &
cell.getStringCellValue().equals("")))
cell.setCellValue("0");
columnsContent.add(cell.getStringCellValue());
}
rowsContent.add(columnsContent);
}
try(FileOutputStream out = new
FileOutputStream("C:\\Users\\student3\\Used"+sfilename+".xlsx");
) {
workBook.write(out);
out.close(); }
}
catch (IOException e) {
e.printStackTrace();
}
return rowsContent;
}
private Integer findOneInFirstColumn(XSSFSheet sheet, Integer maxRows){
int result=0;
toNextLine:
for (int lineId=0;lineId<maxRows;lineId++){
Row row = sheet.getRow(lineId);
if (row==null | row.getCell(0)==null) {result++; continue
toNextLine; }
else{
row.getCell(0).setCellType(Cell.CELL_TYPE_STRING);
if
(row.getCell(0).getStringCellValue().equals("1")){return
result;}
else {result++;}
}
}
return result;
}
private void setModuleCount(XSSFSheet sheet, Integer moduleCount){
Row row = sheet.getRow(1);
if (moduleCount==0) {}
if (moduleCount>0)
{row.createCell(2).setCellValue(moduleCount.toString());}
}
}
Now i use 2 files, becouse i need to save my formulas. I want to use only
1 (source) and update him correctly.

CountdownTimer add time to the current time

CountdownTimer add time to the current time

I have a countdown timer and I want to add 10 seconds to it whenever my
isAddTime method is true. I have successfully added it but whenever the
time is added, it still finishes on the current time.
For example, when it is 20 sec and then isAddTime hits true, the time will
be 30 sec but it will end still end in 20 seconds.
Here's my code:
timerHolder = new CountDownTimer(30000, 1000) {
@Override
public void onFinish() {
Class.isAddTime = false;
Intent i = new Intent(getBaseContext(), OtherClass.class);
startActivity(i);
}
@Override
public void onTick(long millisUntilFinished) {
timeLeft = millisUntilFinished;
if(Class.isAddTime()){
timerHolder.cancel();
AddTime();
Class.isAddTime = false;
}
timer.setText("Time left: " + String.valueOf(timeLeft /
1000));
}
}.start();
And here is the AddTime():
private void AddTime(){
timerHolder = new CountDownTimer(timeLeft + 10000, 1000) {
@Override
public void onFinish() {
Class.isAddTime = false;
Intent i = new Intent(getBaseContext(), OtherClass.class);
startActivity(i);
}
@Override
public void onTick(long millisUntilFinished) {
timeLeft += 10000;
timeLeft = millisUntilFinished;
if(Class.isAddTime()){
timerHolder.cancel();
AddTime();
Class.isAddTime = false;
}
timer.setText("Time left: " + String.valueOf(timeLeft / 1000));
}
}.start();
I was wondering why it still continue the current time even if i had it
cancelled?

Re-Hash user database

Re-Hash user database

I was wondering if there was a method to change the way my site hashed
passwords. My coder friend wasn't the smartest when he didn't add salts to
the sha512 hash. So now it is very insecure and I wish to change that. I
was thinking about making some complicated code to rehash when someone who
has the old hash type logs in and it would set the variable to true after
adding a salt. Or I could take the currently hashed passwords and somehow
fuse a salt into them. I would rather not reset my user database if I
don't have to. Any idea would help. I am also quite the php noob so please
explain if you include code.
It is Hashed using this method.
<?php hash('sha512',"passwordhere") ?>

Vertex Displacement Shader is mapping radial, not linear. How do I fix?

Vertex Displacement Shader is mapping radial, not linear. How do I fix?

I'm writing a vertex displacement shader. I successfully mapped the
vertices of a plane to the brightness values of a video with a GLSL Shader
and Three.js, but the GLSL Shader is mapping the values in a radial
fashion which might be appropriate for texturing a sphere, but not this
plane. There is radial distortion coming from the center outward. I want
to map the "z-depth" of each vertex to a brightness value in a linear
fashion. How do I achieve this?
RuttEtraShader = {
uniforms: {
"tDiffuse": { type: "t", value: null },
"opacity": { type: "f", value: 1.0 }
},
vertexShader: [
'uniform sampler2D tDiffuse;',
'varying vec3 vColor;',
"varying vec2 vUv;",
'void main() {',
'vec4 newVertexPos;',
'vec4 dv;',
'float df;',
"vUv = uv;",
'dv = texture2D( tDiffuse, vUv.xy );',
'df = 1.33*dv.x + 1.33*dv.y + 16.33*dv.z;',
'newVertexPos = vec4( normalize(position) * df * 10.3, 0.0 ) +
vec4( position, 1.0 );',
'vColor = vec3( dv.x, dv.y, dv.z );',
'gl_Position = projectionMatrix * modelViewMatrix * newVertexPos;',
'}'
].join("\n"),
fragmentShader: [
'varying vec3 vColor;',
'void main() {',
'gl_FragColor = vec4( vColor.rgb, 1.0 );',
'}'
].join("\n")
};
texture = new THREE.Texture( video );
texture.minFilter = THREE.LinearFilter;
texture.magFilter = THREE.LinearFilter;
texture.format = THREE.RGBFormat;
texture.generateMipmaps = true;
videoMaterial = new THREE.ShaderMaterial( {
uniforms: {
"tDiffuse": { type: "t", value: texture },
},
vertexShader: RuttEtraShader.vertexShader,
fragmentShader: RuttEtraShader.fragmentShader,
depthWrite: false,
depthTest: true,
transparent: true,
overdraw: false
} );
videoMaterial.renderToScreen = true;
geometry = new THREE.PlaneGeometry(720, 480, 720, 480);
geometry.overdraw = false;
geometry.dynamic = true;
mesh = new THREE.Mesh( geometry, videoMaterial );
mesh.position.x = 0;
mesh.position.y = 0;
mesh.position.z = 0;
mesh.visible = true;
scene.add( mesh );

SJF Algorithm (SRTFS) - Calculate Sorting the Processes?

SJF Algorithm (SRTFS) - Calculate Sorting the Processes?

Table Here
Ok, I have the table above, and I need to calculate the average waiting
time using the preemptive SJF algorithm, but to do that, you must first
'sort' these processes, which I think I don't understand properly how to
do.
If I knew how to sort them, I'd have no trouble calculating the average
waiting time at all.
Here's what I came up with, but I think it's probably wrong.
My Probably Wrong Solution

XML deserialization: All properties null / EndElement not expected

XML deserialization: All properties null / EndElement not expected

Any help is appreciated with this, I've been struggling.
From a HTTP request I receive an XML response. I have no control over its
structure, so I must match that structure with my data contracts. However,
no matter what i do, all the properties in the Result object are either
null or the default value.
XML Structure:
<Customnamedroot xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Results="2"
Skip="0">
<Object>
<Something xsi:nil="true" />
<Anything>2012-06-08T11:21:27</Anything>
<Booleanthing>true</Booleanthing>
</Object>
<Object>
<Something>1463387</Something>
<Anything>2012-06-07T09:16:11.41</Anything>
<Booleanthing>true</Booleanthing>
</Object>
</Customnamedroot>
The call:
SearchResults objects = response.Content.ReadAsAsync<SearchResults>().Result;
Corresponding Data Contract classes:
[CollectionDataContract(Name = "Customnamedroot", ItemName = "Object",
Namespace = "")]
public class SearchResults : List<Result>
{
}
//[DataContract(Name = "Object")]
public class Result
{
[DataMember(Order = 1, Name = "Something", IsRequired = false)]
public decimal? Something{ get; set; }
[DataMember(Order = 2, Name = "Anything", IsRequired = true,
EmitDefaultValue = false)]
public DateTime Anything{ get; set; }
[DataMember(Order = 3, Name = "Booleanthing", IsRequired = true,
EmitDefaultValue = false)]
public bool Booleanthing{ get; set; }
}
Edit: This problem occurs if the DataContract(Name = "Object") is omitted.
If that DataContractAttribute is added, I get the following error:
System.Runtime.Serialization.SerializationException: Error in line 1
position 157.
'EndElement' 'Object' from namespace '' is not expected.
Expecting element 'Something| Anything'.
What am I doing wrong?

Magento: Set Group_Price and Tier_Price => Duplicate entry SQLSTATE[23000]: Integrity constraint violation:

Magento: Set Group_Price and Tier_Price => Duplicate entry
SQLSTATE[23000]: Integrity constraint violation:

I'll try to import products with tier prices and group prices. First time
it works great, but if I try to update it, I'll get an error:
Versuche zu speichern:SQLSTATE[23000]: Integrity constraint violation:
1062 Doppelter Eintrag '4463-0-0-0' für Schlüssel 2
(Duplicate entry for primary key 4463-0-0-0).
I've found a "solution" in a german blog. It recommends to delete all rows
from the tables catalog_product_entity_group_price and
catalog_product_entity_tier_price for the entity_id ( = ProductId).
This works great! But is there a better solution for doing this? A class
method? And why does the magento import process not delete this entrys
before try to inserting the rows?
Another solution was the following code. But it requires a product->save()
action, which was not good for the import performance:
$product->setTierPrice( array() );
$product->save()
$product->setTierPrice($pid["my_tier_price_array"]);
$product->save()
Is there a better solution than a "double save()-method" or directy delete
from the database?

Bull Pugh method of implementing Singleton resulting in "Out-of-order Write"?

Bull Pugh method of implementing Singleton resulting in "Out-of-order Write"?

I went through Bull-Pugh's method of implementing Singleton design pattern
in Java.
I have a concern regarding it. Please correct me if I am wrong anywhere.
Please consider the below Bull-Pugh code:
public class Singleton {
// Private constructor prevents instantiation from other classes
private Singleton() { }
/**
* SingletonHolder is loaded on the first execution of
Singleton.getInstance()
* or the first access to SingletonHolder.INSTANCE, not before.
*/
private static class SingletonHolder {
public static final Singleton INSTANCE = new Singleton();
// Line 10
}
public static Singleton getInstance() {
return SingletonHolder.INSTANCE; // Line 14
}
}
Consider "Thread-1" has called "return SingletonHolder.INSTANCE;" on
Line-14 for the first time. Now the Singleton class will be instantiated
on Line-10.
Before this instantiation is complete, let us say that "Thread-1" is
preempted by an another thread- "Thread-2". When "Thread-2" calls "return
SingletonHolder.INSTANCE;" on Line-14, WILL IT RETURN PARTIALLY
CONSTRUCTED OBJECT?
If it returns a partially constructed object, this situation will be an
"Out-of-Order Write". Please let me know if I am correct on the above case
and share your thoughts. Also please let me know if this situation can be
overcome by any other means. Thanks in advance.

Monday, 9 September 2013

Wordpress blocking iframe automatically created

Wordpress blocking iframe automatically created

I have installed this theme: http://www.designwall.com/product/dw-minion/
in my self-hosted Wordpress

But the thing is whenever I go to a post, I can't highlight nor click on
anything because an iframe is blocking the whole page! I do not know this
generated iframe and it only happens on the said theme. Anyone got an idea
what it is and how can I get rid of it?

How to remove background image with Opencv

How to remove background image with Opencv

i'm new opencv . i writing a remove the background .
my input image
i coded my program as follow steps :
- calculate average pixels

//define roi of image
cv::Rect roi(0, 0, 20 , 20 );
//copies input image in roi
cv::Mat image_roi = imgGray( roi );
//imshow("roi", image_roi);
//computes mean over roi
cv::Scalar avgPixelIntensity = cv::mean( image_roi );
//prints out only .val[0] since image was grayscale
cout << "Pixel intensity over ROI = " << avgPixelIntensity.val[0] << endl;
-create new Mat image base on average pixels values :

//create new mat image base on avgPixelIntensity
cv::Mat areaSampleArv(imgGray.rows,
imgGray.cols,imgGray.type(),avgPixelIntensity.val[0]);
imshow("areaSampleArv", areaSampleArv);
-Invert image :

void image_invert(Mat& image){
int height, width, step, channels;
uchar *data;
height = image.cols;
width = image.rows;
step = (int)image.step;
channels = image.channels();
data = (uchar *)image.data;
for(int i = 0; i < height; i++){
for(int j = 0; j < width; j++){
for(int k = 0; k < channels; k++){
data[i*step + j*channels + k] = 255 - data[i*step + j*channels
+ k];
}
}
}
//imwrite("/Users/thuydungle/Desktop/1234/inverted.png", image);
imshow("inverted", image);}
my image inverted result :
-Add inverted image with original image:

Mat dst;
dst = areaSampleArv + im0;
imshow("dst", dst);
any my image result :
seem it is very bad and i can use thresholding for extraction numbers ?
so , can you tell me how to fix it ?
thank !