Saturday, 31 August 2013

MySQL group by affecting other group

MySQL group by affecting other group

I've got a SUM(value) which calculates the votes for each idea, but this
gets affected by the amount of tags each idea can have.
For example,
SELECT
id,
title,
description,
COALESCE(SUM(case when value > 0 then value end),0) votes_up,
COALESCE(SUM(case when value < 0 then value end),0) votes_down,
GROUP_CONCAT(DISTINCT tags.name) AS 'tags',
FROM ideas
LEFT JOIN votes ON ideas.id = votes.idea_id
LEFT JOIN tags_rel ON ideas.id = tags_rel.idea_id
LEFT JOIN tags ON tags_rel.tag_id = tags.id
GROUP BY ideas.id
So if there are more than one tags.name, then the SUM() get multiplied by
the number of tags.name
How can I fix this?

How can I justify Tumblr blog posts horizontally?

How can I justify Tumblr blog posts horizontally?

I've tried using the recommended methods I've seen used on here for
justifying divs inside of divs, but none of the methods have worked on
Tumblr for blog posts. Any other suggestions for justifying posts
horizontally?

Trackment protection code

Trackment protection code

I have signed up Trackment, added my website. The given code for my
website is like;
<script src="http://trackment.com/?p=**code**"></script>
In their description, I need to add on my page, just after body tag. The
problem is that my designer havent add the body tag in the page, since its
a flash website.
I have added their code after my html tag, it works fine, however I
suspect if its working 100% correctly.
My question is, is it must to add the javascript code in between body tags
or its just a suggestion ? Note: javascript and jquery are included in my
web page.

Using exceptions for control flow

Using exceptions for control flow

I have read that using exceptions for control flow is not good, but how
can I achieve the following easily without throwing exceptions? So if user
enters username that is already in use, I want to show error message next
to the input field. Here is code from my sign up page:
public String signUp() {
User user = new User(username, password, email);
try {
if ( userService.save(user) != null ) {
// ok
}
else {
// not ok
}
}
catch ( UsernameInUseException e ) {
// notify user that username is already in use
}
catch ( EmailInUseException e ) {
// notify user that email is already in use
}
catch ( DataAccessException e ) {
// notify user about db error
}
return "index";
}
save method of my userService:
@Override
@Transactional
public User save(User user) {
if ( userRepository.findByUsername(user.getUsername()) != null ) {
LOGGER.debug("Username '{}' is already in use", user.getUsername());
throw new UsernameInUseException();
}
else if ( userRepository.findByEmail(user.getEmail()) != null ) {
LOGGER.debug("Email '{}' is already in use", user.getEmail());
throw new EmailInUseException();
}
user.setPassword(BCrypt.hashpw(user.getPassword(), BCrypt.gensalt()));
user.setRegisteredOn(DateTime.now(DateTimeZone.UTC));
return userRepository.save(user);
}

Windows ftp client supporting multithreaded remote to remote transfer

Windows ftp client supporting multithreaded remote to remote transfer

I have a large amount of data (3.5TB) that I need to transfer between two
FTP servers. I am not looking for an FXP solution; I understand that I am
looking for an FTP client that will handle downstream to local temp
storage and subsequent upload to destination. The origin FTP I am grabbing
files from limits single connection to 1MBps but allows concurrent
connection without limit. I have a gigabit connection available on the
local windows machine handling the transfer and need multithreaded
downloads (not multipart).
I'm a Linux/Mac developer and I can't think of a client that does what I
need and I have tried filezilla(no remote to remote transfer), smartftp(no
non fxp remote-remote transfer), flashfxp(no multithreading), cuteftp(no
multithreading only multipart). Cyberduck will do what I need, but to
allow multithreading I have to place files individually into the queue,
with thousands of files to transfer I estimate it will take me 30 hours
just to do this.
TL;DR I need a windows FTP client that has a feature set including
Multithreaded downloads for individual files that are queued.
Remote to remote download with temp local storage buffer.

setAccessoryType destroys TableViewCell

setAccessoryType destroys TableViewCell

I use a custom tablecell, labels and images are connected with tags.
If i add
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator]
it destroys my tableview. the image destroys and the background-color.
here are the differences:

Does anyone have any idea where the problem could be? Thanks

Opening c isam files?

Opening c isam files?

I am trying to find a way to access a database of some management software
which uses some kind of raw isam files to store the data. The data folder
compromises of of .idx and .fs5 files, I cannot find any evidence of this
being a informix type as mentioned in another question here on
stackoverflow.
Does anyone have any kind of solution to creating some kind of bridge to
the database? I have had no luck finding an open source odbc to c-isam
driver, is anyone aware of something that could possibly help here?

Friday, 30 August 2013

OpenGL ES 2.0 Scene Lighting iOS

OpenGL ES 2.0 Scene Lighting iOS

I have been looking online and cannot find an example of scene lighting.
Scene lighting meaning there is a light on the wall and all objects which
pass this light get lighted appropriately on the faces which face the
light. Can anyone provide me with an example of such? Or some good reading
on how to do such. I would like to get to the point of using multiple
lights and shadows and possibly lights such as fire which flicker? Is this
possible?
My code below is shading my character but as he rotates (the model view
matrix is rotating), the faces are not changing any lighting.
Vertex Shader precision highp float;
attribute vec4 a_position;
attribute vec3 a_normal;
attribute vec2 a_texCoord;
uniform mat4 u_mvMatrix;
uniform mat4 u_mvpMatrix;
varying lowp vec2 v_texCoord;
varying vec3 v_ecNormal;
varying vec4 v_position;
void main()
{
vec4 mcPosition = a_position;
vec3 mcNormal = a_normal;
vec3 ecNormal = vec3(u_mvMatrix * vec4(mcNormal, 0.0));
v_ecNormal = ecNormal;
v_position = a_position;
v_texCoord = vec2(a_texCoord.x, 1.0 - a_texCoord.y);
gl_Position = u_mvpMatrix * mcPosition;
}
Frag Shader
precision highp float;
uniform sampler2D u_texture;
varying lowp vec2 v_texCoord;
struct DirectionalLight {
vec3 position;
vec3 halfplane;
vec4 ambientColor;
vec4 diffuseColor;
vec4 specularColor;
};
struct Material {
vec4 ambientFactor;
vec4 diffuseFactor;
vec4 specularFactor;
float shininess;
};
uniform DirectionalLight u_directionalLight;
uniform Material u_material;
varying vec3 v_ecNormal;
varying vec4 v_position;
void main()
{
//gl_FragColor = colorVarying * texture2D(texture, texCoordOut);
// normalize
vec3 ecNormal = v_ecNormal / length(v_ecNormal);
vec3 lightPosition = u_directionalLight.position;
vec3 lightDirection;
lightDirection.x = v_position.x - lightPosition.x;
lightDirection.y = v_position.y - lightPosition.y;
lightDirection.z = v_position.z - lightPosition.z;
float ecNormalDotLightDirection = max(0.0, dot(ecNormal,
lightDirection));
float ecNormalDotLightHalfplane = max(0.0, dot(ecNormal,
u_directionalLight.halfplane));
// calc ambient light
vec4 ambientLight = u_directionalLight.ambientColor *
u_material.ambientFactor;
// calc diffuse light
vec4 diffuseLight = ecNormalDotLightDirection *
u_directionalLight.diffuseColor * u_material.diffuseFactor;
// calc specular light
vec4 specularLight = vec4(0.0);
if (ecNormalDotLightHalfplane > 0.0) {
specularLight = pow(ecNormalDotLightHalfplane,
u_material.shininess) * u_directionalLight.specularColor *
u_material.specularFactor;
}
vec4 light = ambientLight + diffuseLight + specularLight;
gl_FragColor = light * texture2D(u_texture, v_texCoord);
}

Thursday, 29 August 2013

Pom.xml is not able to send email?

Pom.xml is not able to send email?

I have added this in my pom.xml . I am on windows7 , I am using
java+testng to write automation scripts. Do I need postfix smtp server to
send emails, thats why below code is not running for me, because same code
is running on ubuntu machine, which has postfix installed.
<plugin>
<groupId>ch.fortysix</groupId>
<artifactId>maven-postman-plugin</artifactId>
<executions>
<execution>
<id>send a mail</id>
<phase>test</phase>
<goals>
<goal>send-mail</goal>
</goals>
<inherited>false</inherited>
<configuration>
<from>test123@test.com</from>
<subject> Test Results</subject>
<failonerror>true</failonerror>
<mailhost></mailhost>
<receivers>
<receiver>paul.lev007@gmail.com</receiver>
</receivers>
<htmlMessageFile>target/surefire-reports/emailable-report.html</htmlMessageFile>
</configuration>
</execution>
</plugin>

Weird behaviour with jQuery datepicker in IE10

Weird behaviour with jQuery datepicker in IE10

I have added a jQuery datepicker to my MVC application and it seems to be
working perfectly in all browsers except for Internet Explorer.
On click of the cell the calendar control appears but clicking through the
months using the navigation icons seems to stop after varying amount of
clicks. The date cells then become unclickable and I am unable to set the
date.
Has anyone ever seen this issue before? And if so was there a solution
available?
My javascript code is as follows:
$(document).ready(function () {
$('#expirydate').datepicker({ dateFormat: 'dd/mm/yy', changeMonth:
true, changeYear: true });
});
And my HTML is as follows:
<label for="expirydate">Expiry Date:</label>
<input type="text" id="expirydate" class="datepicker" name="expirydate"
/><br />

Taking time to load the image from URL to UIImageview

Taking time to load the image from URL to UIImageview

I am using this code for displaying the image from URL to UIImageview
UIImageView *myview=[[UIImageView alloc]init];
myview.frame = CGRectMake(50, 50, 320, 480);
NSURL *imgURL=[[NSURL
alloc]initWithString:@"http://soccerlens.com/files/2011/03/chelsea-1112-home.png"];
NSData *imgdata=[[NSData alloc]initWithContentsOfURL:imgURL];
UIImage *image=[[UIImage alloc]initWithData:imgdata];
myview.image=image;
[self.view addSubview:myview];
But the problem is that its taking too long time to display the image in
imageview.
Please help me...
Is there any method to fast the process...

Wednesday, 28 August 2013

Enhanced Recurring Payments with Website Payments Standard Issue

Enhanced Recurring Payments with Website Payments Standard Issue

Problem: Trying to pass along a variable Monthly Subscription cost to
PayPal based on user-selected options on the form I created with more
Values From Anothers Standart Products. Working Within Website Payments
Standard with Enhanced Recurring Payment option.
Details: User visits "shop" page, Which Is a form with four line items,
each line item Consisting of 2-7 options, each option with an associated
price.
For example, line item 1 is "size of business" with the options being: a)
1-10 employees - $ 20 b) 11 - 20 employees - $ 30, c) 20+ employees - $40
he also bought an item with a fixed value $ 25, that is out a Recurring
Payment.
Is this possible?
What is the correct way to solve this problem by api paypal? It is
possible to attach a signature and a normal purchase in the same shipment?
What about Adaptative Payments to solve This Problem?
Thanks.

JQuery for loop stuck at last index

JQuery for loop stuck at last index

I have function process_row that appends tags to html, and those tags are
chained to a function upon clicked. (in this case, simply alert(i), its
position in the result array).
But however, upon being clicked, the newly generated alerts the length of
the entire result array. I have tried many, many changes to try and make
it work, but it doesn't.
Strange thou, fab_div.attr("id", result_data[0]); works fine !! In Chrome
inspect element the id tags are displayed as they are, but the click
function points everything to the last element in the array.
for example, if I do, fab_div.click(function () { alert(result_data[0])
});, I get the name of the LAST element in the array, doesn't matter which
element was clicked.
can anyone please explain to me... WHY??
I think it may have something to do with $("<div>") where JQuery thinks
it's the same div that it's assigning to. Is there any way around this?
The 's are generated dynamically and I would not want to let PHP do the
echoing. Plus the content may be updated realtime.
Example dataset :
Smith_Jones#Smith#Jones@janet_Moore#Janet#Moore@Andrew_Wilson#Andrew#Wilson
After many, many changes, still not working:
function process_row(data){
result_array = data.split("@");
if(result_array.length > 0){
result_data =result_array[0].split("#");
for(i = 0; i < result_array.length; i++){
result_data =result_array[i].split("#");
var fab_text = result_data[1] + " " + result_data[2]
var fab_div = $("<div>");
fab_div.addClass('scroll_tap');
fab_div.attr("id", result_data[0]);
fab_div.append(fab_text)
// fab_div.click(function () { alert(i) });
// ^ not working, try appending list of id's to id_list
id_list.push(result_data[0])
$('#ls_admin').append(fab_div)
}
for(j = 0; j < id_list.length; j++){
$('#' + id_list[j]).click(function () { alert(j) })
}
}
}
Original Attempt:
function process_row(data){
result_array = data.split("@");
if(result_array.length > 0){
result_data =result_array[0].split("#");
for(i = 0; i < result_array.length; i++){
result_data =result_array[i].split("#");
var fab_text = result_data[1] + " " + result_data[2]
var fab_div = $("<div>").append(fab_text).click(function () {
alert(i) });
fab_div.addClass('scroll_tap');
fab_div.attr("id", result_data[0]);
$('#ls_admin').append(fab_div)
}
}
}

Using FOR loop in VHDL with a variable

Using FOR loop in VHDL with a variable

Is there any possible way to create a for loop in the form:
for i in 0 to some_var loop
// blah,blah
end loop;
If not, is there any alternative way to create the same loop? Since While
loops allows to use variable as the limit, but they are not synthesizeable
in my project.
Thanks in Advance,
Bojan Matovski

javascript - Validation for and tags

javascript - Validation for and tags

I need javascript validation for and tags.
I need validation for following code:
<embed
width="420" height="345"
src="http://www.youtube.com/v/XGSy3_Czz8k"
type="application/x-shockwave-flash">
</embed>
(or)
<iframe width="420" height="345"
src="http://www.youtube.com/embed/XGSy3_Czz8k">
</iframe>

Ajax fill in city automatically

Ajax fill in city automatically

I have a HTML form, and when i fill in a zipcode, i want the city field to
be automaticly updated to the city that belongs with that zipcode.
Here's my form:
<form method="post" action="">
<input type="text" name="zipcode" id="zipcode">
<input type="text" name="city" id="city">
</form>
Here is my ajax:
$('#zipcode').keyup(function(){
var el = $(this);
if (el.val().length == 4) {
$.ajax({
url: 'get_city.php',
cache: false,
type: "GET",
data: "zipcode=" + el.val(),
success: function(data) {
$('#city').val(data);
}
})
}
})
And here is the PHP
$db = mysql_connect('localhost', 'root', '');
mysql_select_db('testbox_new', $db);
$sql = 'select * from cities where zipcode = "'.$_GET['zipcode'].'"';
$result = mysql_query($sql);
while ($row = mysql_fetch_array($sql)) {
return $row['city_name'];
}
Anyone who knows why this isn't working?
Thx :)

Setting DNS servers using OpenVPN client config file

Setting DNS servers using OpenVPN client config file

How can I set DNS servers on the client using only the client
configuration. My client is a windows machine and I want to change the DNS
servers when the client connects and revert back to the original
configuration when I disconnect from the VPN.
All information I have found so far refers to pushing the DNS
configuration to the client using the server's config but in this case I
can't change the server configuration and am currently doing it manually
every time I connect to the VPN. An openvpn config option to set the local
machines DNS servers for the duration of the connection would be great.

Tuesday, 27 August 2013

{ line-height: 0; } causing text to stick out from parent div?

{ line-height: 0; } causing text to stick out from parent div?

<div>
<p>Text Text Text</p>
</div>
div {
height: 100px;
width: 500px;
margin-top: 50px;
background-color: #00f;
}
p {
font-size: 20px;
color: #000;
line-height: 0;
}
Look here: http://jsfiddle.net/pJCBv/
I'm trying to align text flush against the top of the parent div.
line-height: 1; adds 1-2 pixels above and below the font which is why I'm
trying line-height: 0;. But then the text sticks out from the parent div?
It would be perfect if I could get it flush against the top (with no
spacing in between).
Another question: browsers render fonts slightly different, but is the
pixel height consistant accross all browsers? E.g., Will Arial measuring
11px tall be guarenteed to be 11px tall in all browsers? If this is the
case then I could just set the line-height equal to 11px.

Want Ember.js named outlet to only display on click

Want Ember.js named outlet to only display on click

I have a subnav close to working properly thanks to the help of
@intuitivepixel. The problem now is that when I load the root, the subnav
is already displaying. The subnav should only be a part of the 'about'
section -- the main nav is:
about conditions programs testimonials
On the index, the root of the app, these are the only links I would like
displayed. But when you click 'about' I would like a subnav to display
right below the main nav with 'about' set as active and the available sub
links as:
philosophy leadership staff affiliations
Then finally when you click on, say 'philosophy', the philosophy template
loads but the 'about' nav is still active, and now the 'philosophy' nav is
active.
application.hbs:
<div class="row left-nav">
<img class="ew_logo" src="assets/ew.png">{{/linkTo}}
</div>
<div class="row nav">
<div class="large-12 colummns">
<ul class="inline-list top-nav">
<li><h6>ABOUT{{/linkTo}}</h6></li>
<li><h6>//</h6></li>
<li><h6>CONDITIONS</h6></li>
<li><h6>//</h6></li>
<li><h6>PROGRAMS</h6><li>
<li><h6>//</h6></li>
<li><h6>TESTIMONIALS</h6></li>
</ul>
</div>
</div>
<div class="row subnav">
<div class="large-12 colummns">

</div>
</div>
{{outlet}}
application_route.coffee:
Ew.ApplicationRoute = Ember.Route.extend(renderTemplate: ->
@render()
# this renders the application template per se
# and this additional call renders the subnav template into the named
outlet
@render "subnav", #the name of your template
outlet: "subnav" #the name of the named outlet
into: "application" #the name of the template where the named outlet
should be rendered into
)
Thank you!
EDIT
I should also add that I don't want 'subnav' to show up in the url when
'about' is clicked. Sorry for all the questions. Just curious if there an
ember way to do this without hacking a bunch of jquery.

favicon.ico appear in URL of submitted form

This summary is not available. Please click here to view the post.

How to make ping less verbose

How to make ping less verbose

I want to make ping less verbose for my batch script, but I do want it to
show time-out messages and other errors.
This is what I've got so far:
@echo off
:BEGIN
time /T
ping 127.0.0.0 -n 1 | find "TTL"
ping 127.0.0.1 -n 1 | find "TTL"
ping 1.1.1.1 -n 1 | find "TTL"
sleep 10s
GOTO BEGIN
This works, but it is hard to spot the errors on 127.0.0.0 and 1.1.1.1
that give an error message and a time-out message. (I mostly care about
the time-out actually).
Is there any way to make find filter lines with time out and TTL, or
perhaps another trick i can use?

facebook iframe app mismatch scroll

facebook iframe app mismatch scroll


I mentioned this unnecessary horizontal scroll on mine and other apps, is
there a way to fix that or this is facebook bug due the fact they push
layout changes?
thanks

DecimalFormat not ceiling properly

DecimalFormat not ceiling properly

We are currently running some tests which involve ceiling numbers that
have two decimal places. In order to achieve this, we are using Java's
DecimalFormat.
However, the tests are getting strange results, particularly for the case
when we wish to ceil up a '0.00xxx' number.
The following is the instance of the DecimalFormatter that is being used
by the tests:
DecimalFormat decimalFormatter = new DecimalFormat("#########0.00");
decimalFormatter.setRoundingMode(RoundingMode.CEILING);
This test works as expected, that is, it was ceiled correctly:
//The below asserts as expected
@Test
public void testDecimalFormatterRoundingDownOneDecimalPlace3()
{
String formatted = decimalFormatter.format(234.6000000000001);
Assert.assertEquals("Unexpected formatted number", "234.61",
formatted);
}
However, this does not:
//junit.framework.ComparisonFailure: Unexpected formatted number
//Expected :0.01
//Actual :0.00
@Test
public void testSmallNumber()
{
double amount = 0.0000001;
String formatted = decimalFormatter.format(amount);
Assert.assertEquals("Unexpected formatted number", "0.01",
formatted);
}
Can you please explain why we are getting this behaviour. Thanks

How to append 2 word documents into 1 using the command line (no vba)

How to append 2 word documents into 1 using the command line (no vba)

I'm trying to find a simple solution to append 2 MSWord files into one
using Windows 7 command line /batch file only (no vba).
I already tried
copy /B /Y file1.doc+file2.doc=file3.doc
but file3.doc only gets the contents of file1.doc, but not file2.doc.
Copy works just fine with text documents, but is not working for me on
MSWord documents.
Any ideas on how I can accomplish that from the command line?
If doing that in a vb script is simple, I might do it in vb and forget
about my batch file approach.

Monday, 26 August 2013

What is the difference between misc drivers and char drivers?

What is the difference between misc drivers and char drivers?

I'm reading about misc drivers in Linux, and I'm a little confused about
the differences between them and char drivers. One source, the Linux
journal, writes:
Alessandro tells us how to register a small device needing a single entry
point with the misc driver.

Sometimes people need to write "small" device drivers, to support custom
hacks—either hardware or software ones. To this end, as well as to host
some real drivers, the Linux kernel exports an interface to allow modules
to register their own small drivers. The misc driver was designed for this
purpose.
Ok, so from this I get that there's a simple driver (in this case with a
single entry point), that's a misc driver. Then another source, Essential
Linux Device Drivers, states:
Misc (or miscellaneous) drivers are simple char drivers that share certain
common characteristics. Because misc drivers are char drivers, the earlier
discussion on char driver entry points hold for misc drivers, too.
Now this seems to say that misc drivers are just char drivers, but perhaps
a subset of functions, and char drivers can have more than one entry point
(such as an ioctl() or an open() or a read() call)
So, what, in Linux C coding terms, are the differences between a char and
misc device driver? (Besides the obvious major number assignment (10) for
all misc drivers). Is there a difference in supported entry points? Is my
assumption correct that misc device drivers only have a subset of what you
can get in a full char device driver?

How to get only incoming edges on mySQL graph?

How to get only incoming edges on mySQL graph?

I have a Graph represented on a mySQL table as:
uidFrom, uidTo
1 4
4 1
1 5
5 1
6 1 <- only incoming edge
How to get only the "6, 1" pair, having only "1" as input? I mean, how to
query the only incoming edges to node "1" (not both incoming and outgoing
like 4 or 5)?
Thanks in advance;

Windows 7 Lockout

Windows 7 Lockout

I just changed my domain password and now my account keeps getting locked
out. There must be some process on my machine that attempting to
authenticate with incorrect credentials. How can I find out which programs
are attempting authentication?

python join key and values from a dictionary

python join key and values from a dictionary

I have a dictionary that looks similar to this one :
mydic = {'key1':['va1','va2'], 'key2':['vb1','vb2']}
I would like to print file path out these, e.g.
/path/to/dir/key1/dir2/va1
/path/to/dir/key1/dir2/va2
/path/to/dir/key2/dir2/vb1
/path/to/dir/key3/dir2/vb2
I have tried,
for k, v in mydic.iteritems():
print "/path/to/dir/k/dir2/v"
But this one prints out v as a list. How can I achieve the above ? Thanks...

Vagrantfile doesn't notice my shared folder settings

Vagrantfile doesn't notice my shared folder settings

This is my Vagrantfile.
Vagrant.configure("2") do |config|
config.vm.box = "lucid64"
config.vm.box_url = "http://files.vagrantup.com/lucid64.box"
config.vm.network :private_network, ip: "192.168.2.99"
config.ssh.forward_agent = true
config.vm.provider :virtualbox do |v|
v.customize ["modifyvm", :id, "--natdnshostresolver1", "on"]
v.customize ["modifyvm", :id, "--memory", 1024]
v.customize ["modifyvm", :id, "--name", "my-first-box"]
v.gui = false
end
config.vm.synced_folder "C:/wamp/www/yapites", "/var/www", id:
"vagrant-root"
config.vm.provision :shell, :inline =>
"if [[ ! -f /apt-get-run ]]; then sudo apt-get update && sudo
touch /apt-get-run; fi"
config.vm.provision :shell, :inline => 'echo -e "mysql_root_password=1
controluser_password=awesome" > /etc/phpmyadmin.facts;'
config.vm.provision :puppet do |puppet|
puppet.manifests_path = "manifests"
puppet.module_path = "modules"
puppet.options = ['--verbose']
end
end
I believe there is a small mistake here. config.vm.synced_folder
"C:/wamp/www/yapites", "/var/www", id: "vagrant-root".
I can't see my yapites folder under /var/www and see basic things like
index.html.
What may be causing it?

Upgrading GlassFish 3.1.2.2 to use JPA 2.1

Upgrading GlassFish 3.1.2.2 to use JPA 2.1

I am working with GlassFish 3.1.2.2 (I can not upgrade to 4 due to OS
restrictions).
I'm interested in upgrading JPA 2.0 to JPA 2.1 GlassFish 3.1.2.2. How can
I achieve this?

@autorelease Pool and Loops (for, while, do) Syntax

@autorelease Pool and Loops (for, while, do) Syntax

clang allows the following loop syntax:
for (...) @autorelease { ... }
while (...) @autorelease { ... }
do @autorelease { ... } while (...);
I haven't found any documentation on that syntax so far (Apple doesn't use
this syntax in their guides, at least no in the guides introducing the
@autorelease construct), but is it reasonable to assume that the three
statement above are equivalent to the three statements below:
for (...) { @autorelease { ... } }
while (...) { @autorelease { ... } }
do { @autorelease { ... } } while (...);
Since that is what I would expect them to be (going by standard C syntax
rules), yet I'm not entirely sure if that's really the case. It could also
be some "special syntax", where the autorelease pool is not renewed for
every loop iteration.

Hot Deployment with WSO2 ESB

Hot Deployment with WSO2 ESB

Can I do a hot deployment in WSO2 ESB. As an example I want add a new
service / new route without restarting the ESB to minimize the service
interruption.
If possible can you give any example.
If not possible can I know if it will be in future releases.

framesets: url of the changing page is not displayed

framesets: url of the changing page is not displayed

having a frameset in a page, there's a header that i would not like to
change, since it's a menu, i'm sure you're familiar with that... another
frame is a target to links in that menu, and the links lead to other
pages. The problem is when a link is clicked, the url of the page remains
unchanged, so on refresh it's as if i never clicked the link, which is
something i really need to avoid in the context of my webpage...Is there
any way to get the page to display the url of the page being loaded by the
link?

Sunday, 25 August 2013

Inno Setup: Delete empty lines from test file

Inno Setup: Delete empty lines from test file

We are using below code to delete empty lines from text file, But it's not
working.
function UpdatePatchLogFileEntries : Boolean;
var
a_strTextfile : TArrayOfString;
iLineCounter : Integer;
ConfFile : String;
begin
ConfFile := ExpandConstant('{sd}\patch.log');
LoadStringsFromFile(ConfFile, a_strTextfile);
for iLineCounter := 0 to GetArrayLength(a_strTextfile)-1 do
begin
if (Pos('', a_strTextfile[iLineCounter]) > 0) then
Delete(a_strTextfile[iLineCounter],1,1);
end;
SaveStringsToFile(ConfFile, a_strTextfile, False);
end;
Please help me. Thanks in Advance.

add a character C in a column if that column is blank

add a character C in a column if that column is blank

I have some files that look as follows. I need to add a character 'C' in
the fifth column if that column is blank. I prefer inplace editing.
1 87 E P 0 0 131 0, 0.0 0, 0.0 0, 0.0
0, 0.0 0.000 360.0 360.0 360.0 150.0 7.2 83.8 79.2
2 88 E V + 0 0 136 1,-0.1 2,-0.5 3,-0.0
0, 0.0 0.993 360.0 80.8 -61.8 -61.8 7.7 80.9 76.8
3 89 E K S S+ 0 0 195 2,-0.0 2,-0.3 0, 0.0
-1,-0.1 -0.222 77.4 108.3 -45.5 95.3 5.5 82.5 74.2
4 90 E R S S- 0 0 153 -2,-0.5 2,-0.5 2,-0.0
0, 0.0 -0.864 72.2-119.8-173.3 140.8 8.2 84.8 72.9
5 91 E R - 0 0 202 -2,-0.3 2,-0.2 1,-0.0
-2,-0.0 -0.772 46.1-115.0 -83.4 130.6 10.4 85.4 70.0
6 92 E L H - 0 0 109 -2,-0.5 2,-0.5 1,-0.1
-1,-0.0 -0.499 24.5-142.8 -70.2 134.3 14.0 85.3 71.3
7 93 E D + 0 0 126 -2,-0.2 -1,-0.1 1,-0.1
0, 0.0 -0.852 36.1 149.0-101.0 126.6 15.9 88.6 71.1
8 94 E L 0 0 140 -2,-0.5 -1,-0.1 0, 0.0
-2,-0.0 0.735 360.0 360.0-125.7 -35.5 19.6 88.3 70.3
9 95 E E 0 0 235 0, 0.0 -2,-0.0 0, 0.0
0, 0.0 0.494 360.0 360.0 -8.6 360.0 21.0 91.3 68.3
Desired Output
1 87 E P C 0 0 131 0, 0.0 0, 0.0 0, 0.0
0, 0.0 0.000 360.0 360.0 360.0 150.0 7.2 83.8 79.2
2 88 E V C + 0 0 136 1,-0.1 2,-0.5 3,-0.0
0, 0.0 0.993 360.0 80.8 -61.8 -61.8 7.7 80.9 76.8
3 89 E K S S+ 0 0 195 2,-0.0 2,-0.3 0, 0.0
-1,-0.1 -0.222 77.4 108.3 -45.5 95.3 5.5 82.5 74.2
4 90 E R S S- 0 0 153 -2,-0.5 2,-0.5 2,-0.0
0, 0.0 -0.864 72.2-119.8-173.3 140.8 8.2 84.8 72.9
5 91 E R C - 0 0 202 -2,-0.3 2,-0.2 1,-0.0
-2,-0.0 -0.772 46.1-115.0 -83.4 130.6 10.4 85.4 70.0
6 92 E L H - 0 0 109 -2,-0.5 2,-0.5 1,-0.1
-1,-0.0 -0.499 24.5-142.8 -70.2 134.3 14.0 85.3 71.3
7 93 E D C + 0 0 126 -2,-0.2 -1,-0.1 1,-0.1
0, 0.0 -0.852 36.1 149.0-101.0 126.6 15.9 88.6 71.1
8 94 E L C 0 0 140 -2,-0.5 -1,-0.1 0, 0.0
-2,-0.0 0.735 360.0 360.0-125.7 -35.5 19.6 88.3 70.3
9 95 E E C 0 0 235 0, 0.0 -2,-0.0 0, 0.0
0, 0.0 0.494 360.0 360.0 -8.6 360.0 21.0 91.3 68.3

[ Video & Online Games ] Open Question : Battlefield 3 freeze?

[ Video & Online Games ] Open Question : Battlefield 3 freeze?

I just joined a game on Op. firestorm right when it finished loading it
froze the icon was disappearing BUT I still hear the battle going if I
turn my Xbox of will it delete my deta or should I wait the match out

Create a web application to send sms to a group of people [on hold]

Create a web application to send sms to a group of people [on hold]

I have been given a project to create a web Application to send message to
a group of people via sms. After googling it i only found that php can be
used to do so but don't know how. Please can anybody help me where to
start. Can i somehow use way2sms.com to send? Please let me know how.

Celery periodic_task in Django run once(!)

Celery periodic_task in Django run once(!)

I am creating a periodic_task using celery and Django which I want to run
every X seconds.. The task should spawn a couple of sub-tasks, but I need
to make sure only one set of sub-tasks are spawned for each main task.
This is what I have..
@periodic_task(run_every=datetime.timedelta(seconds=2))
def initialize_new_jobs():
for obj in Queue.objects.filter(status__in=['I', 'Q']):
obj = Queue.objects.get(id=obj.id)
if obj.status not in ['I', 'Q']:
continue
obj.status = 'A'
obj.save()
create_other_task.delay(obj.id)
This kinda works, but feels wrong. I haveto refresh obj at the beginning
of the loop to make sure another running periodic_task isnt issuing
create_other_task on the same Queue object.
Is there any better way of doing this kind of job? Basically, I want to do
create_other_task as often as possible, but only ONCE per Queue object
with status I or Q.
This is a shortened version of my problem, so please ignore the fact that
I could just run create_other_task when creating the Queue object, instead
of running the periodic task :)

Timed memory tiles game. now works without timing

Timed memory tiles game. now works without timing

I have done a memory tiles program but i want it to be timed, i.e, the
user shoud be able to play the game only for 2 mins. what do i do?
Also in linux sleep() does not work, what should we use for a delay??

Saturday, 24 August 2013

Overriden methods cannot throw exceptions Java

Overriden methods cannot throw exceptions Java

This is my code block.
class Alpha{
public void Gamma() {
System.out.println("Alphas");
}
}
class Beta extends Alpha{
public void Gamma() throws Exception //Line 1
{
try {
System.out.println("Betas");
} catch(Exception e) {
System.out.println("Exception caught");
} finally {
System.out.println("xfg");
}
}
public static void main(String[] args) throws Exception {
Alpha g = new Beta();
g.Gamma();
}
}
This code fails to compile because I have added "throws" in Line1.
The compiler complains that overridden methods cannot throw exceptions.
Why so ?.
Why cant an overridden method throw an exception ?.
Because I can override a method from a base class by adding n lines of
code in the child's class implementation.
And these added code can throw an exception so why I cant use "throws" in
the overridden method ?.

Using selenium to save images from page

Using selenium to save images from page

I'm using Selenium & Google Chrome Driver to open pages programatically.
On each page there is a dynamically generated image which I'd like to
download. At the moment, I'm waiting for the page to finish loading, then
I grab the image URL and download it using System.Net.WebClient.
That works fine except I'm downloading the images twice - once in the
browser, once with WebClient. The problem is that each image is roughly
15MB and downloading twice adds up quickly.
So - is it possible to grab the image straight from Google Chrome?

Double filter with lambda expression

Double filter with lambda expression

I'm create a product edit form, this form has following TextBox, Id, Code,
Width, Height, and Color
Id and Code can't repeat, so I want make a "checking" for Code repeat in
my Code_TextChanged event
I had try fallowing lambda expression for checking (products is a List)
if(products.Where(x=>x.code.Equals(Code.Text)).Count(g=>!g.id.Equals(Id.Text))
0) CodeExist = true;
I don't know why, when I opened a register, it will mark CodeExist is true
How to I can make a condition, for filter product.code.Equals(Code.Text)
and !product.id(Id.Text) ?

Error using carrierwave on image processing

Error using carrierwave on image processing

I keep getting this error when uploading a file using carrierwave.
undefined method `process' for
/uploads/tmp/1377378142-19197-6422/4.jpg:AvatarUploader
I am trying to resize an image on upload, I have minimagick installed.
This is what the avater uploader looks like:
# Process files as they are uploaded:
process :scale => [200, 300]
#
def scale(width, height)
process resize_to_fill: [200, 300]
end
Any ideas what could be wrong ? I am using rails 4.0

Probability, "good" basket.

Probability, "good" basket.

We have 10 balls to divide to 5 baskets, the baskets are numbered 1-5 and
we consider a "good" basket one which contains the same ammount of balls
as its number. X = Number of "good" baskets. Calculate E(X), the average
value of X.
This question is under the "Indicators" section of my course, But seeing
as everybasket has a different chance to be "good" I dont know how to
calculate this, except going into combinatorics but that would take the
whole day. Thanks in advance.

Ubuntu Touch install syntax error

Ubuntu Touch install syntax error

I encounter an error while trying to install ubuntu touch on my nexus 4.
After the following: phablet-flash
(cdimage-touch|cdimage-legacy|ubuntu-system|community) -b
I receive an error saying: syntax error near unexpected token `cdimage-touch'
Anyone know where I'm going wrong?
Thanks

Are potato fruits (not "potatoes") edible?

Are potato fruits (not "potatoes") edible?

My uncle has a fairly expansive garden and he grows potatoes. He asked a
question, that being if they'd ever seen tomatoes growing from their
potato plants. I've done some research (and remembered some things I had
been told), mostly coming to find out that potatoes and tomatoes are both
of the nightshade family and so they share some similar traits (one of
which that they have similar fruit, i.e. tomatoes and my uncles potato
fruits).
My question is whether they're edible or not? (They're from the nightshade
family, they could kill you for all I know)
If they ARE edible, how could you cook them?

Getting NullPointerException when running simple JMS

Getting NullPointerException when running simple JMS

I try to run a simple JMS application from Oracle Java EE 6 tutorial ,
here's the URLs to the app code
http://ianzepp.googlecode.com/svn/trunk/javaeetutorial5/examples/jms/simple/producer/src/java/Producer.java
http://ianzepp.googlecode.com/svn/trunk/javaeetutorial5/examples/jms/simple/synchconsumer/src/java/SynchConsumer.java
I mainly use Eclipse, GlassFish 3.1.2 . Ended up getting
NullPointerException . Throwing some light on it would be far appreciated
..

Friday, 23 August 2013

checking different data value in a same column mysql query?

checking different data value in a same column mysql query?

id_detail_item id_item id_detail_item_name
1 1 abc
2 1 abcd
3 1 cde
4 3 zki
5 3 zkr
how to check if there are two different data in "id_detail_item_name" in
same "id_item"?
I've tried this but got error "SELECT id_item FROM table_detail_item WHERE
id_detail_item_name='abc' AND id_detail_item_name='abcd'";

Is there a way to set a distinct ID and name for a text_field in Rails 2?

Is there a way to set a distinct ID and name for a text_field in Rails 2?

I've got a Rails 2 site I'm trying to add a form handler to, but I'm
running into problems converting the html form fields into form handler
fields.
The form code begins with:
<% form_for @newsavedmap, :html=>{:id=>'createaMap'} do |f| %>
I keep getting errors when I try things like
<%= text_field :newsavedmap, :html=>{ :value => 'New Map',
:name=>'newsavedmapname', :id=> 'savedmap_name', :size => '30' } %>
Error:
ActionView::TemplateError (wrong number of arguments (1 for 2)) on
line #284 of app/views/layouts/maptry.html.erb:
Here are the fields. How can I convert these to form handler fields in
Rails 2?
<input id="savemap_name" name="newsavedmapname" size="30" type="text"
value="New Map"></p>
<select id="startdrop" name="startthere">
<OPTIONS HERE>
</select>
<select multiple id="waypoints" class="mobile-waypoints-remove"
name="waypointsselected[]">
<OPTIONS HERE>
</select>
Thanks for any help you can provide!

How do you reply to questions?

How do you reply to questions?

I have asked several questions and received satisfactory answers. Is there
a way to close out a question or does their status just stay open?
Thanks,

About hosting architecture for a travel agency - How to decide? [on hold]

About hosting architecture for a travel agency - How to decide? [on hold]

We're changing the hosting for our web sites. Do you know where can I get
advice on the best architecture that we can have?
Currently we've only one server which holds all the domains and all the
databases. The domains are from a Travel Agency, and this is an IIS server
with SQL Server, and the number of visits is around 500,000 per month.
I was thinking in having two database servers, one that manages all the
database content for promotions, tours information, etc, and other
database server that holds the customers information (the information from
the people buying things on the web sites).
What do you think?

Should int main() function must return a value in all compilers?

Should int main() function must return a value in all compilers?

why is it not necessary to include return statement while using int main()
in some compilers for c++?What about turbo c++?

Stereo NvAPI init delayed

Stereo NvAPI init delayed

I have directx9 application and a problem with nVidia's stereo api
(automatic mode). Commands like NvAPI_Stereo_Activate() start working ONLY
after first present() on directx device. All nvapi initialization was done
well (got everywhere NvAPI_OK).

Thursday, 22 August 2013

Missing email folders

Missing email folders

I just got the samsung galaxy s3 through verizon and linked my personal
bellsouth email account. I notice when i go to look at all folders that
three or four are missing from my view. How can I get all of my folders in
my view?

bootstrap modal page on load issue

bootstrap modal page on load issue

I have an "awesome" bootstrap modal bug. When document ready, the bootrap
modal window rendered (not showing), and I can not click any links in this
area. After I launched the modal, the issue has been eliminated.
here an screenshot: http://d.pr/i/LK4f
tip, idea?
cheers, daniel

How do you add marker to map using leaflet map.on('click', function) event handler

How do you add marker to map using leaflet map.on('click', function) event
handler

I'm trying to use an event handler to add a marker to the map. I can
manage this with a callback function, but not when I separate the function
from the event handler.
Callback (http://fiddle.jshell.net/rhewitt/U6Gaa/7/):
map.on('click', function(e){
var marker = new L.marker(e.latlng).addTo(map);
});
Separate function (http://jsfiddle.net/rhewitt/U6Gaa/6/):
function newMarker(e){
var marker = new L.marker(e.latlng).addTo(map);
}

Change src of IFRAME to URL dinamically generated in JSF

Change src of IFRAME to URL dinamically generated in JSF

I have a rich:modalPanel being triggered by an a4j:button in a xhtml page
(Facelets). Inside the modal, there is an html:IFRAME in order to redirect
the flow to another system's page login.
The problem is that external page expects a parameter. This parameter is
set in a Managed Bean and referenced by the IFRAME, like this:
<rich:modalPanel id="modalCadastramentoProcessoSAJ"
styleClass="modalForms" width="800" height="400" zindex="1001"
style="overflow:auto">
...
<iframe id="frameSAJ" width="750" height="600"
src="changeIframeSrc(#{tratarProcessoMB.urlString})"/>
</rich:modalPanel>
By doing that, I am receiving a HTTP 404 error. Therefore, the URL is not
being built correctly. Below is the Javascript code:
<script language="Javascript" type="text/javascript">
function changeIframeSrc(param)
{
<!--
var str1 = "<IP>/saj/loginIntegracao.jsf?sistema=TDCS&parametro=";
var srcString = str1.concat(param);
document.getElementById("frameSAJ").src = srcString;
-->
}
</script>
How can I dinamically build this URL ?
I've tried to pass it by POST, but the result is a blank page redirecting,
inside the IFRAME.

How to get collections from sub-folder in docpad?

How to get collections from sub-folder in docpad?

my folds structure are something like this:
documents
techs
docs
I want to get a collection from docs, my code is :
coffeescript techs: ->
@getCollection("html").findAllLive({relativeOutDirPath:
/techs/docs/},[{date: -1}]).on "add", (model) ->
model.setMetaDefaults({layout: "post"})
It just won't works... Could somebody tell me what's going on?

Wednesday, 21 August 2013

Pass data between two servers in KDB using C

Pass data between two servers in KDB using C

There are two server with different data available in them. I am looking
for a way to combine two tables using q query in C++ without running any
servers at my end.
Query 1 @ Server 1 => table1 Query 2 @ Server 2 => table2
I want to use asof join in Q to join table1 and table2 in C++.
Is this possible ?

Why is word inserting dots into output of RTF file

Why is word inserting dots into output of RTF file

I am replacing text in RTF documents for a mail merge and have come across
a problem with Microsoft Word 2010, I assume the same is occuring in
earlier versions of Word. The problem is Word is duplicating paragraphs
and inserting "..." at the start of the paragraph.
I would like to know why this is happening? Seaching the raw text does not
find a string with three dots. I assume there is an error in the
formatting or structure of the text?
Note that opening the same document in Libre Office or Open office does
not have the dots or duplicated paragraphs.
An example document can be found here http://pastebin.com/1kBzS3FP

How do I return the text of a WebElement using Perl's Selenium::Remote::Driver?

How do I return the text of a WebElement using Perl's
Selenium::Remote::Driver?

I feel like I must be missing something obvious. I know the XPath to a
WebElement and I want to compare the text in that element to some string.
Say the XPath for the element is /html/body/div/a/strong and I want to
compare it to $str.
So it shows up in source like ...<strong>find this string</strong>
So I say
use strict;
use warnings;
use Selenium::Remote::Driver;
# Fire up a Selenium object, get to the page, etc..
Test::More::ok($sel->find_element("/html/body/div/a") eq $str, "Text
matched");
When I run this the test fails when it should pass. When I try to print
the value of find_element($xpath) I get some hash reference. I've googled
around some and find examples telling me to try
find_element($xpath)->get_text() but get_text() isn't even a method in the
original package. Is it an obsolete method that used to actually work?
Most of the examples online for this module say "It's easy!" then show me
how to get_title() but not how to check the text at an XPath. I might be
going crazy.

Debug "Comparison method violates its general contract!"

Debug "Comparison method violates its general contract!"

I have an own, relatively sophisticated string comparator and a large list
of strings (~100 strings, already tried to reduce but then the problem is
not reproducible) where sorting them produces the above error when trying
to sort with Java 7. I guess, that the rule
if a < b and b < c then a < c
might be violated. What is the best way to find out a sample which
violates the contract?

How to export Oracle database scheme in Navicat for Oracle?

How to export Oracle database scheme in Navicat for Oracle?

I can export full database (schemas and data) in Navicat for Oracle, but I
need only database scheme. How can I get it?

Cant create iframe with fixed position

Cant create iframe with fixed position

I need to create iframe with fixed (absolute) position. I usesd
<iframe src="http://www.whatismyreferer.com" width="300" height="300"
style="position: fixed; left: 100; top: 10"></iframe>
But it not works :( My iframe showed like styles "left" and "top" are 0
So question is how to create iframe with fixed position on the page and
correctly set the left and top params?
Regards!

My listview with database is not working

My listview with database is not working

Hi I have created a list view in my activity,in which I want to display
the contents from the database. but an error occured saying there is no
list view found Can anybody give me a better solution to overcome the
error?
my log cat is given below
08-21 06:54:52.103: E/AndroidRuntime(6874): FATAL EXCEPTION: main
08-21 06:54:52.103: E/AndroidRuntime(6874): java.lang.RuntimeException:
Unable to start a
ctivity ComponentInfo{com.neochat/com.neochat.Friends}:
java.lang.RuntimeException: Unable
to start activity ComponentInfo{com.neochat/com.neochat.Friends_list}:
java.lang.RuntimeException: Your content must have a ListView whose id
attribute is
'android.R.id.list'
08-21 06:54:52.103: E/AndroidRuntime(6874): at
android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
08-21 06:54:52.103: E/AndroidRuntime(6874): at
android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
08-21 06:54:52.103: E/AndroidRuntime(6874): at
android.app.ActivityThread.access$600(ActivityThread.java:141)
I am giving my code for the listview java class below
public class Friends_list extends ListActivity implements
OnItemClickListener{
private ArrayList<String> results = new ArrayList<String>();
private String tableName = LoginDataBaseAdapter.tableName;
private SQLiteDatabase newDB;
ListView listview;
Context context;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
openAndQueryDatabase();
displayResultList();
setContentView(R.layout.activity_friends);
context=this;
listview=(ListView)findViewById(R.id.listView1);
//String[] arrayColumns=new String[]{"Name,Username"};
//int[]arrayViewIDs=new int[]
{R.id.textViewSMSSender,R.id.textViewMessageBody};
Cursor cursor;
//cursor.getContentResolver().query(Uri.parse
("content://sms/inbox"),null,null,null,null);
//@SuppressWarnings("deprecation")
//SimpleCursorAdapter adapter=new
SimpleCursorAdapter(this,R.layout.friendsms, cursor,
arrayColumns,
arrayViewIDs);
//listview.setAdapter(adapter);
// ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
// android.R.layout.simple_list_item_activated_1,
android.R.id.text1,
value);
listview.setOnItemClickListener(this);
}
private void displayResultList() {
TextView tView = new TextView(this);
tView.setText("Friends");
getListView().addHeaderView(tView);
setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, results));
getListView().setTextFilterEnabled(true);
}
private void openAndQueryDatabase() {
try {
LoginDataBaseAdapter loginDataBaseAdapter=new
LoginDataBaseAdapter(this.getApplicationContext());
newDB=loginDataBaseAdapter.getWritableDatabase();
Cursor c=newDB.rawQuery(" SELECT NAME , USERNAME FROM "+
tableName, null);
if (c != null ) {
if (c.moveToFirst()) {
do {
String Name=c.getString(c.getColumnIndex("NAME"));
String Username=c.getString(c.getColumnIndex("USERNAME"));
}
while(c.moveToNext());
}
}
}
catch (SQLiteException se) {
Log.e(getClass().getSimpleName(), "Could not open the database");
}
finally {
if(newDB!=null)
newDB.execSQL(" DELETE FROM "+ tableName);
newDB.close();
}
}
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
long arg3)
{
Intent in2=new
Intent(Friends_list.this,InboxActivity.class);
startActivity(in2);
}
}
Here is the code where I have created my database
public class LoginDataBaseAdapter extends SQLiteOpenHelper {
public static final int NAME_COLUMN=2;
static final String DATABASE_NAME = "UserDetails.db";
static final int DATABASE_VERSION = 1;
static final String tableName="Signup";
static final String DATABASE_CREATE = "create table "
+ " Signup "+ " " + " "
+ " ( "
+ " ID "
+ " integer primary key autoincrement , "
+ " NAME text , USERNAME text ,
PASSWORD text , EMPLOYEE_CODE text,"
+ " MOBILE_NUMBER integer ); ";
public SQLiteDatabase db;
private final Context context;
private DataBaseHelper dbHelper;

Tuesday, 20 August 2013

Ruby: Using split and regex

Ruby: Using split and regex

I am trying to take in a line of text as follows:
1 | Company 1234 Anywhere St, SJ (12.34567, -98.765432)
and isolate the first number and the two floats.
I have been playing with a RegEx creator and came up with the following:
To get the first integer: (\\d+) To get the floats:
([+-]?\\d*\\.\\d+)(?![-+0-9\\.])
But when I use these with .split I am getting "syntax error, unexpected
$undefined, expecting ')'"
Any insight would be great!

Display webcam snapshots on website

Display webcam snapshots on website

I have a Dlink DCS-942-L webcam that will ftp one snapshot jpeg per hour
to my website. It embeds them in a folder by date and then again in
subfolders by hour according to time. I would like to display these
pictures on a webpage. Any ideas would be appreciated.

Design Pattern for Server, where application is single-page RIA

Design Pattern for Server, where application is single-page RIA

So I'm using Node and ExtJS server-side/client-side respectfully. By using
ExtJS, I'm moving a lot of the presentation logic client-side. Thus,
something like MVC wouldn't make sense server-side since the view-logic is
all client-side.
At this point, my Node server's responsibilities are essentially:
Act as proxy to persistent storage (MongoDB) for ExtJS stores
User validation/sessioning with Windows Active Directory
Hooking-in with existing Enterprise infrastructure (databases,
Salesforce.com, etc).
Well I know design patterns aren't the end-all-be-all, and conforming to a
design pattern can in some cases impede progress, but I'm relatively new
to web-programming in general. I'd like to use a pattern to start just so
I don't make any major architectural decisions that will haunt me for the
rest of the project.
Is there a pattern will suited for my needs that I could lean-on?

setting fragments in page viewer

setting fragments in page viewer

Okay, so the thing is that my PagerAdapter keeps repeating only one
fragment for a specific amount of times. I'm using the PagerAdapter that
automaticly is created with Eclipse's 'Fixed tabs + swipe' option. I've
edited it a little bit but the problem seems to persist. What have I done
wrong and/or how do I set another fragment to be displayed? Here is my
PagerAdapter's code.
public class SectionsPagerAdapter extends FragmentPagerAdapter {
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int index) {
Fragment fragment = null;
switch(index){
case 0:
fragment = new DummySectionFragment();
break;
case 1:
fragment = new Fragment2();
break;
default:
break;
}
//return fragment
return fragment;
}
@Override
public int getCount() {
// Show 2 total pages.
return 2;
}
@Override
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.title_section1).toUpperCase(l);
case 1:
return getString(R.string.title_section2).toUpperCase(l);
case 2:
return getString(R.string.title_section3).toUpperCase(l);
}
return null;
}
}

Last page missing

Last page missing

I was writing a document in TeX but when I reach what is supposed to be
page number 5 the pdf output refuses to show the last page. I have checked
the code and there is nothing wrong with it. If I remove some parts it
shows up without any problem. It seems the last page is simply unwilling
to show up!
I'm using TeX Shop on a Mac and the built in previewer.
Any clues?

Monday, 19 August 2013

Change Variable Value in While Looping

Change Variable Value in While Looping

I want to know how to modify variable value each time while looping.
Please guide me what i am doing wrong in below coding.
$amount = 500;
while ($amount > 0) {
$a = $amount - 50;
echo $a . "<br>";
}
I am receiving this:
450 450 450 450 450 450 450 450 450
But i want that:
450 400 350 300 250 200 150 100 50

Opencart .htaccess config issue

Opencart .htaccess config issue

I know there was similar issues but was unable to resolve the problem I've
been having.
I am using Opencart 1.5.5.1. We recently updated the website so all the
links are completely different so I have 301 redirected a very large
number of links. The problem is, they aren't working.
This is what my .htaccess file looks like:
# 1.To use URL Alias you need to be running apache with mod_rewrite enabled.
# 2. In your opencart directory rename htaccess.txt to .htaccess.
# For any support issues please visit: http://www.opencart.com
Options +FollowSymlinks
# Prevent Directoy listing
Options -Indexes
# Prevent Direct Access to files
<FilesMatch "\.(tpl|ini|log)">
Order deny,allow
Deny from all
</FilesMatch>
# SEO URL Settings
RewriteEngine On
# If your opencart installation does not run on the main web folder make
sure you folder it does run in ie. / becomes /shop/
RewriteBase /
RewriteRule ^sitemap.xml$ index.php?route=feed/google_sitemap [L]
RewriteRule ^googlebase.xml$ index.php?route=feed/google_base [L]
RewriteRule ^download/(.*) /index.php?route=error/not_found [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_URI} !.*\.(ico|gif|jpg|jpeg|png|js|css)
RewriteRule ^([^?]*) index.php?_route_=$1 [L,QSA]
### Additional Settings that may need to be enabled for some servers
### Uncomment the commands by removing the # sign in front of it.
### If you get an "Internal Server Error 500" after enabling any of the
following settings, restore the # as this means your host doesn't allow
that.
# 1. If your cart only allows you to add one item at a time, it is
possible register_globals is on. This may work to disable it:
# php_flag register_globals off
# 2. If your cart has magic quotes enabled, This may work to disable it:
# php_flag magic_quotes_gpc Off
# 3. Set max upload file size. Most hosts will limit this and not allow it
to be overridden but you can try
# php_value upload_max_filesize 999M
# 4. set max post size. uncomment this line if you have a lot of product
options or are getting errors where forms are not saving all fields
# php_value post_max_size 999M
# 5. set max time script can take. uncomment this line if you have a lot
of product options or are getting errors where forms are not saving all
fields
# php_value max_execution_time 200
# 6. set max time for input to be recieved. Uncomment this line if you
have a lot of product options or are getting errors where forms are not
saving all fields
# php_value max_input_time 200
# 7. disable open_basedir limitations
# php_admin_value open_basedir none
RewriteRule ^downloads.asp$ http://www.example.com/downloads [R=301,L]
#301 redirect
Redirect 301 /onlinestore http://mywebsite.com.au
Redirect 301 /gallery.html http://mywebsite.com.au
Redirect 301 /Images/getaflatstomachoct2012.pdf http://mywebsite.com.au
Redirect 301 /onlinestore/all-products/allvia-melatonin-3-cream-57g
http://mywebsite.com.au
Redirect 301 /aboutus.html http://mywebsite.com.au/about_us
Redirect 301 /meetus.html http://mywebsite.com.au/about_us
Redirect 301 /mission.html http://mywebsite.com.au/about_us
Redirect 301 /articleselectprotein.html http://mywebsite.com.au/blogs
Redirect 301 /enewsletters.html http://mywebsite.com.au/blogs
Redirect 301 /enewsletters/april2013/april2013.html
http://mywebsite.com.au/blogs
Redirect 301 /enewsletters/june2010/enewsletterjune2010.html
http://mywebsite.com.au/blogs
Redirect 301 /enewsletters/june2013/june2013.html
http://mywebsite.com.au/blogs
Redirect 301 /enewsletters/october2012/october2012.html
http://mywebsite.com.au/blogs
Redirect 301 /proteintablelarge.html http://mywebsite.com.au/blogs
Redirect 301 /enewsletters/november2011/november2011.html
http://mywebsite.com.au/blogs/christmas-survival-guide.html
Redirect 301 /enewsletters/march2011/march2011.html
http://mywebsite.com.au/blogs/digestion-boost-energy-recover-better-be-happier.html
Redirect 301 /enewsletters/february2011/february2011.html
http://mywebsite.com.au/blogs/fat-loss-during-your-lunch-break.html
Redirect 301 /enewsletters/june2012/june2012.html
http://mywebsite.com.au/blogs/living-healthier-by-alkalising-your-body-what-it-means-and-how-to-achieve-it..html
Redirect 301 /enewsletters/august2010/enewsletteraugust2010.html
http://mywebsite.com.au/blogs/marathon-triathlon-and-endurance-supplementation-guide.html
Redirect 301 /articletop10fattips.html
http://mywebsite.com.au/blogs/psn-s-top-10-fat-loss-tips.html
Redirect 301 /enewsletters/september2010/enewsletterseptember2010.html
http://mywebsite.com.au/blogs/psn-s-top-10-fat-loss-tips.html
Redirect 301 /enewsletters/march2012/march2012.html
http://mywebsite.com.au/blogs/q-a-we-answer-frequently-asked-questions.html
Redirect 301 /enewsletters/may2012/may2012.html
http://mywebsite.com.au/blogs/supplement-packs-for-your-goal.html
Redirect 301 /enewsletters/november2010/enewsletternovember2010.html
http://mywebsite.com.au/blogs/supplement-packs-for-your-goal.html
Redirect 301 /enewsletters/july2011/july2011.html
http://mywebsite.com.au/blogs/zma-better-sleep-sex-recovery-and-more.html
Redirect 301 /contactus.html http://mywebsite.com.au/contact
Redirect 301 /maplarge.pdf http://mywebsite.com.au/contact
Redirect 301 /benefits.html
http://mywebsite.com.au/membership-terms-and-conditions.html
Redirect 301 /memberform.html
http://mywebsite.com.au/membership-terms-and-conditions.html
Redirect 301 /terms.html
http://mywebsite.com.au/membership-terms-and-conditions.html
Redirect 301 /onlinestore/accessories-1/all-accessories?page=1
http://mywebsite.com.au/accessories
Redirect 301 /onlinestore/accessories-1/all-accessories?page=2
http://mywebsite.com.au/accessories
Redirect 301 /onlinestore/accessories-1/all-accessories?page=3
http://mywebsite.com.au/accessories
Redirect 301 /onlinestore/accessories-1/all-accessories?page=4
http://mywebsite.com.au/accessories
Redirect 301
/onlinestore/accessories-1/all-accessories/advanced-fitness-manta-ray
http://mywebsite.com.au/accessories
The redirects continue. So the issue is:
-when you go to original address:
http://www.mywebsite.com.au/onlinestore/accessories-1/all-accessories/advanced-fitness-manta-ray
-it
should redirect you to here: http://mywebsite.com.au/accessories
-but
it goes here:
route=onlinestore/accessories-1/all-accessories/advanced-fitness-manta-ray">http://mywebsite.com.au/accessories-1/all-accessories/advanced-fitness-manta-ray?route=onlinestore/accessories-1/all-accessories/advanced-fitness-manta-ray
So the issue is, it goes to the correct new site, but then adds ?route=
followed by the original url.
I have tried to get support but have had no success. If I can get any
support at all, I would be very grateful.
Regards, Helen

IOS Cancelling Local Notifications

IOS Cancelling Local Notifications

I dont like asking vague questions but I couldnt exactly tell what the
problem is.
In my app I set some daily local notifications. Shooting everyday at
200PM. I later removed the codes that sets the local notifications, and
added push notification feature.
I test the push and it works (whenever I want to). But I still get the old
notifications as well, could it be because I set them earlier somewhere on
the phone itself. Is there a way to cancel them without coding. For
example are they cancelled if I remove the app?

Accessing a previously fullfilled promise result in a promises chain

Accessing a previously fullfilled promise result in a promises chain

What is the correct pattern, when coding with promises, to access data
coming from long before in a chain of promises?
For example:
do_A.then(do_B).then(do_C).then(do_D).then(do_E_WithTheDataComingFrom_A_And_C_OnlyWhen_D_IsSuccesfullyCompleted)
My current solution: passing along a single JSON structure through the
chain, and let each step populate it. Any opinion about that?

WPF - Window DataContext or ElementName

WPF - Window DataContext or ElementName

I am currently facing a little problem with specifing or not specifing the
datacontext of a window, and why there is a difference between various
methods. Hope you can help me out.
Lets start with some code to show my problem. This is the code behind for
my TestWindow.xaml.cs, nothing really special about it just a simple
string property
public partial class TestWindow : Window
{
private string _helloWorld = "Hello World!";
public string HelloWorld
{
get { return _helloWorld; }
set { _helloWorld = value; }
}
public TestWindow()
{
InitializeComponent();
}
}
This code will be the same for all 3 following XAML layouts, so no changes
behind the code only in XAML.
1.) Databinding with given ElementName
<Window x:Class="Ktsw.Conx.ConxClient.TestWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TestWindow" Height="300" Width="300"
Name="TestWin">
<Grid>
<TextBlock Text="{Binding HelloWorld,
ElementName=TestWin}"></TextBlock>
</Grid>
</Window>
2.) Databinding with specifing DataContext on Window
<Window x:Class="Ktsw.Conx.ConxClient.TestWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TestWindow" Height="300" Width="300"
DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
<TextBlock Text="{Binding HelloWorld}"></TextBlock>
</Grid>
</Window>
3.) Neither ElementName nor specifing DataContext
<Window x:Class="Ktsw.Conx.ConxClient.TestWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="TestWindow" Height="300" Width="300">
<Grid>
<TextBlock Text="{Binding HelloWorld}"></TextBlock>
</Grid>
</Window>
The first two methods work just fine, but why fails the 3rd?
In the first method I am not specifing the DataContext and it works
automatically, in the second method I am not specifing the ElementName and
it works, but without declaring one of those it fails. Why would it fail
getting both automatically, but work fine with getting each individually?

Sunday, 18 August 2013

Intellij can't run app on Genymotion(but can start it)

Intellij can't run app on Genymotion(but can start it)

I tried to use genymotion instead of emulator.But after installing the
genymotion and intellij plugin,I found that I can't run app on the
genymotion.The target devices which I choose is"Show chooser dialog" but
there is no genymotion even I can start the genymotion with the plugin.
The version of intellij is 12.1.4,and the genymotion is 1.1.0.

PayPal subscription integration workflow

PayPal subscription integration workflow

I am looking to offer subscriptions on one of my websites, but am a little
confused on exactly which PayPal services I need to use to accomplish
this. I'm not looking for any code to help me here, just a little guidance
on how the entire process should play out and whether I'm using the
correct PayPal tools.
So, users sign up for an account on my site and receive a free 30 day
membership (I know I can set this in PayPal, but I do not want to ask
users for credit card/billing information at registration). Within that
initial 30 days, users have the option of subscribing and keeping their
account active by entering their payment information directly on my site
using PayPal Payments Advanced. If the user still has, for example, 10
days left in the complimentary subscription, I do not want them to be
charged until after their complimentary subscription expires.
Is there a way I can specify the date I would like the subscription to
start when submitting the subscription information to PayPal? Or would I
need to use a simple 'Buy Now' type of transaction for the first payment,
and then set up a subscription?
Am I also correct in assuming that by using PayPal IPN I will receive
relevant subscription information, such as when I receive a payment, when
a customer's payment could not be successfully completed, etc., so that I
can take the necessary administrative actions on my site to activate or
deactivate their accounts?
Also, can I use "Modify Subscription" buttons to allow users to update
their credit card or billing information, or would they need to directly
login to their PayPal accounts for this?
Finally, would all this still work as intended for users who do not have
PayPal accounts?

count the number of images on a webpage, using urllib

count the number of images on a webpage, using urllib

For a class, I have an exercise where i need to to count the number of
images on any give web page. I know that every image starts with , so I am
using a regexp to try and locate them. But I keep getting a count of one
which i know is wrong, what is wrong with my code:
import urllib
import urllib.request
import re
img_pat = re.compile('<img.*>',re.I)
def get_img_cnt(url):
try:
w = urllib.request.urlopen(url)
except IOError:
sys.stderr.write("Couldn't connect to %s " % url)
sys.exit(1)
contents = str(w.read())
img_num = len(img_pat.findall(contents))
return (img_num)
print (get_img_cnt('http://www.americascup.com/en/schedules/races'))

Why is my UIButton object not showed?

Why is my UIButton object not showed?

Ther is my code, when I create button:
- (void)viewDidLoad
{
[super viewDidLoad];
UIButton *button=[­[UIButton alloc] initWithFrame:CGRectMake(20, 20, 40,
20)];
button.titleLabel.text=@"but1";
button.backgroundColor=[UIColor redColor];
button.alpha=0.6;
}
Please help me, I tried to change button parameters, origin and other,
itsnot help.

NAS servers, best option?

NAS servers, best option?

I'm about to buy a nas server, 4bay, with intel processor (so I can put
PLEX in it).
I've been looking at two options: Netgear ReadyNAS Ultra 4 and Asustor
AS-604T
The Asustor is a bit more expensive, is it worth the extra money?
Is there any other better options?

Error on HTML processing

Error on HTML processing

I have the following html code below.
<html>
<head><title>OPTIONS</title></head>
<body>
<p>Choose schedule to generate:</p>
<form action='cgi-bin/mp1b.cgi' method="get">
<input type=checkbox value='tfield' name=on />Teacher<input type=text
name="teacher" value=""/><br>
<input type=checkbox value='sfield' name=on />Subject<input type=text
name="subject" value=""/><br>
<input type=checkbox value='rfield' name=on />Room<input type=text
name="room" value=""/><br>
<input type=submit value="Generate Schedule"/>
</form>
</body>
</html>
And I have this CGI script written in C:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void)
{
char *data = malloc(1024);
char *teacher;
char *subject;
char *room;
printf("Content-type:text/html\n\n");
printf("<html><body>");
data = getenv("QUERY_STRING");
if(data){
sscanf(data,"teacher=%s&subject=%s&room=%s",teacher,subject,room);
printf("%s,%s,%s",teacher,subject,room);
}
printf("</body></html>");
return 0;
}
Whenever I click the Submit button, it outputs
(null),Ã…,œí
What's wrong with my code? Thanks!

Saturday, 17 August 2013

How to get action to execute onclick

How to get action to execute onclick

I've added a "Help Tour" link to the top of my page. So, when somebody
clicks it, I call guiders.show('first');
So, to get this to work I've tried:
Code snippit from index
<div class="click"><a href="#">Launch LeapFM Mini tutorial'</a></div>
Code snippit from guiders.js.coffee
$('.click').click.guiders.show('first');
guiders.createGuider({
buttons: [{ name: 'Next' }]
, description: 'Follow this short 7 tip tutorial and learn how to get the
most out of Leap. It will only take a few minutes :)'
, id: 'first'
, next: 'second'
, overlay: true
, title: 'Welcome to LeapFM! Mini Tutorial:'
}).show();
But when I click the link to the tutorial it doesn't start the tutorial.
I have a feeling it's a simple error with this line here:
$('.click').click.guiders.show('first');
Albeit, after messing around with it for quite a bit, I can't seem to spot
it.

Visual intuition partial/directional derivative

Visual intuition partial/directional derivative

I've had some trouble with the (visual) intuition behind the directional
derivatives so I decided to take a step back and look up the visual
intuition behind partial derivatives, which I think I do understand. See
picture below

As I understood it, we basically have the purple paraboloid (?) which is a
function of (x,y) and then we have the gray plane which is the plane in
the direction of the x-axis. If you intersect the 2 planes I would say you
get a parabola. If you have a certain point specified on the paraboloid,
you can find its partial derivative in the direction of x.
The way I draw the connection to a directional derivative is just by
saying that you can tilt the gray plane in any direction and find the
derivative. Is this correct, and if not, what's wrong?

How do weapon statistics relate to game play?

How do weapon statistics relate to game play?

I'm interested to know what the weapon stats mean in the game. I have made
some assumptions, but I'm curious to know if there is any official line on
them.
Take the following example of adding a short barrel to my rifle.

So does this mean that with reduced accuracy I'll have less chance to hit
an enemy, so more weapon spread. What about mobility? Is a higher value
better? Does it affect weapon swapping? Reloading? What benefits are there
of lots of noise?
There doesn't really seem to be anything in game to understand what the
stats actually mean in real terms.

Android-heap: Image in AlertDialog taking up huge heap memory and not freeing it up

Android-heap: Image in AlertDialog taking up huge heap memory and not
freeing it up

I have a particular fragment containing an image. On click of the image I
scale up the image and show it in a dialog with some title.
All this works fine.
While using DDMS I saw the heap memory shoots up by ~4Mb on open of the
dialog box and on close of it that is not freed up.
And hence doing this a couple of times takes up huge heap memory.
public class ImageOnClickListener implements OnClickListener {
String article_title ;
String article_url;
public ImageOnClickListener(String imageUrl, String title) {
article_title = title;
article_url = imageUrl;
}
@Override
public void onClick(View v) {
View layout = null;
AlertDialog.Builder imageDialog = new
AlertDialog.Builder(getActivity());
LayoutInflater inflater =
(LayoutInflater)getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = inflater.inflate(R.layout.image_fragment, null);
TextView articleTitle =
(TextView)layout.findViewById(R.id.image_title);
articleTitle.setText(article_title);
articleTitle.setTextSize(MainActivity.fontSize +10);
articleTitle.setTextColor(getResources().getColor(
android.R.color.white));
URL imageUri = null;
try {
imageUri = new URL(article_url);
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
Bitmap bitmapImage = null;
try {
bitmapImage =
BitmapFactory.decodeStream(imageUri.openConnection().getInputStream());
} catch (IOException e) {
e.printStackTrace();
}
WindowManager wm = (WindowManager)
getActivity().getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int width = display.getWidth(); // deprecated
int height = display.getHeight();
int w = (int) (width*0.8);
int h = (int) (height*0.8);
ImageView imageObject =
(ImageView)layout.findViewById(R.id.image_main);
int imgWidth = bitmapImage.getWidth();
int imgHeight = bitmapImage.getHeight();
int ratio = w/imgWidth;
Bitmap.createScaledBitmap(bitmapImage,
imgWidth*ratio,imgHeight*ratio, true);
imageObject.setImageBitmap(bitmapImage);
RelativeLayout.LayoutParams imageParams = new
RelativeLayout.LayoutParams(w,h);
imageObject.setLayoutParams(imageParams);
alertDialog = imageDialog.setView(layout).create();
int dialogWidth = (int) (width*0.9);
int dialogHeight = (int) (height*0.9);
alertDialog.show();
alertDialog.getWindow().setLayout(dialogWidth,dialogHeight);
}
}
Basically I was looking for a way to free up that memory on dismiss of the
dialog.

php get matching keywords even if they are not exactly the same / next to each other

php get matching keywords even if they are not exactly the same / next to
each other

I'm looking for a way to find keywords (or word combinations) in a text,
that not necessarily match literally with keywords in a database but are
recognized as such.
There is a database with keywords;
id keyword
.. ...
6 cities
7 hotel
8 visit Paris
9 swimming pool
.. ...

I already have the following code to get the exact matching keywords from
a text:
$text = $_POST['text'];
$connection = new mysqli('localhost', 'root', 'password', 'database');
if (mysqli_connect_errno($connection))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$query = "SELECT * FROM `keywords`";
$keywords_found = array();
$result = $connection->query($query);
while ($result = $result->fetch_assoc())
{ if (stripos($text, $result['keyword']) !== false) {
$keywords_found[] = $result['keyword'];
}
else {}
}
echo "<div>";
foreach ($keywords_found as $key => $value) {
echo '<p>' . $value . '</p>';
}
echo '</div>';
Some examples of what is already achieved:
1.1 "You have visited a lot of cities." => ["cities"]
1.2 "She wants to visit Paris some day and stay in a hotel with a swimming
pool." => ["visit Paris", "hotel", "swimming pool"]
1.3 "When they visit cities such as Paris, they choose a 5-star hotel." =>
["cities", "hotel"]

Some examples of what I want to achieve:
2.1 "When they visit cities such as Paris, they choose a 5-star hotel." =>
["visit Paris", "cities", "hotel"]
2.2 "On the second day of my visit to Paris, I wanted to go swimming in
the hotel's pool." => ["visit Paris", "swimming pool", "hotel"]
2.3 "Paris is one of those cities I'd like to visit" => ["cities", "visit
Paris"]
2.4 "When I visited my uncle, ... [3 lines of text] ... he lived in
several cities, such as London and Paris" => ["cities"] // visit and Paris
are too far away

I haven't got much of a clue on how to tackle this and I'm not even sure
if this is possible. I've been looking at regex; is it possible to set a
limited search range (eg. example 2.4)? Can I use offset to limit the
search area around part of one keyword element if there are more of them?

The ratio of boys to girls in a certain classroom was 2:3. if boys represented ...

The ratio of boys to girls in a certain classroom was 2:3. if boys
represented ...

pThe ratio of boys to girls in a certain classroom was $2:3$. If boys
represented five more than one third of the class, how many people were
there in the class room?/p pI do not seem to get how to solve it. Can
somebody please help? /p

Implementing PIPO in verilog

Implementing PIPO in verilog

I am looking to implement a 32-bit Parallel in-Parallel out in verilog
HDL. Here is the code I have written...
module pipo(input_seq, answer,reset, clock);
input [31:0] input_seq;
input reset,clock;
output [31:0] answer;
always @ (reset)
begin
if(!reset)
begin
answer[31:0]<=1'b0;
end
end
always @ (posedge clock)
begin
answer[31:1]<=input_seq[30:0];
end
endmodule
However this leads to the following error log( using iverilog):
pipo.v:10: error: answer['sd31:'sd0] is not a valid l-value in pipo.
pipo.v:4: : answer['sd31:'sd0] is declared here as wire.
pipo.v:16: error: answer['sd31:'sd1] is not a valid l-value in pipo.
pipo.v:4: : answer['sd31:'sd1] is declared here as wire.
Elaboration failed
What are the problems?

Friday, 16 August 2013

How can I get a date into this format, 2013-08-09T19:08:28Z, using PHP?

How can I get a date into this format, 2013-08-09T19:08:28Z, using PHP?

Needed format: 2013-08-09T19:08:28Z
I would prefer to use the DateTime class in PHP.
Please help. Thanks.

Saturday, 10 August 2013

Changing Gnome back to Unuty

Changing Gnome back to Unuty

I recently installed the new Gnome 3.8 on my Ubuntu OS thinking it would
only add the DE to my session manager at log in. I was wrong however. It
actually changed the default to Gnome! I prefer Unity much more, but
cannot change it back. How can I fix this?

make extern C++ function return a message if an exception is thrown

make extern C++ function return a message if an exception is thrown

I would like to make my extern C++ function return a message when an
exception occurs. Something like this:
extern "C" __declspec(dllexport) const char* __stdcall Calculate(double
&result, double a, double b)
{
try
{
result = InternalCalculation(a, b);
}
catch(std::invalid_argument& e)
{
return e.what();
}
return "";
}
double InternalCalculation(double a, double b)
{
if(a < b)
{
const char* err = "parameters error!";
throw std::invalid_argument(err);
}
return sqrt(a - b);
}
On the other hand, I call the function from my C# program and I would like
to show error in a MessageBox:
[DllImport(@"MyDll.dll", EntryPoint = "Calculate")]
private static extern IntPtr Calculate(out double result, double a, double
b);
private void Calculate()
{
IntPtr err;
double result = 0;
err = Calculate(out result, out 2, out 3);
var sErr = Marshal.PtrToStringAnsi(err);
if (string.IsNullOrEmpty(sErr))
MessageBox.Show(sErr);
...
}
Unfortunately, it doesn't work.. the MessageBox just shows random characters.
I'm surprised because if I replace:
return e.what();
by:
const char* err = "parameters error!";
return err;
Then "parameters error!" will be shown correctly in the messagebox of the
C# code. Both 'err' and 'e.what()' are the same type (const char*), so
what's wrong with 'e.what()'??

PyQt App deployment

PyQt App deployment

I'm developing four bioinformatic software's with PyQt. I mostly target
Windows OS users but since the programs run without any problems on
Ubuntu, I thought to upload them to the USC (I also got several requests).
However, I'm a bit worry whether this makes sense because last year I
participated the Ubuntu App Showdown and my app is still pending review.
Is there an easy way to create Debian packages (similar to Quickly) or can
I simply upload the source? Is the reviewer process "dead" or not
interested in scientific tools? In short, does it makes sense to invest
time in deployment to the USC?
Thanks in advance! Stefanie

Friday, 9 August 2013

PHP string cookie define

PHP string cookie define

I have a string defined like:
DEFINE('IMAGES_DIR',"/portal/images/");
After i place it inside of a cookie its content becomes
%2Fportal%2Fimages%2F
I need the string to return like:
/portal/images/

How To Create Launcher For Application?

How To Create Launcher For Application?

I am using Ubuntu 13.04, I recently downloaded Fritzing .tar.bz2 , which I
extracted it & there is one .sh file, which I have to execute everytime
from terminal to run the application.
My question is, Is it possible to create a launcher of Fritzing & make it
show up in Applications in Dash ? If it is, then please help me out with
steps.
Thank you.

A General Question [on hold]

A General Question [on hold]

Can some one post a question in this site and also indicate that he/she
will send $$ to the first person who can help with a correct answer? Or
will this be a violation of the rules and regulations?

MySQL Update with Subquery

MySQL Update with Subquery

I've got an annoying issue with an update query I'm trying to get
working... The following statement SHOULD update channels.media_view_count
to the result of the subquery (for all channels).
UPDATE
channels c
SET
c.media_view_count = (
SELECT
SUM(t.view_count)
FROM (
SELECT DISTINCT
m.viewkey,
m.view_count
FROM
media m
INNER JOIN
participants p
ON
m.id = p.medium_id
WHERE
p.user_id = c.id
AND
m.is_viewable = 1
AND
(p.pending = 0)
) AS t
);
The subquery works fine independently (when specifying an actual id for
c.id, like 47778 or whatever), but when I execute this statement, I get:
ERROR 1054 (42S22): Unknown column 'c.id' in 'where clause'
I thought I would be able to access the channels table (aliased as c) from
within the subquery? Am I missing something or am I totally wrong here?
Any and all help is appreciated :)
Thanks,
Jeff