Multiple Inheritance in C
I am stuck with a classical Multiple Inheritance problem in C.
I have created source files Stack.c and Queue.c. Both of them #include a
file Node.c (which containing functions to allocate and deallocate
memory). Now, I am trying to implement another program in a single file,
for which I need to include both Stack.c and Queue.c. I tried to #include
both the files, but the compiler is throwing a conflicting type error.
What is the most correct way to do so?
Thanks in advance!!
Saturday, 31 August 2013
Mysql subquery sum of votes
Mysql subquery sum of votes
I've got a table of votes, alongside a table of 'ideas' (entries)
Basically, I want to retrieve an object that can be read as:
id,
name,
title,
votes : {
up : x,
down : y
}
So it's simple enough until I get to the subquery and need to do two sets
of SUMs on the positive and negative values of votes.
SELECT id,name,title FROM ideas
LEFT JOIN votes ON ideas.id = votes.idea_id
My (simplified) votes table looks something like:
id
idea_id
value
Where value can be either a positive or negative int.
How would I go about getting the above object in a single query?
Bonus point: How would I also get an aggregate field, where positive and
negative votes are added together?
I've got a table of votes, alongside a table of 'ideas' (entries)
Basically, I want to retrieve an object that can be read as:
id,
name,
title,
votes : {
up : x,
down : y
}
So it's simple enough until I get to the subquery and need to do two sets
of SUMs on the positive and negative values of votes.
SELECT id,name,title FROM ideas
LEFT JOIN votes ON ideas.id = votes.idea_id
My (simplified) votes table looks something like:
id
idea_id
value
Where value can be either a positive or negative int.
How would I go about getting the above object in a single query?
Bonus point: How would I also get an aggregate field, where positive and
negative votes are added together?
How can I get the base address of the target process after DLL injection?
How can I get the base address of the target process after DLL injection?
After I've successfully injected my dll into my target process, say
"target.exe", how can I get the base address of "target.exe"?
I've tried GetModuleHandle(0) and GetModuleHandle("target.exe") but it
doesn't seem to be right and I'm not sure how to debug. I've tried to
print it like this:
//retrive target's base address
DWORD EXEBaseAddr = (DWORD) GetModuleHandle((LPCWSTR)"target.exe");
std::stringstream sstr;
sstr << EXEBaseAddr;
std::string str = sstr.str();
String^ str3 = gcnew String(str.c_str());
baseAddressLBL->Text = str3;
I had to cast it at the end again because I'm using a Windows Form (not
sure if that's what it's called) to print the address in my interface.
After I've successfully injected my dll into my target process, say
"target.exe", how can I get the base address of "target.exe"?
I've tried GetModuleHandle(0) and GetModuleHandle("target.exe") but it
doesn't seem to be right and I'm not sure how to debug. I've tried to
print it like this:
//retrive target's base address
DWORD EXEBaseAddr = (DWORD) GetModuleHandle((LPCWSTR)"target.exe");
std::stringstream sstr;
sstr << EXEBaseAddr;
std::string str = sstr.str();
String^ str3 = gcnew String(str.c_str());
baseAddressLBL->Text = str3;
I had to cast it at the end again because I'm using a Windows Form (not
sure if that's what it's called) to print the address in my interface.
How to return IEnumerable instead of string with conditions in foreach?
How to return IEnumerable instead of string with conditions in foreach?
What approach do I have to make, to make something like the method below
to work for IEnumerable<Flight> instead of string? I want to manipulate my
IEnumerable source(in parameter) with conditions written in method, and
return IEnumerable based on those conditions only.
public string FilterFlights(IEnumerable<Flight> flights)
{
string s = "";
foreach (var flight in flights)
{
var indexItem = 0;
DateTime previousArrivalDateTime = new DateTime();
TimeSpan timeSpan;
int time = 0;
foreach (var segments in flight.Segments)
{
if (indexItem == 0)
{
previousArrivalDateTime = segments.ArrivalDate;
s = s + "Departure: " + segments.DepartureDate + ",
Arrival: " + segments.ArrivalDate + "; ";
}
if (indexItem > 0)
{
timeSpan = segments.DepartureDate - previousArrivalDateTime;
time += timeSpan.Hours;
s = s + "Departure: " + segments.DepartureDate + ",
Arrival: " + segments.ArrivalDate + "; ";
previousArrivalDateTime = segments.ArrivalDate;
}
indexItem++;
}
if (time > 2)
Console.WriteLine(s);
}
return s;
}
Thank you!
What approach do I have to make, to make something like the method below
to work for IEnumerable<Flight> instead of string? I want to manipulate my
IEnumerable source(in parameter) with conditions written in method, and
return IEnumerable based on those conditions only.
public string FilterFlights(IEnumerable<Flight> flights)
{
string s = "";
foreach (var flight in flights)
{
var indexItem = 0;
DateTime previousArrivalDateTime = new DateTime();
TimeSpan timeSpan;
int time = 0;
foreach (var segments in flight.Segments)
{
if (indexItem == 0)
{
previousArrivalDateTime = segments.ArrivalDate;
s = s + "Departure: " + segments.DepartureDate + ",
Arrival: " + segments.ArrivalDate + "; ";
}
if (indexItem > 0)
{
timeSpan = segments.DepartureDate - previousArrivalDateTime;
time += timeSpan.Hours;
s = s + "Departure: " + segments.DepartureDate + ",
Arrival: " + segments.ArrivalDate + "; ";
previousArrivalDateTime = segments.ArrivalDate;
}
indexItem++;
}
if (time > 2)
Console.WriteLine(s);
}
return s;
}
Thank you!
django/nginx/gunicorn - ec2 instance not serving static files
django/nginx/gunicorn - ec2 instance not serving static files
I've tried to resolve this myself, but my application on ec2 is not
getting any static files e.g. js, css, img, etc.
nginx conf looks like:
server {
server_name ec2-xx-xxx-xxx-xxx.compute-1.amazonaws.com;
access_log off;
location /static/ {
alias /home/ubuntu/virtualenv/staticfiles/;
}
location / {
proxy_pass http://127.0.0.1:8001;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header X-Real-IP $remote_addr;
add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI
COM NAV"';
}
}
settings.py in django
STATIC_ROOT = '/home/ubuntu/virtualenv/staticfiles/'
I ran python manage.py findstatic img/templated/base/favicon.ico and it
came back with:
user@ip-X-X-X-X:~/virtualenv/mysite$ python manage.py findstatic
img/templated/base/favicon.ico
Found 'img/templated/base/favicon.ico' here:
/home/ubuntu/virtualenv/mysite/homelaunch/static/img/templated/base/favicon.ico
What am I doing wrong here? I'm simply trying to use the files under
/home/ubuntu/virtualenv/mysite/homelaunch/static/ and it is loading the
templates properly, but not any img, css, etc.
I've tried to resolve this myself, but my application on ec2 is not
getting any static files e.g. js, css, img, etc.
nginx conf looks like:
server {
server_name ec2-xx-xxx-xxx-xxx.compute-1.amazonaws.com;
access_log off;
location /static/ {
alias /home/ubuntu/virtualenv/staticfiles/;
}
location / {
proxy_pass http://127.0.0.1:8001;
proxy_set_header X-Forwarded-Host $server_name;
proxy_set_header X-Real-IP $remote_addr;
add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI
COM NAV"';
}
}
settings.py in django
STATIC_ROOT = '/home/ubuntu/virtualenv/staticfiles/'
I ran python manage.py findstatic img/templated/base/favicon.ico and it
came back with:
user@ip-X-X-X-X:~/virtualenv/mysite$ python manage.py findstatic
img/templated/base/favicon.ico
Found 'img/templated/base/favicon.ico' here:
/home/ubuntu/virtualenv/mysite/homelaunch/static/img/templated/base/favicon.ico
What am I doing wrong here? I'm simply trying to use the files under
/home/ubuntu/virtualenv/mysite/homelaunch/static/ and it is loading the
templates properly, but not any img, css, etc.
Transmission on FreeNAS umask / owner of files
Transmission on FreeNAS umask / owner of files
going slightly crazy with Transmission installed on FreeNas 8.3.1 (not in
a jail)
Everything is fine except the ownership / permissions of the downloaded
files, they are all owned by root and have mask: rwxr-sr-x
I have tried changing 'umask' in settings.json from 0 to 18 (read it
somewhere) but that doesn't help; what I want is for ANY user to be able
to delete these files (rw.rw.rw.), or at a minimum the group, not just the
owner; I don't know what I should change umask to for this to work.
Probably really easy if you understand umask...
alternatively, how do I change the settings so the owner is another user,
not root; i start the transmission on startup as a service /daemon, so not
sure how to do all that.
any tips greatly appreciated!
going slightly crazy with Transmission installed on FreeNas 8.3.1 (not in
a jail)
Everything is fine except the ownership / permissions of the downloaded
files, they are all owned by root and have mask: rwxr-sr-x
I have tried changing 'umask' in settings.json from 0 to 18 (read it
somewhere) but that doesn't help; what I want is for ANY user to be able
to delete these files (rw.rw.rw.), or at a minimum the group, not just the
owner; I don't know what I should change umask to for this to work.
Probably really easy if you understand umask...
alternatively, how do I change the settings so the owner is another user,
not root; i start the transmission on startup as a service /daemon, so not
sure how to do all that.
any tips greatly appreciated!
Vimgolf Top X explaination
Vimgolf Top X explaination
Challenge: http://vimgolf.com/challenges/51cf1fae5e439e0002000001
Best solution:
S]*daw{@.UP@.JZZ
Now the question is how does the solution work? Just picking up Vim and
now just getting into the more advanced commands.
Challenge: http://vimgolf.com/challenges/51cf1fae5e439e0002000001
Best solution:
S]*daw{@.UP@.JZZ
Now the question is how does the solution work? Just picking up Vim and
now just getting into the more advanced commands.
PHP Error: Constants get undefined after including them
PHP Error: Constants get undefined after including them
Ok heres the problem. I defined a few constants to store in my database
information.
Example -
FileName: config.php
<?php
//Define Database Constants
defined("DB_SERVER") ? NULL : define("DB_SERVER", "localhost");
defined("DB_NAME") ? NULL : define("DB_NAME", "test");
defined("DB_USER") ? NULL : define("DB_USER", "root");
defined("DB_PASSWORD") ? NULL : define("DB_PASSWORD", "password");
?>
I've included this in another file called database.php :
<?php
require_once("config.php");
class MySQLDatabase {
private $connection;
function __construct(){
$this->open_connection();
}
public function open_connection(){
$this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD);
if(!$this->connection){
die("Database connection failed: " . mysql_error());
} else {
$db_select = mysql_select_db(DB_NAME);
if(!$db_select){
die("Database selection failed: " . mysql_error());
}
}
}
}
$database = new MySQLDatabase();
?>
Here's the problem, whenever I include 'database.php' on another page,
theres an error stating that I have undefined constants. Of course the
database connection doesnt work either. Now, if I define these constants
inside of 'database.php' instead of doing it on a different file, this
works.
Is there a reason why this is happening?
Ok heres the problem. I defined a few constants to store in my database
information.
Example -
FileName: config.php
<?php
//Define Database Constants
defined("DB_SERVER") ? NULL : define("DB_SERVER", "localhost");
defined("DB_NAME") ? NULL : define("DB_NAME", "test");
defined("DB_USER") ? NULL : define("DB_USER", "root");
defined("DB_PASSWORD") ? NULL : define("DB_PASSWORD", "password");
?>
I've included this in another file called database.php :
<?php
require_once("config.php");
class MySQLDatabase {
private $connection;
function __construct(){
$this->open_connection();
}
public function open_connection(){
$this->connection = mysql_connect(DB_SERVER, DB_USER, DB_PASSWORD);
if(!$this->connection){
die("Database connection failed: " . mysql_error());
} else {
$db_select = mysql_select_db(DB_NAME);
if(!$db_select){
die("Database selection failed: " . mysql_error());
}
}
}
}
$database = new MySQLDatabase();
?>
Here's the problem, whenever I include 'database.php' on another page,
theres an error stating that I have undefined constants. Of course the
database connection doesnt work either. Now, if I define these constants
inside of 'database.php' instead of doing it on a different file, this
works.
Is there a reason why this is happening?
Friday, 30 August 2013
Where to place sitemap.xml in playframework 2.1 project
Where to place sitemap.xml in playframework 2.1 project
Just for a quick question. Where does the sitemap.xml to place in play
framework 2.1 project? do we need to configure the route file to the
sitemap.xml?
Appreciate your help
thanks, Best rgsd, a1ucard
Just for a quick question. Where does the sitemap.xml to place in play
framework 2.1 project? do we need to configure the route file to the
sitemap.xml?
Appreciate your help
thanks, Best rgsd, a1ucard
Thursday, 29 August 2013
Does the simpleGrid require additional downloads?
Does the simpleGrid require additional downloads?
I want to try the simpleGrid in a HotTowel project. When it came to:
this.gridViewModel = new ko.simpleGrid.viewModel({
data: this.items, ....
it threw an exception Unable to get property 'viewModel' of undefined or
null reference. I stepped through and found that ko.simpleGrid is
undefined.
Must any other files be added or is simpleGrid available from the standard
Knockout.js library?
I want to try the simpleGrid in a HotTowel project. When it came to:
this.gridViewModel = new ko.simpleGrid.viewModel({
data: this.items, ....
it threw an exception Unable to get property 'viewModel' of undefined or
null reference. I stepped through and found that ko.simpleGrid is
undefined.
Must any other files be added or is simpleGrid available from the standard
Knockout.js library?
Wednesday, 28 August 2013
Get `transform: scale(...)` to position elements the same as `zoom: ...`
Get `transform: scale(...)` to position elements the same as `zoom: ...`
The best way to explain is probably with a picture.
Here is how my elements are positioned when applying:
.shape {
transform: scale(0.5);
transform-origin: 0 0;
}
And here is how they are positioned when applying:
.shape {
zoom: 0.5;
}
Notice that scale lays the components out as if they were their original
size where as zoom lays them out based on their scaled down size.
Unfortunately zoom is not supported in Firefox (AFAIK) so I need to get
the layout behavior of zoom when applying transform: scale...
Any ideas? I'd like to avoid absolute positioning as much as possible.
The best way to explain is probably with a picture.
Here is how my elements are positioned when applying:
.shape {
transform: scale(0.5);
transform-origin: 0 0;
}
And here is how they are positioned when applying:
.shape {
zoom: 0.5;
}
Notice that scale lays the components out as if they were their original
size where as zoom lays them out based on their scaled down size.
Unfortunately zoom is not supported in Firefox (AFAIK) so I need to get
the layout behavior of zoom when applying transform: scale...
Any ideas? I'd like to avoid absolute positioning as much as possible.
Which is the technology behind jacquico
Which is the technology behind jacquico
I was wondering how this site http://www.jacquico.com/ is built. I mean
which is the technology behind.
Thanks in advance
I was wondering how this site http://www.jacquico.com/ is built. I mean
which is the technology behind.
Thanks in advance
Windows context menu option for "Copy a link to file"
Windows context menu option for "Copy a link to file"
Is there a utility to add a context menu option for copying a link to a
file to include in a plaintext email (or something that accomplishes the
same thing in Outlook) for Windows 7?
For example, if I have a mounted Windows network share \\foo and there was
a file on it bar baz, I would like to get file:///\\foo\bar%20baz. Ideally
this would work with mounted FTP drives, etc., but what I really would
like it for is network shares.
Shift-right click gives a "Copy as path" option, but this will generate a
path like "Q:\bar baz", not file:///\\foo\bar%20baz. Outlook has a link
function, but it does not work with plaintext email.
Is there a utility to add a context menu option for copying a link to a
file to include in a plaintext email (or something that accomplishes the
same thing in Outlook) for Windows 7?
For example, if I have a mounted Windows network share \\foo and there was
a file on it bar baz, I would like to get file:///\\foo\bar%20baz. Ideally
this would work with mounted FTP drives, etc., but what I really would
like it for is network shares.
Shift-right click gives a "Copy as path" option, but this will generate a
path like "Q:\bar baz", not file:///\\foo\bar%20baz. Outlook has a link
function, but it does not work with plaintext email.
Private Methods can be made static
Private Methods can be made static
I had installed resharper with VS2010. It is notifying as Method
'GetFeeds' can be made static. Why it is saying like that?
private DataTable GetFeeds(Feed feed)
{
--code
}
I had installed resharper with VS2010. It is notifying as Method
'GetFeeds' can be made static. Why it is saying like that?
private DataTable GetFeeds(Feed feed)
{
--code
}
Tuesday, 27 August 2013
How to assign hyperlink to a variable in perl?
How to assign hyperlink to a variable in perl?
I have a variable in perl where i need to assign a hyperlink like below
and when this variable is printed it needs to display the hyperlink. When
the variable is displayed it shows nothing. How to do it. The below code
didn't work. Please help.
my $Results_31 = "\<a
href=\"http:\/\/xx.xxx.xx.xx\/Android\/31BX.html\"\>31\-Results<\/a>";
I have a variable in perl where i need to assign a hyperlink like below
and when this variable is printed it needs to display the hyperlink. When
the variable is displayed it shows nothing. How to do it. The below code
didn't work. Please help.
my $Results_31 = "\<a
href=\"http:\/\/xx.xxx.xx.xx\/Android\/31BX.html\"\>31\-Results<\/a>";
Redirecting A Specific Tab Firefox Add On
Redirecting A Specific Tab Firefox Add On
I'm writing an exntension for firefox. Basically by using
getElementsByClassName, I'm searching for a specific class and if there's
any hit, I'm redirecting the page by using: gBrowser.loadURI The problem
is if I open a link by middle mouse button, that link is opened in the
background tab. So if there's any hit for the above class criteria in that
page, the active tab is redirected instead of the bacground one, which is
a wrong behaviour. So basically I want to use a similar loadURI function
but for a specific tab, not the current active tab. Instead of loadURI I
can also use window.location = "http://www.google.com/". But somehow when
I use window.location, every button in the ff window disappears, as if
full view. Do you have any idea for redirecting the inactive tab?
I'm writing an exntension for firefox. Basically by using
getElementsByClassName, I'm searching for a specific class and if there's
any hit, I'm redirecting the page by using: gBrowser.loadURI The problem
is if I open a link by middle mouse button, that link is opened in the
background tab. So if there's any hit for the above class criteria in that
page, the active tab is redirected instead of the bacground one, which is
a wrong behaviour. So basically I want to use a similar loadURI function
but for a specific tab, not the current active tab. Instead of loadURI I
can also use window.location = "http://www.google.com/". But somehow when
I use window.location, every button in the ff window disappears, as if
full view. Do you have any idea for redirecting the inactive tab?
What is the most up-to-date hastle-free way to move a wordpress MAMP site to a webspace on 1and1.com
What is the most up-to-date hastle-free way to move a wordpress MAMP site
to a webspace on 1and1.com
I've been searching for days to find the easiest, most newb-friendly set
of directions to get a wordpress 3.6 site done on MAMP to a webspace like
1and1.com, as I am a total beginner when it comes to wordpress. The
wordpress Codex I didn't find useful with regards to this issue as there
are many explanations and nothing broken down into simple, detailed, easy
to understand way. I've searched thread after thread and blog post after
blog post and most of them are not detailed enough or out of date. If
anyone would care to share their insight on their preferred methods for
moving a MAMP site to a webspace it would be greatly appreciated.
The closest one I found was:
http://www.jasonbobich.com/web-design/moving-wordpress-to-a-new-server/
but it suggests that you should use this plugin:
http://interconnectit.com/products/search-and-replace-for-wordpress-databases/
and I have no idea how to use it (they only offer a brief 3 paragraph
explanation on its usage)
Is this a good reference to go by? I just wanna make sure because it seems
like a daunting task where the smallest trace of human error ruins your
day. what would be great is something like a one-click solution (input
necessary fields like URLs and click a button that says "Move Site") but I
haven't been able to come across one that works - the Duplicator plugin
came recommended for something like this but it also came abhorred by
others so I'm a little wary on using it.
What are your thoughts? What should I do??
Thanks
to a webspace on 1and1.com
I've been searching for days to find the easiest, most newb-friendly set
of directions to get a wordpress 3.6 site done on MAMP to a webspace like
1and1.com, as I am a total beginner when it comes to wordpress. The
wordpress Codex I didn't find useful with regards to this issue as there
are many explanations and nothing broken down into simple, detailed, easy
to understand way. I've searched thread after thread and blog post after
blog post and most of them are not detailed enough or out of date. If
anyone would care to share their insight on their preferred methods for
moving a MAMP site to a webspace it would be greatly appreciated.
The closest one I found was:
http://www.jasonbobich.com/web-design/moving-wordpress-to-a-new-server/
but it suggests that you should use this plugin:
http://interconnectit.com/products/search-and-replace-for-wordpress-databases/
and I have no idea how to use it (they only offer a brief 3 paragraph
explanation on its usage)
Is this a good reference to go by? I just wanna make sure because it seems
like a daunting task where the smallest trace of human error ruins your
day. what would be great is something like a one-click solution (input
necessary fields like URLs and click a button that says "Move Site") but I
haven't been able to come across one that works - the Duplicator plugin
came recommended for something like this but it also came abhorred by
others so I'm a little wary on using it.
What are your thoughts? What should I do??
Thanks
RichTextBoxPrintCtrl Printing Issue
RichTextBoxPrintCtrl Printing Issue
This is my first posting and my programmer status is keen amateur.
I have created a c# Form RichTextBoxPrintCtrl editor with print capability
via a printDialog and printDocument control. Before I print I want to
determine the page size (based on the number of characters) per print
page. The code which calls the RichTextBoxPrintCtrl dll to get this info
is:
checkPrint = richTextBoxPrintCtrl1.Print(checkPrint, textEnd, e); with e
being the printDocument PrintPageEventArgs.
The only way I can see to do this appears to be to actually print the
document.
Is there a way to capture the printDocument PrintPageEventArgs and use
them in the above code without actually printing?
The reason I want to do this is to have the ability to use the page from
and page to facility within the printDialog. Any help would be
appreciated.
This is my first posting and my programmer status is keen amateur.
I have created a c# Form RichTextBoxPrintCtrl editor with print capability
via a printDialog and printDocument control. Before I print I want to
determine the page size (based on the number of characters) per print
page. The code which calls the RichTextBoxPrintCtrl dll to get this info
is:
checkPrint = richTextBoxPrintCtrl1.Print(checkPrint, textEnd, e); with e
being the printDocument PrintPageEventArgs.
The only way I can see to do this appears to be to actually print the
document.
Is there a way to capture the printDocument PrintPageEventArgs and use
them in the above code without actually printing?
The reason I want to do this is to have the ability to use the page from
and page to facility within the printDialog. Any help would be
appreciated.
32 Bits OpenGL into 64 Bit Ubuntu 12.04 PlayonlInux
32 Bits OpenGL into 64 Bit Ubuntu 12.04 PlayonlInux
I'm using Ubuntu 12.04 64 bits. I have installed Playonlinux, but when I
run it, it says: Unable to find 32 bit OpenGl libraries. I see I need
ia32-libs to run 32bits apps. I have installed ia32-libs and
ia32-libs:i386, but Playonlinux is still saying the same.
How can I solve that?
I'm using Ubuntu 12.04 64 bits. I have installed Playonlinux, but when I
run it, it says: Unable to find 32 bit OpenGl libraries. I see I need
ia32-libs to run 32bits apps. I have installed ia32-libs and
ia32-libs:i386, but Playonlinux is still saying the same.
How can I solve that?
Execute onCreate of activity of layout included in ViewFlipper
Execute onCreate of activity of layout included in ViewFlipper
I'm trying to use ViewFlipperin my app but I'm having some problems.
What I want is:
After login (first view), go to ViewFlipper, where I have included two
layouts. The first one, which I want to show, is a
SherlockFragmentActivitywith FragmentPagerAdapter. Without ViewFlipperit
is running ok.
The problem is:
How can I call onCreate method of my SherlockFragmentActivity? As it is
not called, it's not showing anything.
Code:
view_flipper.xml
<?xml version="1.0" encoding="utf-8"?>
<ViewFlipper xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/flipper"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<include
android:id="@+id/first"
layout="@layout/fragment_pager" />
<include
android:id="@+id/second"
layout="@layout/activity_factura" />
</ViewFlipper>
FlipperActivity.java
public class FlipperActivity extends SherlockActivity {
ViewFlipper flipper;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_flipper);
}
}
fragment_pager.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context=".TabsFacturasActivity" >
<com.viewpagerindicator.TitlePageIndicator
android:id="@+id/indicator"
android:padding="10dip"
android:layout_height="wrap_content"
android:layout_width="fill_parent" />
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#1184A4E8" />
</LinearLayout>
I'm trying to use ViewFlipperin my app but I'm having some problems.
What I want is:
After login (first view), go to ViewFlipper, where I have included two
layouts. The first one, which I want to show, is a
SherlockFragmentActivitywith FragmentPagerAdapter. Without ViewFlipperit
is running ok.
The problem is:
How can I call onCreate method of my SherlockFragmentActivity? As it is
not called, it's not showing anything.
Code:
view_flipper.xml
<?xml version="1.0" encoding="utf-8"?>
<ViewFlipper xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/flipper"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<include
android:id="@+id/first"
layout="@layout/fragment_pager" />
<include
android:id="@+id/second"
layout="@layout/activity_factura" />
</ViewFlipper>
FlipperActivity.java
public class FlipperActivity extends SherlockActivity {
ViewFlipper flipper;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.view_flipper);
}
}
fragment_pager.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical"
tools:context=".TabsFacturasActivity" >
<com.viewpagerindicator.TitlePageIndicator
android:id="@+id/indicator"
android:padding="10dip"
android:layout_height="wrap_content"
android:layout_width="fill_parent" />
<android.support.v4.view.ViewPager
android:id="@+id/pager"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1"
android:background="#1184A4E8" />
</LinearLayout>
cleare python idle using command
cleare python idle using command
I searched a lot but could not find any command to clear python idle(GUI)
can anyone help me and tell me if there is any command to clear the python
IDLE. Your help will be appreciated a lot.
I searched a lot but could not find any command to clear python idle(GUI)
can anyone help me and tell me if there is any command to clear the python
IDLE. Your help will be appreciated a lot.
Monday, 26 August 2013
JFreeChart Margin
JFreeChart Margin
I am very new to this.
I am using jasperreport to create a line chart for my webapps.
I have successfully passed the dataset to the compiled Jasperreport
(created in iReport) and can see the data correctly.
However, I want to do some customization on the margin.
The value shown on the line chart is trimming for the highest value as
there is no margin.
The X-Axis label is coming after few empty space from Y-Axis 0 value. I
want to remove that margin and start the X-Axis from very close to the
meeting point of X & Y.
Please see the picture.
I am using customized class which is defined in my webspps. I am able to
change the font size and rotation of the label but don't know how to
adjust margin.
public class LineChartCustomizer implements JRChartCustomizer {
private static Log log = LogFactory.getLog(LineChartCustomizer.class);
@Override
public void customize(JFreeChart jFreeChart, JRChart jrChart) {
CategoryPlot plot = jFreeChart.getCategoryPlot();
DecimalFormat dfKey = new DecimalFormat("###,###");
StandardCategoryItemLabelGenerator labelGenerator = new
StandardCategoryItemLabelGenerator("{2}", dfKey);
/*
* {0} - label would be equal to Series expression,
* {1} - label would be equal to Category expression,
* {2} - label would be equal to Value expression
*
*/
LineAndShapeRenderer renderer = new LineAndShapeRenderer();
renderer.setBaseItemLabelsVisible(true);
renderer.setBaseItemLabelGenerator(labelGenerator);
renderer.setBaseItemLabelFont(new java.awt.Font("SansSerif",
java.awt.Font.PLAIN, 4));
/*
renderer.setSeriesPositiveItemLabelPosition(0,
new
ItemLabelPosition(ItemLabelAnchor.OUTSIDE3,
TextAnchor.BOTTOM_LEFT,
TextAnchor.BOTTOM_LEFT,
Math.PI));*/
renderer.setSeriesShape(0, ShapeUtilities.createDiamond(1F));
plot.setRenderer(renderer);
}
}
See the image : http://tinypic.com/r/2lidiz6/5
I am very new to this.
I am using jasperreport to create a line chart for my webapps.
I have successfully passed the dataset to the compiled Jasperreport
(created in iReport) and can see the data correctly.
However, I want to do some customization on the margin.
The value shown on the line chart is trimming for the highest value as
there is no margin.
The X-Axis label is coming after few empty space from Y-Axis 0 value. I
want to remove that margin and start the X-Axis from very close to the
meeting point of X & Y.
Please see the picture.
I am using customized class which is defined in my webspps. I am able to
change the font size and rotation of the label but don't know how to
adjust margin.
public class LineChartCustomizer implements JRChartCustomizer {
private static Log log = LogFactory.getLog(LineChartCustomizer.class);
@Override
public void customize(JFreeChart jFreeChart, JRChart jrChart) {
CategoryPlot plot = jFreeChart.getCategoryPlot();
DecimalFormat dfKey = new DecimalFormat("###,###");
StandardCategoryItemLabelGenerator labelGenerator = new
StandardCategoryItemLabelGenerator("{2}", dfKey);
/*
* {0} - label would be equal to Series expression,
* {1} - label would be equal to Category expression,
* {2} - label would be equal to Value expression
*
*/
LineAndShapeRenderer renderer = new LineAndShapeRenderer();
renderer.setBaseItemLabelsVisible(true);
renderer.setBaseItemLabelGenerator(labelGenerator);
renderer.setBaseItemLabelFont(new java.awt.Font("SansSerif",
java.awt.Font.PLAIN, 4));
/*
renderer.setSeriesPositiveItemLabelPosition(0,
new
ItemLabelPosition(ItemLabelAnchor.OUTSIDE3,
TextAnchor.BOTTOM_LEFT,
TextAnchor.BOTTOM_LEFT,
Math.PI));*/
renderer.setSeriesShape(0, ShapeUtilities.createDiamond(1F));
plot.setRenderer(renderer);
}
}
See the image : http://tinypic.com/r/2lidiz6/5
Javascript: detecting if two div's are too close or collide/overlap
Javascript: detecting if two div's are too close or collide/overlap
I'm trying to detect if two given DIV's are too close or collide/overlap .
I have the below codepen which tries to generate 20 random DIV's and only
append them to body if their position isn't too close to other existing
DIVs. That's the idea but it doesn't work as expected where i get DIV's
that get through with close/overlapping positions to existing DIVs. (run
it multiple times if first time is perfect and you should come across it).
http://codepen.io/anon/pen/yqJHp
Can anyone see the mistake and way to make it work?
Thanks
I'm trying to detect if two given DIV's are too close or collide/overlap .
I have the below codepen which tries to generate 20 random DIV's and only
append them to body if their position isn't too close to other existing
DIVs. That's the idea but it doesn't work as expected where i get DIV's
that get through with close/overlapping positions to existing DIVs. (run
it multiple times if first time is perfect and you should come across it).
http://codepen.io/anon/pen/yqJHp
Can anyone see the mistake and way to make it work?
Thanks
HttpContext.Current is null in custom IHttpHandlerFactory
HttpContext.Current is null in custom IHttpHandlerFactory
public class HandlerFactory : IHttpHandlerFactory
{
public IHttpHandler GetHandler(HttpContext context, string
requestType, string url, string pathTranslated)
{
// lots of code
}
public void ReleaseHandler(IHttpHandler handler)
{
// HttpContext.Current is always null here.
}
}
How can I make HttpContext.Current available (or use alternative approach
to store per-request variables such that they can be retrieved in
ReleaseHandler)?
public class HandlerFactory : IHttpHandlerFactory
{
public IHttpHandler GetHandler(HttpContext context, string
requestType, string url, string pathTranslated)
{
// lots of code
}
public void ReleaseHandler(IHttpHandler handler)
{
// HttpContext.Current is always null here.
}
}
How can I make HttpContext.Current available (or use alternative approach
to store per-request variables such that they can be retrieved in
ReleaseHandler)?
Ways to remove android device encryption
Ways to remove android device encryption
Since I still encounter issues with modified boot images and recovery
images I want to remove the device encryption from my Nexus 4 (running
4.3).
I known that there is no "official" way to to this but since this is an
encryption it can be reverted. So please don't tell me that it is
impossible (I already know that android don't want you to do this).
So I came up with two ideas but I could not find anyone who already did
this and want to be sure before wiping my data partition. My device is not
rooted but the bootloader is unlocked.
Making a backup with adb backup, format the data partition and restore the
backup. But I could imagine that adb is unable to restore backups on
non-encrypted devices if they were made on an encrypted on. (Can tell me
for sure?)
Starting a modified boot image with fastboot that just decrypts the data
partition (should be perfectly possbile but I havn't seen such a tool)
Any other idea?
Since I still encounter issues with modified boot images and recovery
images I want to remove the device encryption from my Nexus 4 (running
4.3).
I known that there is no "official" way to to this but since this is an
encryption it can be reverted. So please don't tell me that it is
impossible (I already know that android don't want you to do this).
So I came up with two ideas but I could not find anyone who already did
this and want to be sure before wiping my data partition. My device is not
rooted but the bootloader is unlocked.
Making a backup with adb backup, format the data partition and restore the
backup. But I could imagine that adb is unable to restore backups on
non-encrypted devices if they were made on an encrypted on. (Can tell me
for sure?)
Starting a modified boot image with fastboot that just decrypts the data
partition (should be perfectly possbile but I havn't seen such a tool)
Any other idea?
Sharing authentication between 3 websites
Sharing authentication between 3 websites
I have a main website, with 2 sub-sites. I want to create a simple way to
authenticate on a website such that I can view the other 2 sub-sites.
THe websites are setupa as follows:
www.example.com/
www.example.com/subsite1
www.example.com/subsite2
As a further requirement, subsite1 and subsite2 may be re-used on a
different website.
Could I use the built in Authentication module in ASP.NET for this? Or do
I have to create my own custom cookie?
I have a main website, with 2 sub-sites. I want to create a simple way to
authenticate on a website such that I can view the other 2 sub-sites.
THe websites are setupa as follows:
www.example.com/
www.example.com/subsite1
www.example.com/subsite2
As a further requirement, subsite1 and subsite2 may be re-used on a
different website.
Could I use the built in Authentication module in ASP.NET for this? Or do
I have to create my own custom cookie?
Swapping file names in the same folder C++
Swapping file names in the same folder C++
I had two set of files in the same folder may or may not be equal in
number. One set of files contains the word "rect" as a part of their names
and the other one contain "circle" in their names.
I need to rename all the files which contain "rect" with "circle" by
retaining the rest part of the file name and vice versa. What is the best
method to do this?
I had two set of files in the same folder may or may not be equal in
number. One set of files contains the word "rect" as a part of their names
and the other one contain "circle" in their names.
I need to rename all the files which contain "rect" with "circle" by
retaining the rest part of the file name and vice versa. What is the best
method to do this?
I want to create menu for category archive
I want to create menu for category archive
I want to create menu for category archive based on tags which will refine
result for that category only in WordPress
I want to create menu for category archive based on tags which will refine
result for that category only in WordPress
Sunday, 25 August 2013
Fill Dropdownlist with values from sql database in MVC4 using c#
Fill Dropdownlist with values from sql database in MVC4 using c#
i have a table in my database which i select all Mem_NA to fill it in my
dropdownlist in my view.
i can´t understand how can i fill the values in there.someone can give me
a hand?
My Model
public class MemberBasicData
{
public int Id { get; set; }
public string Mem_NA { get; set; }
public string Mem_Occ { get; set; }
}
public List<MemberBasicData> GetAllMembers()
{
DateTime today = DateTime.Now;
List<MemberBasicData> mbd = new List<MemberBasicData>();
using (SqlConnection con = new
SqlConnection(Config.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT
Id,Mem_NA,Mem_Occ FROM Mem_Basic", con))
{
try
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
MemberBasicData mb = new MemberBasicData();
mb.Id = (int)reader["Id"];
mb.Mem_NA = (string)reader["Mem_NA"];
mb.Mem_Occ =(string)reader["Mem_Occ"];
mbd.Add(mb);
}
}
catch (Exception e) { throw e; }
finally { if (con.State ==
System.Data.ConnectionState.Open) con.Close(); }
return mbd;
}
}
}
GetAllMembers() function is an IEnumerable fuction which i was used for
get all details of members. Can i use the same function for filling the
dropdown list. My controller
public ActionResult Register()
{
return View(new Member());
}
And View
@Html.DropDownListFor("-- Select --", new SelectList("")) <=== ???? i
dont know
i have a table in my database which i select all Mem_NA to fill it in my
dropdownlist in my view.
i can´t understand how can i fill the values in there.someone can give me
a hand?
My Model
public class MemberBasicData
{
public int Id { get; set; }
public string Mem_NA { get; set; }
public string Mem_Occ { get; set; }
}
public List<MemberBasicData> GetAllMembers()
{
DateTime today = DateTime.Now;
List<MemberBasicData> mbd = new List<MemberBasicData>();
using (SqlConnection con = new
SqlConnection(Config.ConnectionString))
{
using (SqlCommand cmd = new SqlCommand("SELECT
Id,Mem_NA,Mem_Occ FROM Mem_Basic", con))
{
try
{
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
MemberBasicData mb = new MemberBasicData();
mb.Id = (int)reader["Id"];
mb.Mem_NA = (string)reader["Mem_NA"];
mb.Mem_Occ =(string)reader["Mem_Occ"];
mbd.Add(mb);
}
}
catch (Exception e) { throw e; }
finally { if (con.State ==
System.Data.ConnectionState.Open) con.Close(); }
return mbd;
}
}
}
GetAllMembers() function is an IEnumerable fuction which i was used for
get all details of members. Can i use the same function for filling the
dropdown list. My controller
public ActionResult Register()
{
return View(new Member());
}
And View
@Html.DropDownListFor("-- Select --", new SelectList("")) <=== ???? i
dont know
How can a module with setup.py installed using Cython?
How can a module with setup.py installed using Cython?
First I've no experience with python. I just want to install a module in
blender which comes with a setup.py. It seems that I need Cython to
install that. I added Cython to PYTHONPATH and the bin folder to the PATH.
This error is shown:
python setup.py install
running install
running build
running build_ext
Traceback (most recent call last):
File "setup.py", line 17, in <module>
cmdclass = {'build_ext': build_ext})
File "C:\Python33\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "C:\Python33\lib\distutils\dist.py", line 917, in run_commands
self.run_command(cmd)
File "C:\Python33\lib\distutils\dist.py", line 936, in run_command
cmd_obj.run()
File "C:\Python33\lib\distutils\command\install.py", line 569, in run
self.run_command('build')
File "C:\Python33\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "C:\Python33\lib\distutils\dist.py", line 936, in run_command
cmd_obj.run()
File "C:\Python33\lib\distutils\command\build.py", line 126, in run
self.run_command(cmd_name)
File "C:\Python33\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "C:\Python33\lib\distutils\dist.py", line 936, in run_command
cmd_obj.run()
File "C:\Cython-0.19.1\Cython\Distutils\build_ext.py", line 163, in run
_build_ext.build_ext.run(self)
File "C:\Python33\lib\distutils\command\build_ext.py", line 354, in run
self.build_extensions()
File "C:\Cython-0.19.1\Cython\Distutils\build_ext.py", line 170, in
build_extensions
ext.sources = self.cython_sources(ext.sources, ext)
File "C:\Cython-0.19.1\Cython\Distutils\build_ext.py", line 181, in
cython_sources
from Cython.Compiler.Main \
File "C:\Cython-0.19.1\Cython\Compiler\Main.py", line 302
except UnicodeDecodeError#, e:
^
SyntaxError: invalid syntax
Versions are: Python 3.3 / Windows7 64 / Cython-0.19.1
Any ideas, what should I try?
First I've no experience with python. I just want to install a module in
blender which comes with a setup.py. It seems that I need Cython to
install that. I added Cython to PYTHONPATH and the bin folder to the PATH.
This error is shown:
python setup.py install
running install
running build
running build_ext
Traceback (most recent call last):
File "setup.py", line 17, in <module>
cmdclass = {'build_ext': build_ext})
File "C:\Python33\lib\distutils\core.py", line 148, in setup
dist.run_commands()
File "C:\Python33\lib\distutils\dist.py", line 917, in run_commands
self.run_command(cmd)
File "C:\Python33\lib\distutils\dist.py", line 936, in run_command
cmd_obj.run()
File "C:\Python33\lib\distutils\command\install.py", line 569, in run
self.run_command('build')
File "C:\Python33\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "C:\Python33\lib\distutils\dist.py", line 936, in run_command
cmd_obj.run()
File "C:\Python33\lib\distutils\command\build.py", line 126, in run
self.run_command(cmd_name)
File "C:\Python33\lib\distutils\cmd.py", line 313, in run_command
self.distribution.run_command(command)
File "C:\Python33\lib\distutils\dist.py", line 936, in run_command
cmd_obj.run()
File "C:\Cython-0.19.1\Cython\Distutils\build_ext.py", line 163, in run
_build_ext.build_ext.run(self)
File "C:\Python33\lib\distutils\command\build_ext.py", line 354, in run
self.build_extensions()
File "C:\Cython-0.19.1\Cython\Distutils\build_ext.py", line 170, in
build_extensions
ext.sources = self.cython_sources(ext.sources, ext)
File "C:\Cython-0.19.1\Cython\Distutils\build_ext.py", line 181, in
cython_sources
from Cython.Compiler.Main \
File "C:\Cython-0.19.1\Cython\Compiler\Main.py", line 302
except UnicodeDecodeError#, e:
^
SyntaxError: invalid syntax
Versions are: Python 3.3 / Windows7 64 / Cython-0.19.1
Any ideas, what should I try?
What will be the optimized and fast way to generate 1 million random points in Python?
What will be the optimized and fast way to generate 1 million random
points in Python?
Basically I need over a million points on x-y plane. I am thinking about
first generating 1 million points in range -x to x, another million in
range y to -y and then coupling them together. What will be optimized and
fast way to do this? In random.randrange good enough?
points in Python?
Basically I need over a million points on x-y plane. I am thinking about
first generating 1 million points in range -x to x, another million in
range y to -y and then coupling them together. What will be optimized and
fast way to do this? In random.randrange good enough?
Saturday, 24 August 2013
Error when using namespaces - class not declared
Error when using namespaces - class not declared
I'm new to C++ and using namespaces and I can't see what I'm doing wrong
here. When I compile the code below, I get the error:
error: 'Menu' has not been declared
Here is my header file Menu.hpp
#ifndef MENU_H //"Header guard"
#define MENU_H
namespace View
{
class Menu
{
void startMenu();
};
}
I'm new to C++ and using namespaces and I can't see what I'm doing wrong
here. When I compile the code below, I get the error:
error: 'Menu' has not been declared
Here is my header file Menu.hpp
#ifndef MENU_H //"Header guard"
#define MENU_H
namespace View
{
class Menu
{
void startMenu();
};
}
Can i set entry point at code in PE headers?
Can i set entry point at code in PE headers?
If i set something like 0x00000040(my code is located at this address),
then program crush with error: "The application was unable to start
correctly (0xc000007b)" But if i jmp frome code section on 0x00400040 then
all right.
Why i got error with that strange addr? (0xc000007b) Is it possible to
start execution of program from code which is located outside sections?
I use Win8 OS.
If i set something like 0x00000040(my code is located at this address),
then program crush with error: "The application was unable to start
correctly (0xc000007b)" But if i jmp frome code section on 0x00400040 then
all right.
Why i got error with that strange addr? (0xc000007b) Is it possible to
start execution of program from code which is located outside sections?
I use Win8 OS.
Finding Roles MVC 4 Simple Membership
Finding Roles MVC 4 Simple Membership
My Action
[Authorize(Roles = "Admin")]
public ActionResult Index()
{
using (var ctx = new _dbContext())
{
return View(ctx.UserProfiles.OrderBy(x => x.UserId).ToList());
}
}
I want to display roles with UserId and UserName how can i do that??
My Action
[Authorize(Roles = "Admin")]
public ActionResult Index()
{
using (var ctx = new _dbContext())
{
return View(ctx.UserProfiles.OrderBy(x => x.UserId).ToList());
}
}
I want to display roles with UserId and UserName how can i do that??
Intel 520 240Gb SSD in Dell XPS l702x Disappeared
Intel 520 240Gb SSD in Dell XPS l702x Disappeared
I installed an intel 520 SSD in my laptop about a month ago. It' been
working fine until today.
I was watching a film, I paused it in the middle to answer a phone call,
when I returned my laptop had gone to sleep. When I turned it back on
Windows Media Player had frozen, then my whole computer became completely
unresponsive. I held the power button down until my laptop powered off
since this seemed to be my only option.
When I powered on again, my SSD was no longer present in the BIOS.
I have done some searching and found plenty of similar problems with SSDs
becoming invisible but I'd like to know what steps I can take to attempt
to recover the SSD.
I installed an intel 520 SSD in my laptop about a month ago. It' been
working fine until today.
I was watching a film, I paused it in the middle to answer a phone call,
when I returned my laptop had gone to sleep. When I turned it back on
Windows Media Player had frozen, then my whole computer became completely
unresponsive. I held the power button down until my laptop powered off
since this seemed to be my only option.
When I powered on again, my SSD was no longer present in the BIOS.
I have done some searching and found plenty of similar problems with SSDs
becoming invisible but I'd like to know what steps I can take to attempt
to recover the SSD.
Image Grid Fluid Layout (Responsive)
Image Grid Fluid Layout (Responsive)
I am working on image grid(4 columns) with fluid layout. In jsfiddle
currently the height is set to auto but it's not coming the way I am
expecting because the image dimensions are different. The image size is
not proportional after fixing the height. I know, it will work properly
when image(width/height) will be equal but I don't want to do this because
images will be coming dynamically(same width/different height). Is there
any way it can be fixed for different image dimensions? Fiddle below
img{
width:100%;
//height:150px;
height:auto;
}
JSFiddle
I am working on image grid(4 columns) with fluid layout. In jsfiddle
currently the height is set to auto but it's not coming the way I am
expecting because the image dimensions are different. The image size is
not proportional after fixing the height. I know, it will work properly
when image(width/height) will be equal but I don't want to do this because
images will be coming dynamically(same width/different height). Is there
any way it can be fixed for different image dimensions? Fiddle below
img{
width:100%;
//height:150px;
height:auto;
}
JSFiddle
e books,websites,magazines,applications etc to learn qml
e books,websites,magazines,applications etc to learn qml
i wish to learn qml so that i could code in Ubuntu sdk effectively.
so can you name some books,websites,apps etc so i could learn qml?
i have good experience of programming in c++.
but not so in python.qml being part of Java,can knowledge of c++ help in
learning qml?( because people say its easy to learn Java having knowledge
of c++)
i can't have a professional course because I'm currently completing my
junior college.lol.
i think i could make some money for my future education by programming for
android and UBUNTU
i wish to learn qml so that i could code in Ubuntu sdk effectively.
so can you name some books,websites,apps etc so i could learn qml?
i have good experience of programming in c++.
but not so in python.qml being part of Java,can knowledge of c++ help in
learning qml?( because people say its easy to learn Java having knowledge
of c++)
i can't have a professional course because I'm currently completing my
junior college.lol.
i think i could make some money for my future education by programming for
android and UBUNTU
TinyMCE: buttons does not work after ajax requests
TinyMCE: buttons does not work after ajax requests
I'm using TinyMCE and wicket/jquery requests together. TinyMCE works fine
the first time when it is loaded - every buttons work well
Scenario:
Given
The page contains a form with fields: rating field and textarea (TinyMCE).
When
I click rating field to update the field,
Then
Wicket updated the field and returns only it (not the whole form). And
after click on the TinyMCE buttons to change aligns of text for instance
then nothing happens (BAD!!! the text should apply aligns)
PS: when I click a button in TinyMCE and press ENTER then it starts to
apply or menu starts to open.
What is the strange behavior?
TinyMCE 4.0.4 Wicket: 6.9.0 using jQuery 10.x
I'm using TinyMCE and wicket/jquery requests together. TinyMCE works fine
the first time when it is loaded - every buttons work well
Scenario:
Given
The page contains a form with fields: rating field and textarea (TinyMCE).
When
I click rating field to update the field,
Then
Wicket updated the field and returns only it (not the whole form). And
after click on the TinyMCE buttons to change aligns of text for instance
then nothing happens (BAD!!! the text should apply aligns)
PS: when I click a button in TinyMCE and press ENTER then it starts to
apply or menu starts to open.
What is the strange behavior?
TinyMCE 4.0.4 Wicket: 6.9.0 using jQuery 10.x
PHP - Issue in array
PHP - Issue in array
i have an array code, like :
$responeArray = array();
$_counter = 0;
foreach($xmlResp->readCalls->classify as $readCalls) {
$ClassificationClass = array();
foreach($readCalls->classification->{'class'} as $classes) {
$ClassificationClass[] = implode(" ",array('p' =>
(string)$classes['p']));
}
$responeArray[] = $ClassificationClass;
$_counter++;
}
return $responeArray;
that will give result like
Array
(
[0] => Array
(
[0] => 0.999999
[1] => 5.65423e-007
[2] => 2.3301e-008
)
[1] => Array
(
[0] => 0.333333
[1] => 0.333333
[2] => 0.333333
)
[2] => Array
(
[0] => 1.19172e-007
[1] => 0.999993
[2] => 6.75659e-006
)
)
my purpose to get result like
0.999999 5.65423e-007 2.3301e-008
...
1.19172e-007 0.999993 6.75659e-006
i try using this
$responeArray = array();
$_counter = 0;
foreach($xmlResp->readCalls->classify as $readCalls) {
$ClassificationClass = array();
foreach($readCalls->classification->{'class'} as $classes) {
$ClassificationClass[] = implode(" ",array('p' =>
(string)$classes['p']));
}
$responeArray[] = $ClassificationClass;
$nilaineg = $ClassificationClass[0];
$nilainet = $ClassificationClass[1];
$nilaipos = $ClassificationClass[2];
$_counter++;
}
return $nilaineg.' '.$nilainet.' '.$nilaipos;
but code above just result :
1.19172e-007 0.999993 6.75659e-006
Am i missing something? Sorry for the noobs, i just learn about programming.
Thanks for your response.
i have an array code, like :
$responeArray = array();
$_counter = 0;
foreach($xmlResp->readCalls->classify as $readCalls) {
$ClassificationClass = array();
foreach($readCalls->classification->{'class'} as $classes) {
$ClassificationClass[] = implode(" ",array('p' =>
(string)$classes['p']));
}
$responeArray[] = $ClassificationClass;
$_counter++;
}
return $responeArray;
that will give result like
Array
(
[0] => Array
(
[0] => 0.999999
[1] => 5.65423e-007
[2] => 2.3301e-008
)
[1] => Array
(
[0] => 0.333333
[1] => 0.333333
[2] => 0.333333
)
[2] => Array
(
[0] => 1.19172e-007
[1] => 0.999993
[2] => 6.75659e-006
)
)
my purpose to get result like
0.999999 5.65423e-007 2.3301e-008
...
1.19172e-007 0.999993 6.75659e-006
i try using this
$responeArray = array();
$_counter = 0;
foreach($xmlResp->readCalls->classify as $readCalls) {
$ClassificationClass = array();
foreach($readCalls->classification->{'class'} as $classes) {
$ClassificationClass[] = implode(" ",array('p' =>
(string)$classes['p']));
}
$responeArray[] = $ClassificationClass;
$nilaineg = $ClassificationClass[0];
$nilainet = $ClassificationClass[1];
$nilaipos = $ClassificationClass[2];
$_counter++;
}
return $nilaineg.' '.$nilainet.' '.$nilaipos;
but code above just result :
1.19172e-007 0.999993 6.75659e-006
Am i missing something? Sorry for the noobs, i just learn about programming.
Thanks for your response.
Friday, 23 August 2013
Pass a value to the backend from custom options (dropdown) programatically
Pass a value to the backend from custom options (dropdown) programatically
I've got this problem that I can't solve. Partly because I can't explain
it with the right terms. I'm new to this so sorry for this clumsy
question.
Below you can see an overview of my goal.
In my product i have a dropdown custom option.
For Example: I have Color ,in that i have Red, White, Black
I want to set Set White is Default value Programatically.
I am using Magento CE1.7.0.2
Any Ideas ?
I've got this problem that I can't solve. Partly because I can't explain
it with the right terms. I'm new to this so sorry for this clumsy
question.
Below you can see an overview of my goal.
In my product i have a dropdown custom option.
For Example: I have Color ,in that i have Red, White, Black
I want to set Set White is Default value Programatically.
I am using Magento CE1.7.0.2
Any Ideas ?
Substring in a list of entries
Substring in a list of entries
I have a variable that contains a list of filenames and based on the
extension, I need to perform different action. I am not able to extract
the extension inside the loop
set BINARIES=file1.dll fil2.dll fil3.sys
:: for each file in list of binaries do
FOR %%G IN (%BINARIES%) DO (
:: if extension is dll
if /i [%%G:~-4%]==[.dll] (
echo dll file
) else (
echo sys file
)
)
If condition is always failing. How to correctly extract the extension.
I have a variable that contains a list of filenames and based on the
extension, I need to perform different action. I am not able to extract
the extension inside the loop
set BINARIES=file1.dll fil2.dll fil3.sys
:: for each file in list of binaries do
FOR %%G IN (%BINARIES%) DO (
:: if extension is dll
if /i [%%G:~-4%]==[.dll] (
echo dll file
) else (
echo sys file
)
)
If condition is always failing. How to correctly extract the extension.
Does mergePolicy has any effects on child moc?
Does mergePolicy has any effects on child moc?
Today I realized that there would never be conflicts between child moc and
parent moc because child moc does not treat parent moc's state as
snapshot. To my understanding, when child moc saves it just writes over
parent moc and no conflicts detection is done. So it means mergePolicy
does not make any sense to child moc. Is my understanding right?
Today I realized that there would never be conflicts between child moc and
parent moc because child moc does not treat parent moc's state as
snapshot. To my understanding, when child moc saves it just writes over
parent moc and no conflicts detection is done. So it means mergePolicy
does not make any sense to child moc. Is my understanding right?
Sort Custom Objects in Specific Order
Sort Custom Objects in Specific Order
I'm trying to figure out a tidy way of ordering objects in an array based
on a custom ordering scheme that I define.
In the example below if I printed out the "someText" values for each
object in my unsorted array, my desired output would be.
->Cow ->Cow ->Pig ->Dog
What would be my best option to achieve this custom sorting?
NSArray *scheme=@[@"Cow",@"Pig",@"Dog"];
@interface TestObject : NSObject
@property (strong, nonatomic) NSString *someText;
@end
@interface Test : NSObject
@property (strong, nonatomic) NSMutableArray *unSortedObjects;
@end
@implementation Test
-(void)setup
{
TestObject *t1=[Test alloc]init];
t1.someText=@"Dog";
[unSortedObjects addObject:t1];
TestObject *t2=[Test alloc]init];
t2.someText=@"Pig";
[unSortedObjects addObject:t2];
TestObject *t3=[Test alloc]init];
t3.someText=@"Cow";
[unSortedObjects addObject:t3];
t4.someText=@"Cow";
[unSortedObjects addObject:t4];
}
@end
I'm trying to figure out a tidy way of ordering objects in an array based
on a custom ordering scheme that I define.
In the example below if I printed out the "someText" values for each
object in my unsorted array, my desired output would be.
->Cow ->Cow ->Pig ->Dog
What would be my best option to achieve this custom sorting?
NSArray *scheme=@[@"Cow",@"Pig",@"Dog"];
@interface TestObject : NSObject
@property (strong, nonatomic) NSString *someText;
@end
@interface Test : NSObject
@property (strong, nonatomic) NSMutableArray *unSortedObjects;
@end
@implementation Test
-(void)setup
{
TestObject *t1=[Test alloc]init];
t1.someText=@"Dog";
[unSortedObjects addObject:t1];
TestObject *t2=[Test alloc]init];
t2.someText=@"Pig";
[unSortedObjects addObject:t2];
TestObject *t3=[Test alloc]init];
t3.someText=@"Cow";
[unSortedObjects addObject:t3];
t4.someText=@"Cow";
[unSortedObjects addObject:t4];
}
@end
Python modules not installing correctly
Python modules not installing correctly
So, I downloaded Python 2.7.5 on Ubuntu 12.04 and attempted to install the
module "lxml" using:
sudo pip install lxml
When I try:
pip freeze
it lists lxml as an installed package, however when I run a python script
using
help('modules')
lxml is no longer listed amongst the modules. I've checked using
python -V
and I'm apparently running Python 2.7.5. I've done some poking around and
nothing seems to quite suite what's going on with me here. I believe that
I'm perhaps installing modules to a different version of Python, and
that's the reason pip lists it as installed but not Python's help command.
I'm rather new to Linux so I'm not particularly sure what to do next. Any
help is appreciated, thanks!
So, I downloaded Python 2.7.5 on Ubuntu 12.04 and attempted to install the
module "lxml" using:
sudo pip install lxml
When I try:
pip freeze
it lists lxml as an installed package, however when I run a python script
using
help('modules')
lxml is no longer listed amongst the modules. I've checked using
python -V
and I'm apparently running Python 2.7.5. I've done some poking around and
nothing seems to quite suite what's going on with me here. I believe that
I'm perhaps installing modules to a different version of Python, and
that's the reason pip lists it as installed but not Python's help command.
I'm rather new to Linux so I'm not particularly sure what to do next. Any
help is appreciated, thanks!
Thursday, 22 August 2013
How do i prevent duplicate insertion from one table to another at client side using javascript
How do i prevent duplicate insertion from one table to another at client
side using javascript
This is my table code.The data gets inserted from another table into this
table but with duplicates.I want to insert rows without duplicates.Do i
need to use array and certain other javascript methods? function
onSelect(code,name,phone)
{
var newRow = document.all("listtable").insertRow(-1);
Cell1 = newRow.insertCell(0); Cell1.innerHTML = code;
Cell2 = newRow.insertCell(1); Cell2.innerHTML = name;
Cell3 = newRow.insertCell(2); Cell3.innerHTML = phone;
Cell4 = newRow.insertCell(3); Cell4.innerHTML = " X ";
}
side using javascript
This is my table code.The data gets inserted from another table into this
table but with duplicates.I want to insert rows without duplicates.Do i
need to use array and certain other javascript methods? function
onSelect(code,name,phone)
{
var newRow = document.all("listtable").insertRow(-1);
Cell1 = newRow.insertCell(0); Cell1.innerHTML = code;
Cell2 = newRow.insertCell(1); Cell2.innerHTML = name;
Cell3 = newRow.insertCell(2); Cell3.innerHTML = phone;
Cell4 = newRow.insertCell(3); Cell4.innerHTML = " X ";
}
PHP script not running nor posting to mysql
PHP script not running nor posting to mysql
I have a chat application with a mysql backend. I am trying to add a line
of code that will post " ...has joined the room" after the room change
function is completed.
Here is my code:
$PHP_PW = $_POST['password'];
$PHP_USER = $_POST['email'];
$PHP_ALIAS = $_POST['alias'];
$PHP_GENDER = $_POST['gender'];
$PHP_LON = $_POST['lon'];
$PHP_LAT = $_POST['lat'];
$PHP_STATUS = $_POST['status'];
$PHP_ROOM = $_POST['room'];
$PHP_ICON = $_POST['iconid'];
//$PHP_IP = $_SERVER['REMOTE_ADDR'];
$PHP_AGE = substr($_POST['age'],0,2);
$PHP_LOC = $_POST['location'];
$PHP_DOB = $_POST['dob'];
$PHP_IP = $_POST['device_id'];
if ($_POST['action']=="update")
{
if(!isset($PHP_USER))
{
echo "ERROR";
} else
{
if(isset($PHP_ROOM))
$update = mysql_query("UPDATE USER SET
room='$PHP_ROOM',lastupdate=NOW() WHERE email='$PHP_USER'")or
die("ERROR80");
$postmsg = mysql_query("INSERT INTO DATA
(msgid,userid,date,message,room) VALUES
(NULL,1,CURRENT_TIMESTAMP,'"...has joined the
room"','$PHP_ROOM')") or die("ERROR1");
echo "OK 1";
}
mysql_close($db);
}
The code runs fine without the $postmsg = mysql_query("INSERT INTO DATA
(msgid,userid,date,message,room) VALUES (NULL,1,CURRENT_TIMESTAMP,'"...has
joined the"','$PHP_ROOM')") or die("ERROR1");
However if I run it with the $postmsg line I dont get and error or any
reply from server.
I have a chat application with a mysql backend. I am trying to add a line
of code that will post " ...has joined the room" after the room change
function is completed.
Here is my code:
$PHP_PW = $_POST['password'];
$PHP_USER = $_POST['email'];
$PHP_ALIAS = $_POST['alias'];
$PHP_GENDER = $_POST['gender'];
$PHP_LON = $_POST['lon'];
$PHP_LAT = $_POST['lat'];
$PHP_STATUS = $_POST['status'];
$PHP_ROOM = $_POST['room'];
$PHP_ICON = $_POST['iconid'];
//$PHP_IP = $_SERVER['REMOTE_ADDR'];
$PHP_AGE = substr($_POST['age'],0,2);
$PHP_LOC = $_POST['location'];
$PHP_DOB = $_POST['dob'];
$PHP_IP = $_POST['device_id'];
if ($_POST['action']=="update")
{
if(!isset($PHP_USER))
{
echo "ERROR";
} else
{
if(isset($PHP_ROOM))
$update = mysql_query("UPDATE USER SET
room='$PHP_ROOM',lastupdate=NOW() WHERE email='$PHP_USER'")or
die("ERROR80");
$postmsg = mysql_query("INSERT INTO DATA
(msgid,userid,date,message,room) VALUES
(NULL,1,CURRENT_TIMESTAMP,'"...has joined the
room"','$PHP_ROOM')") or die("ERROR1");
echo "OK 1";
}
mysql_close($db);
}
The code runs fine without the $postmsg = mysql_query("INSERT INTO DATA
(msgid,userid,date,message,room) VALUES (NULL,1,CURRENT_TIMESTAMP,'"...has
joined the"','$PHP_ROOM')") or die("ERROR1");
However if I run it with the $postmsg line I dont get and error or any
reply from server.
Jquery mobile app works on the desktop, doesnt work on mobile
Jquery mobile app works on the desktop, doesnt work on mobile
I have a problem, I am making a jquery mobile web app for android, and on
one page I cant fire button "Proveri" on mobile devices(iPhone 5 and Asus
Pad HD 7 tested).
The link is here
Chek HTML on the source code of this page.
JS:
var film = new Array("balkan ekspres","balkan expres");
$(document).ready(function() {
$('.pomoc').hide();
if(typeof(Storage)!=="undefined")
{
//ucitavanje pomoci
$('.btnpomoc').click(function(){
$('.pomoc').slideDown();
});
$("#bb").text(localStorage.bodovi);
if(localStorage.prviprvo.length>3){
$("#imefilma").val(localStorage.prviprvo);
$("#proveri").parent('.ui-submit').addClass("ui->disabled");
$("#proveri").prev('span.ui-btn->inner').find('span.ui-btn-text').text("Pogoðeno");
}
else{
$(".proveri").on('tap', function(){
var imef = >$("#imefilma").val().toLowerCase();
var pogodak;
$.trim(imef);
for(i=0;i<=film.length-1;i++){
if(imef==film[i]){
pogodak = true;
}else{
pogodak = false;
}
}
if(pogodak==true){
var prvoSlovo = imef.substr(0,1);
var ostatak = imef.substr(1);
var novoIme = >prvoSlovo.toUpperCase() + ostatak;
$("#imefilma").val(novoIme);
alert("Taèno!");
//registrujemo da je ovo pitanje
localStorage.prviprvo = novoIme;
localStorage.bodovi = >Number(localStorage.bodovi) +
10;
$("#bb").text(localStorage.bodovi);
}else{
alert("Netaèno!");
}
});
}
}
else
alert("Dogodila se greska");
});
I have a problem, I am making a jquery mobile web app for android, and on
one page I cant fire button "Proveri" on mobile devices(iPhone 5 and Asus
Pad HD 7 tested).
The link is here
Chek HTML on the source code of this page.
JS:
var film = new Array("balkan ekspres","balkan expres");
$(document).ready(function() {
$('.pomoc').hide();
if(typeof(Storage)!=="undefined")
{
//ucitavanje pomoci
$('.btnpomoc').click(function(){
$('.pomoc').slideDown();
});
$("#bb").text(localStorage.bodovi);
if(localStorage.prviprvo.length>3){
$("#imefilma").val(localStorage.prviprvo);
$("#proveri").parent('.ui-submit').addClass("ui->disabled");
$("#proveri").prev('span.ui-btn->inner').find('span.ui-btn-text').text("Pogoðeno");
}
else{
$(".proveri").on('tap', function(){
var imef = >$("#imefilma").val().toLowerCase();
var pogodak;
$.trim(imef);
for(i=0;i<=film.length-1;i++){
if(imef==film[i]){
pogodak = true;
}else{
pogodak = false;
}
}
if(pogodak==true){
var prvoSlovo = imef.substr(0,1);
var ostatak = imef.substr(1);
var novoIme = >prvoSlovo.toUpperCase() + ostatak;
$("#imefilma").val(novoIme);
alert("Taèno!");
//registrujemo da je ovo pitanje
localStorage.prviprvo = novoIme;
localStorage.bodovi = >Number(localStorage.bodovi) +
10;
$("#bb").text(localStorage.bodovi);
}else{
alert("Netaèno!");
}
});
}
}
else
alert("Dogodila se greska");
});
Replace text between two words
Replace text between two words
This question seems to be simple and repetitive here in SO.
But consider this string: SELECT a, b, c, d FROM. I want to get only what
is between SELECT and FROM.
Nice so I have found this answer that propose this regex:
(?<=SELECT)(.*)(?=FROM). It's perfect if lookbehind works in JavaScript,
according to this post:
Unlike lookaheads, JavaScript doesn't support regex lookbehind syntax
So it won't work(test it in regexpal that is made for JS). This anwser
proposes this regex: SELECT=(.*?)FROM. But it includes the two words, so
it not fits my needs.
The purpose of this is to use in a replace function to transform this...
SELECT a, b, c, d FROM
into this...
SELECT Count(*) FROM
Thank you in advance.
This question seems to be simple and repetitive here in SO.
But consider this string: SELECT a, b, c, d FROM. I want to get only what
is between SELECT and FROM.
Nice so I have found this answer that propose this regex:
(?<=SELECT)(.*)(?=FROM). It's perfect if lookbehind works in JavaScript,
according to this post:
Unlike lookaheads, JavaScript doesn't support regex lookbehind syntax
So it won't work(test it in regexpal that is made for JS). This anwser
proposes this regex: SELECT=(.*?)FROM. But it includes the two words, so
it not fits my needs.
The purpose of this is to use in a replace function to transform this...
SELECT a, b, c, d FROM
into this...
SELECT Count(*) FROM
Thank you in advance.
Using Google api to get State/Country suggestions for city
Using Google api to get State/Country suggestions for city
I have a list of North American cities that are inconsistently paired with
provinces and countries. Example:
Calgary AB Canada
CALGARY Alberta - CA
Calgary Canada
I would like to format each city so it follows a consistent pattern. So
that it includes City State/Province and Country. Like:
Calgary Alberta Canada
I've tried using Google's Places API to get suggestions for possible
formating but all I've been able to achieve is a sort of validation that
indicates if such a city exists. I was wondering if someone who has worked
extensively with Google API's can guide me on how I can get
City/Province-State/Country suggestions ( possibly in JSON format) from a
city input.
var input = "City Name";
var service = new google.maps.places.AutocompleteService();
service.getQueryPredictions({ input: input }, callback});
I tried looking into geocoding but that seems to bring back lat/log
information.
I have a list of North American cities that are inconsistently paired with
provinces and countries. Example:
Calgary AB Canada
CALGARY Alberta - CA
Calgary Canada
I would like to format each city so it follows a consistent pattern. So
that it includes City State/Province and Country. Like:
Calgary Alberta Canada
I've tried using Google's Places API to get suggestions for possible
formating but all I've been able to achieve is a sort of validation that
indicates if such a city exists. I was wondering if someone who has worked
extensively with Google API's can guide me on how I can get
City/Province-State/Country suggestions ( possibly in JSON format) from a
city input.
var input = "City Name";
var service = new google.maps.places.AutocompleteService();
service.getQueryPredictions({ input: input }, callback});
I tried looking into geocoding but that seems to bring back lat/log
information.
Is possible to erase an ArrayList element inside a for( ) cycle?
Is possible to erase an ArrayList element inside a for( ) cycle?
pI have this code:/p poutlets is a ArrayList passed to the method;
riverBasin is a 2D matrix of int (int[][] riverBasin);/p precodefor (int[]
item: outlets) { if (item[0] lt; 2 || item[0] gt; this.riverBasin.length -
1 || item[1] lt; 2 || item[1] gt; this.riverBasin[0].length - 1) {
System.out.println(This provisionally substitutes error catching. Outlet (
+ item[0] + , + item[1] + ) is not correct.); outlets.remove(item);
System.out.println(Remaining outlets: ); for (int[] atem: outlets) {
System.out.print(( + atem[0] + , + atem[1] + )\n); } } else {
this.riverBasin[item[0]][item[1]] = 10; } } /code/pre premoving the item
from the ArrayList outlets generate an error:/p precodeException in thread
main java.util.ConcurrentModificationException at
java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343) at
org.geoframe.ocn.Eden.setMultipleOutlet(Eden.java:135) at
org.geoframe.ocn.Eden.main(Eden.java:205) /code/pre pwhich I do not really
completely understand. I suspect, however, that I broke the iterator.
Correct ? How could then I remove the unwanted elements in the
ArrayList./p pThank you in advance for any help,/p priccardo/p
pI have this code:/p poutlets is a ArrayList passed to the method;
riverBasin is a 2D matrix of int (int[][] riverBasin);/p precodefor (int[]
item: outlets) { if (item[0] lt; 2 || item[0] gt; this.riverBasin.length -
1 || item[1] lt; 2 || item[1] gt; this.riverBasin[0].length - 1) {
System.out.println(This provisionally substitutes error catching. Outlet (
+ item[0] + , + item[1] + ) is not correct.); outlets.remove(item);
System.out.println(Remaining outlets: ); for (int[] atem: outlets) {
System.out.print(( + atem[0] + , + atem[1] + )\n); } } else {
this.riverBasin[item[0]][item[1]] = 10; } } /code/pre premoving the item
from the ArrayList outlets generate an error:/p precodeException in thread
main java.util.ConcurrentModificationException at
java.util.AbstractList$Itr.checkForComodification(AbstractList.java:372)
at java.util.AbstractList$Itr.next(AbstractList.java:343) at
org.geoframe.ocn.Eden.setMultipleOutlet(Eden.java:135) at
org.geoframe.ocn.Eden.main(Eden.java:205) /code/pre pwhich I do not really
completely understand. I suspect, however, that I broke the iterator.
Correct ? How could then I remove the unwanted elements in the
ArrayList./p pThank you in advance for any help,/p priccardo/p
Imagick php windows
Imagick php windows
I am trying to use iMagick in Symfony2.
I am using PHP 5.4.16 and all i have done :
1-Copy php_imagick_nts.dll from php5-4 directory from the extracted
http://valokuva.org/~mikko/imagick-php54-php53.tgz to php/ext .
2-Rename it to php_imagick.dll and add the "extension=php_imagick.dll" to
php.ini
3-Create a page like this :
<?php
$a = new Imagick();
?>
but i receive this :
Fatal error: Class 'Imagick' not found in C:\xampp\htdocs\info.php
When I tried to use this in a symfony controller, the error occur again:
FatalErrorException: Error: Class 'Imagick' not found
Unfortunately the details about imagick extension not appear in output of
"phpinfo()"
Is this version is incompatible with PHP 5.4.16 ?! If yes,what version i
must use? Where? Thank for any help...
I am trying to use iMagick in Symfony2.
I am using PHP 5.4.16 and all i have done :
1-Copy php_imagick_nts.dll from php5-4 directory from the extracted
http://valokuva.org/~mikko/imagick-php54-php53.tgz to php/ext .
2-Rename it to php_imagick.dll and add the "extension=php_imagick.dll" to
php.ini
3-Create a page like this :
<?php
$a = new Imagick();
?>
but i receive this :
Fatal error: Class 'Imagick' not found in C:\xampp\htdocs\info.php
When I tried to use this in a symfony controller, the error occur again:
FatalErrorException: Error: Class 'Imagick' not found
Unfortunately the details about imagick extension not appear in output of
"phpinfo()"
Is this version is incompatible with PHP 5.4.16 ?! If yes,what version i
must use? Where? Thank for any help...
Wednesday, 21 August 2013
403 Forbidden status code - jquery-ajax
403 Forbidden status code - jquery-ajax
var company = $('#company').val();
var street = $('#street').val();
var postal = $('#postal').val();
var city = $('#city').val();
$.ajax({
type: "GET",
url: baseURL,
dataType: "json",
beforeSend: function(request) {
request.setRequestHeader('X-Public', publicKey);
request.setRequestHeader('X-Hash', getHMAC(company
+ " " + street + " " + postal + " " + city,
privateKey));
},
data: {name: company, route: street, postal_code:
postal, locality: city},
success: function(data) {
console.log(data);
},
error: function(errorMessage) {
alert(JSON.stringify(errorMessage));
}
});
On the server side the following has been added:
Access-Control-Allow-Origin:* Access-Control-Allow-Headers:
X-Public,X-Hash & its built on Django REST framework
Im getting a HTTP/1.1 403 FORBIDDEN & when used jsop Im getting HTTP/1.1
401 UNAUTHORIZED
Please help
var company = $('#company').val();
var street = $('#street').val();
var postal = $('#postal').val();
var city = $('#city').val();
$.ajax({
type: "GET",
url: baseURL,
dataType: "json",
beforeSend: function(request) {
request.setRequestHeader('X-Public', publicKey);
request.setRequestHeader('X-Hash', getHMAC(company
+ " " + street + " " + postal + " " + city,
privateKey));
},
data: {name: company, route: street, postal_code:
postal, locality: city},
success: function(data) {
console.log(data);
},
error: function(errorMessage) {
alert(JSON.stringify(errorMessage));
}
});
On the server side the following has been added:
Access-Control-Allow-Origin:* Access-Control-Allow-Headers:
X-Public,X-Hash & its built on Django REST framework
Im getting a HTTP/1.1 403 FORBIDDEN & when used jsop Im getting HTTP/1.1
401 UNAUTHORIZED
Please help
Running Macports apache on OSX 10.8.4
Running Macports apache on OSX 10.8.4
After updating to 10.8.4 I am having trouble running my macports apache
server. I stop the built-in apache with: sudo apachectl stop, then I try
to start macports apache with: sudo /opt/local/apache2/bin/apachectl -k
start and I get:
httpd: Could not reliably determine the server's fully qualified domain
name, using My-Name-iMac.local for ServerName
httpd (pid 98) already running
and when I load localhost in the browser I get Unable to Connect...
After updating to 10.8.4 I am having trouble running my macports apache
server. I stop the built-in apache with: sudo apachectl stop, then I try
to start macports apache with: sudo /opt/local/apache2/bin/apachectl -k
start and I get:
httpd: Could not reliably determine the server's fully qualified domain
name, using My-Name-iMac.local for ServerName
httpd (pid 98) already running
and when I load localhost in the browser I get Unable to Connect...
regular expression select an entire html script block containing a certain word
regular expression select an entire html script block containing a certain
word
I am trying to select all script blocks, where there is a certain word
inside the block. This is in a text editor with regex search (notepad++).
I am doing a global replace. Here is an example:
<script type='text/javascript'>
//some
//javascript
</script>
<script type='text/javascript'>
//some
//script
//bla bla **magicword** bla bla
//more script
</script>
<script type='text/javascript'>
//some other
//script
</script>
given the above code, I would want the entire second script block to be
matched, becuase "magicword" appeared somewhere in between the script
blocks. I am sure there is a regular expression to do this but I do not
know anything about regex right now. Any help would be much appreciated.
Thanks alot.
word
I am trying to select all script blocks, where there is a certain word
inside the block. This is in a text editor with regex search (notepad++).
I am doing a global replace. Here is an example:
<script type='text/javascript'>
//some
//javascript
</script>
<script type='text/javascript'>
//some
//script
//bla bla **magicword** bla bla
//more script
</script>
<script type='text/javascript'>
//some other
//script
</script>
given the above code, I would want the entire second script block to be
matched, becuase "magicword" appeared somewhere in between the script
blocks. I am sure there is a regular expression to do this but I do not
know anything about regex right now. Any help would be much appreciated.
Thanks alot.
Scrapy: inserting data into the MySQL database
Scrapy: inserting data into the MySQL database
I am experincing error : spider has no object _getitem_
Here is my Pipeline code
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
from twisted.enterprise import adbapi
import sys
import MySQLdb
import MySQLdb.cursors
from scrapy import log
class OnthegoPipeline(object):
def __init__(self):
self.dbpool = adbapi.ConnectionPool('MySQLdb',
db='scrapy',
host='127.0.0.1',
user='root',
passwd='',
cursorclass=MySQLdb.cursors.DictCursor,
charset='utf8',
use_unicode=True,
)
def process_item(self, spider, item):
query = self.dbpool.runInteraction(self._conditional_insert, item)
query.addErrback(self.handle_error)
return item
def _conditional_insert(self, tx, item):
tx.execute(\
"insert into links (link) "
"values (%s)",
(item['enam'])
)
def handle_error(self, e):
log.err(e)
and this is my Spider
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from onthego.items import OnthegoItem
import sys
import MySQLdb
import MySQLdb.cursors
from MySQLdb import escape_string
import urlparse
import _mysql
# defining function to get the full craped links
def complete_url(string):
"""Return complete url"""
return "http://www.timeoutdelhi.net" + string
#return url.encode('utf8')
#return urlparse.urljoin("http://www.timeoutdelhi.net", string)
class GoSpider(BaseSpider):
name = "title"
allowed_domains = ["timeoutdelhi.net"]
start_urls = [
"http://www.timeoutdelhi.net/"
]
#rules = [Rule(SgmlLinkExtractor(allow=['a\d+\.htm$']), 'parse_item'),
#Rule(SgmlLinkExtractor(restrict_xpaths='//td[@class="pgs"]'),)]
def parse(self, response):
hxs=HtmlXPathSelector(response)
sites=hxs.select('//ul[@class="menu"]/li[@class="last leaf events
events"]/a/@href')
sites1=hxs.select('//ul[@class="menu"]/li[@class="last leaf
sales-exhibitions sales-exhibitions"]/a/@href')
items=[]
for site in sites:
link = site.extract()
yield Request(complete_url(link), callback=self.parse_category)
for sit in sites1:
link1 = sit.extract()
yield Request(complete_url(link1), callback=self.parse_category)
def parse_category(self, response):
hxs = HtmlXPathSelector(response)
# HXS to Detail link inside td and a
sites =
hxs.select('//div[@class="left-column"]/div[@class="resultContainer1"]/span[@class="field-content"]/h2/a/@href')
sites2 =
hxs.select('//div[@class="left-column"]/div[@class="resultContainer1"]/h2/a/@href')
sites1 =
hxs.select('//div[@class="left-column"]/div[@class="resultContainer"]/span/h2/a/@href')
items=[]
for sit in sites2:
link=sit.extract()
yield Request(complete_url(link),
callback=self.parse_category_tilte)
for site in sites:
link1=site.extract()
yield Request(complete_url(link1),
callback=self.parse_category_tilte)
for site in sites1:
link1=site.extract()
yield Request(complete_url(link1),
callback=self.parse_category_tilte)
def parse_category_tilte(self, response):
hxs = HtmlXPathSelector(response)
sites = hxs.select('//div[@class="box-header"]/h3/text()')
items=[]
for site in sites:
item=OnthegoItem()
item['ename']=site.extract()
items.append(item)
return items
I've tried to change the variable names and even the list. I think it is
unable to reach the item['ename'] in the pipeline . Please help.
I am experincing error : spider has no object _getitem_
Here is my Pipeline code
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
from twisted.enterprise import adbapi
import sys
import MySQLdb
import MySQLdb.cursors
from scrapy import log
class OnthegoPipeline(object):
def __init__(self):
self.dbpool = adbapi.ConnectionPool('MySQLdb',
db='scrapy',
host='127.0.0.1',
user='root',
passwd='',
cursorclass=MySQLdb.cursors.DictCursor,
charset='utf8',
use_unicode=True,
)
def process_item(self, spider, item):
query = self.dbpool.runInteraction(self._conditional_insert, item)
query.addErrback(self.handle_error)
return item
def _conditional_insert(self, tx, item):
tx.execute(\
"insert into links (link) "
"values (%s)",
(item['enam'])
)
def handle_error(self, e):
log.err(e)
and this is my Spider
from scrapy.spider import BaseSpider
from scrapy.selector import HtmlXPathSelector
from scrapy.http import Request
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from onthego.items import OnthegoItem
import sys
import MySQLdb
import MySQLdb.cursors
from MySQLdb import escape_string
import urlparse
import _mysql
# defining function to get the full craped links
def complete_url(string):
"""Return complete url"""
return "http://www.timeoutdelhi.net" + string
#return url.encode('utf8')
#return urlparse.urljoin("http://www.timeoutdelhi.net", string)
class GoSpider(BaseSpider):
name = "title"
allowed_domains = ["timeoutdelhi.net"]
start_urls = [
"http://www.timeoutdelhi.net/"
]
#rules = [Rule(SgmlLinkExtractor(allow=['a\d+\.htm$']), 'parse_item'),
#Rule(SgmlLinkExtractor(restrict_xpaths='//td[@class="pgs"]'),)]
def parse(self, response):
hxs=HtmlXPathSelector(response)
sites=hxs.select('//ul[@class="menu"]/li[@class="last leaf events
events"]/a/@href')
sites1=hxs.select('//ul[@class="menu"]/li[@class="last leaf
sales-exhibitions sales-exhibitions"]/a/@href')
items=[]
for site in sites:
link = site.extract()
yield Request(complete_url(link), callback=self.parse_category)
for sit in sites1:
link1 = sit.extract()
yield Request(complete_url(link1), callback=self.parse_category)
def parse_category(self, response):
hxs = HtmlXPathSelector(response)
# HXS to Detail link inside td and a
sites =
hxs.select('//div[@class="left-column"]/div[@class="resultContainer1"]/span[@class="field-content"]/h2/a/@href')
sites2 =
hxs.select('//div[@class="left-column"]/div[@class="resultContainer1"]/h2/a/@href')
sites1 =
hxs.select('//div[@class="left-column"]/div[@class="resultContainer"]/span/h2/a/@href')
items=[]
for sit in sites2:
link=sit.extract()
yield Request(complete_url(link),
callback=self.parse_category_tilte)
for site in sites:
link1=site.extract()
yield Request(complete_url(link1),
callback=self.parse_category_tilte)
for site in sites1:
link1=site.extract()
yield Request(complete_url(link1),
callback=self.parse_category_tilte)
def parse_category_tilte(self, response):
hxs = HtmlXPathSelector(response)
sites = hxs.select('//div[@class="box-header"]/h3/text()')
items=[]
for site in sites:
item=OnthegoItem()
item['ename']=site.extract()
items.append(item)
return items
I've tried to change the variable names and even the list. I think it is
unable to reach the item['ename'] in the pipeline . Please help.
JSON and Cygwin - how to parse, get fields, etc
JSON and Cygwin - how to parse, get fields, etc
I'm getting a JSON based output when sending GET requests to an API
online, using Cygwin. I know how to manage JSON files over PHP and JS, but
in this I wish to keep using Cygwin.
Is there any way to "handle" those files, getting fields' value, etc? I
know I can "create" something manually with sed, grep, awk and such - but
I'm looking, first of all, for something which is "ready-to-use".
Example: { "campaign": { "name": "my campaign", "id": 1434, "creatives": [
{ "id": 4162, "state": "active" } ], } }
Thanks a lot, Etay
I'm getting a JSON based output when sending GET requests to an API
online, using Cygwin. I know how to manage JSON files over PHP and JS, but
in this I wish to keep using Cygwin.
Is there any way to "handle" those files, getting fields' value, etc? I
know I can "create" something manually with sed, grep, awk and such - but
I'm looking, first of all, for something which is "ready-to-use".
Example: { "campaign": { "name": "my campaign", "id": 1434, "creatives": [
{ "id": 4162, "state": "active" } ], } }
Thanks a lot, Etay
Can we include angularjs component in xhtml page
Can we include angularjs component in xhtml page
I am new to angularjs, and was trying to create a sample angularjs in an
xhtml file. But I am getting an error in the line in eclipseIDE. The error
specifies that the ng-app attribute should be followed by an '='
character. So is it not possible to include angularjs code with xhtml file
? Could someone please advise.
I am new to angularjs, and was trying to create a sample angularjs in an
xhtml file. But I am getting an error in the line in eclipseIDE. The error
specifies that the ng-app attribute should be followed by an '='
character. So is it not possible to include angularjs code with xhtml file
? Could someone please advise.
Selectable/Highlightable List Item with custom background
Selectable/Highlightable List Item with custom background
I have a ListView item which has a set background. This overrides the
default blue highlight that appears when the item is pressed/selected. Is
there a way to have both the background and the selector?
This is my attempt at merging both a background and selector...
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="@color/red"/>
</selector>
<item>
<shape
android:dither="true"
android:shape="rectangle" >
<solid android:color="#ccc" />
</shape>
</item>
<item android:bottom="2dp">
<shape
android:dither="true"
android:shape="rectangle" >
<corners android:radius="6dp" />
<solid android:color="@android:color/white" />
</shape>
</item>
</layer-list>
This is in my drawable folder, and I set it with this in my ListItem xml:
android:background="@drawable/my_background
I have a ListView item which has a set background. This overrides the
default blue highlight that appears when the item is pressed/selected. Is
there a way to have both the background and the selector?
This is my attempt at merging both a background and selector...
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_pressed="true" android:color="@color/red"/>
</selector>
<item>
<shape
android:dither="true"
android:shape="rectangle" >
<solid android:color="#ccc" />
</shape>
</item>
<item android:bottom="2dp">
<shape
android:dither="true"
android:shape="rectangle" >
<corners android:radius="6dp" />
<solid android:color="@android:color/white" />
</shape>
</item>
</layer-list>
This is in my drawable folder, and I set it with this in my ListItem xml:
android:background="@drawable/my_background
Tuesday, 20 August 2013
Social Proxy Server Configuration
Social Proxy Server Configuration
I am using my Company proxy server while redirecting my page to facebook
and vice-versa it gives error for invalid crendentials... I have tried
below two option but its not working...
1.`public ConnectController connectController() { ConnectController
controller = new ConnectController( connectionFactoryLocator(),
connectionRepository());
controller.setApplicationUrl("https://graph.facebook.com/oauth/authorize?client_id=1399601086924425&redirect_uri=http://localhost:8080/spring-social-quickstart-30x");
return controller; }
` 2.
public ConnectController connectController() {
ConnectController controller = new ConnectController(
connectionFactoryLocator(), connectionRepository());
System.setProperty("proxyHost","myProxyAddres");
System.setProperty("proxyPort","myPortNumber");`
}
I am using my Company proxy server while redirecting my page to facebook
and vice-versa it gives error for invalid crendentials... I have tried
below two option but its not working...
1.`public ConnectController connectController() { ConnectController
controller = new ConnectController( connectionFactoryLocator(),
connectionRepository());
controller.setApplicationUrl("https://graph.facebook.com/oauth/authorize?client_id=1399601086924425&redirect_uri=http://localhost:8080/spring-social-quickstart-30x");
return controller; }
` 2.
public ConnectController connectController() {
ConnectController controller = new ConnectController(
connectionFactoryLocator(), connectionRepository());
System.setProperty("proxyHost","myProxyAddres");
System.setProperty("proxyPort","myPortNumber");`
}
c++ error lnk2005 when a global function is included
c++ error lnk2005 when a global function is included
background:C++/dll project/vs2012/error lnk2005
I am doing a dll project, and it had been working well until I added a new
.h, which includes a global function and a struct.
Then the compiling(or link?) failed.
Here is the error message:
1>RobotReality.obj : error LNK2005: "double __cdecl GetNumber(void)"
(?GetNumber@@YANXZ) [[ÒѾÔÚ dllmain.obj Öж¨Òå translate: this has been
defined in dllmain.obj]]
1>stdafx.obj : error LNK2005: "double __cdecl GetNumber(void)"
(?GetNumber@@YANXZ) [[ÒѾÔÚ dllmain.obj Öж¨Òå translate: this has been
defined in dllmain.obj]]
I have added "#pragma once" but the problem still exits.
How to solve the problem?
Thanks!
background:C++/dll project/vs2012/error lnk2005
I am doing a dll project, and it had been working well until I added a new
.h, which includes a global function and a struct.
Then the compiling(or link?) failed.
Here is the error message:
1>RobotReality.obj : error LNK2005: "double __cdecl GetNumber(void)"
(?GetNumber@@YANXZ) [[ÒѾÔÚ dllmain.obj Öж¨Òå translate: this has been
defined in dllmain.obj]]
1>stdafx.obj : error LNK2005: "double __cdecl GetNumber(void)"
(?GetNumber@@YANXZ) [[ÒѾÔÚ dllmain.obj Öж¨Òå translate: this has been
defined in dllmain.obj]]
I have added "#pragma once" but the problem still exits.
How to solve the problem?
Thanks!
Putting the callback on the same line?
Putting the callback on the same line?
I'm not a Ruby developer by any means and am just modifying a Chef recipe.
I'm curious, is it possible to put the following onto one line?
directory "/var/lib/mysql" do
action :delete
end
I tried this:
directory "/var/lib/mysql", :action => "delete"
However, that throws this error:
ArgumentError
-------------
wrong number of arguments (3 for 2)
I'm not a Ruby developer by any means and am just modifying a Chef recipe.
I'm curious, is it possible to put the following onto one line?
directory "/var/lib/mysql" do
action :delete
end
I tried this:
directory "/var/lib/mysql", :action => "delete"
However, that throws this error:
ArgumentError
-------------
wrong number of arguments (3 for 2)
Running Sheet-Specific Macro from Other Sheet
Running Sheet-Specific Macro from Other Sheet
I have a Excel book that has multiple sheets, subs, and macros. In order
to make it a bit more user friendly, I'd like to create a dashboard sheet
where the user has to just click buttons to run everything. This is
possible easily with the subs, but how can I call a macro from one sheet
to another? I can't seem to find any Excel documentation on this.
I have a Excel book that has multiple sheets, subs, and macros. In order
to make it a bit more user friendly, I'd like to create a dashboard sheet
where the user has to just click buttons to run everything. This is
possible easily with the subs, but how can I call a macro from one sheet
to another? I can't seem to find any Excel documentation on this.
postgresql triggers after update
postgresql triggers after update
The following function ,update_sessioninfo(), should only update changed
columns. The New.* columns are being updated to some incorrect values
after running:
update freeradius.radacct set acctsessiontime=25 where radacctid=3;
function
CREATE OR REPLACE FUNCTION update_sessioninfo() RETURNS trigger AS
$radacct_update$
BEGIN
-- update the updated records
update freeradius.day_guiding_usage set
acctstoptime=New.acctstoptime,acctsessiontime=New.acctsessiontime,connectinfo_start=New.connectinfo_start,connectinfo_stop=New.connectinfo_stop,acctinputoctets=New.acctinputoctets,acctoutputoctets=New.acctoutputoctets,acctterminatecause=New.acctterminatecause
where acctsessionid=Old.acctsessionid;
RETURN NULL;
END;
$radacct_update$ LANGUAGE plpgsql;
The trigger is below
CREATE TRIGGER radacct_update AFTER UPDATE ON freeradius.radacct
FOR EACH ROW
WHEN (OLD.* IS DISTINCT FROM NEW.*)
EXECUTE procedure update_sessioninfo();
The following function ,update_sessioninfo(), should only update changed
columns. The New.* columns are being updated to some incorrect values
after running:
update freeradius.radacct set acctsessiontime=25 where radacctid=3;
function
CREATE OR REPLACE FUNCTION update_sessioninfo() RETURNS trigger AS
$radacct_update$
BEGIN
-- update the updated records
update freeradius.day_guiding_usage set
acctstoptime=New.acctstoptime,acctsessiontime=New.acctsessiontime,connectinfo_start=New.connectinfo_start,connectinfo_stop=New.connectinfo_stop,acctinputoctets=New.acctinputoctets,acctoutputoctets=New.acctoutputoctets,acctterminatecause=New.acctterminatecause
where acctsessionid=Old.acctsessionid;
RETURN NULL;
END;
$radacct_update$ LANGUAGE plpgsql;
The trigger is below
CREATE TRIGGER radacct_update AFTER UPDATE ON freeradius.radacct
FOR EACH ROW
WHEN (OLD.* IS DISTINCT FROM NEW.*)
EXECUTE procedure update_sessioninfo();
having module function not working properly
having module function not working properly
i have a situation. i am creating a school database system, ive suddenly
stocked in the module function. i created form that register student every
year. in my query, i want the user to calculate all registered student in
each year. i succeeded in doing that using my parameter in my query date
field and a function in my vba module
Module Function ParmValue() As Date ParmValue = InputBox("date here") End
Function
Query creiterial=parmvalue()
now i want that the chosen date should be displayed on my report label
call "lblyear". the thing is i just cant call any control in my function.
why?, can anyone help me please?
i have a situation. i am creating a school database system, ive suddenly
stocked in the module function. i created form that register student every
year. in my query, i want the user to calculate all registered student in
each year. i succeeded in doing that using my parameter in my query date
field and a function in my vba module
Module Function ParmValue() As Date ParmValue = InputBox("date here") End
Function
Query creiterial=parmvalue()
now i want that the chosen date should be displayed on my report label
call "lblyear". the thing is i just cant call any control in my function.
why?, can anyone help me please?
Entity Framework - Cannot insert explicit value for identity column in table 'LeistungGruppe' when IDENTITY_INSERT is set to OFF
Entity Framework - Cannot insert explicit value for identity column in
table 'LeistungGruppe' when IDENTITY_INSERT is set to OFF
i'm trying to add an EntityObject to my database by calling
AddToLeistungGruppe.
LeistungGruppe in this case is my Table with Primary_Key LeistungGruppe_ID
with Identity true and Identity increment 1 and seed 1.
I search alot for this issue and alot of People got he same error. They
were told to simply set StoreGeneratedPattern to Identity and this would
solve the Problem.
I tried it out and still got the same issue. I'm new to the Entity
Framework and have no idea about how to solve this Problem.
Somehow i think the model isn't updated propably because even if i Switch
arround These Settings i'm getting the same error over and over again.
Every help is appreciated.
PS: sorry for my bad english
Thanks in advance!
table 'LeistungGruppe' when IDENTITY_INSERT is set to OFF
i'm trying to add an EntityObject to my database by calling
AddToLeistungGruppe.
LeistungGruppe in this case is my Table with Primary_Key LeistungGruppe_ID
with Identity true and Identity increment 1 and seed 1.
I search alot for this issue and alot of People got he same error. They
were told to simply set StoreGeneratedPattern to Identity and this would
solve the Problem.
I tried it out and still got the same issue. I'm new to the Entity
Framework and have no idea about how to solve this Problem.
Somehow i think the model isn't updated propably because even if i Switch
arround These Settings i'm getting the same error over and over again.
Every help is appreciated.
PS: sorry for my bad english
Thanks in advance!
Monday, 19 August 2013
Javascript textContent is not working in IE8 or IE7
Javascript textContent is not working in IE8 or IE7
I need to add 2 cell content of a table and display it. Below JavaScript
command works fine in chrome or IE10. But not working in IE8 or 7.
parseFloat(document.getElementById("total").textContent).toFixed(2);
It results,
NaN
Could you please tell me what is the equivalent command in IE7 or IE8 to
read cell content of a table and convert it to float then add..
I need to add 2 cell content of a table and display it. Below JavaScript
command works fine in chrome or IE10. But not working in IE8 or 7.
parseFloat(document.getElementById("total").textContent).toFixed(2);
It results,
NaN
Could you please tell me what is the equivalent command in IE7 or IE8 to
read cell content of a table and convert it to float then add..
use of
use of
The title says it all, can anyone enlighten me what the number sign is for
in what I assume is simply an html comment block?
<!-- #
Thanks!
The title says it all, can anyone enlighten me what the number sign is for
in what I assume is simply an html comment block?
<!-- #
Thanks!
Drupal 7 Database locks up seldomly as Admin
Drupal 7 Database locks up seldomly as Admin
I am working with Drupal 7 from Commerce Kickstart 2.0. For random times
thoughout the day, while I am logged in as admin for the site I will get
"MySql Server has gone away" and Internal Server 500" errors. It will last
from only a few minutes to upwards of an hour and then be completely fine.
Does anybody have any insight as to what could be the issue? I have been
searching for quite a while to find a solution. So far I have changed my
php.ini/my.cnf to increase max_allowed_packet along with a few other
parameters without success. The database formats were switched to myisam
per the host's requests as well.
The site was transferred from a different host and the error did not exist
until after the move. WHen I can not access the site, it is still
available to authenticated and anonymous users as if nothing is wrong.
Here is the error I am presented when the error occurs:
Additional uncaught exception thrown while handling exception.
Original
PDOException: SQLSTATE[70100]: <<Unknown error>>: 1317 Query execution was
interrupted: SELECT revision.order_number AS order_number,
revision.revision_id AS revision_id, revision.revision_uid AS
revision_uid, revision.mail AS mail, revision.status AS status,
revision.log AS log, revision.revision_timestamp AS revision_timestamp,
revision.revision_hostname AS revision_hostname, revision.data AS data,
base.order_id AS order_id, base.type AS type, base.uid AS uid,
base.created AS created, base.changed AS changed, base.hostname AS
hostname FROM {commerce_order} base INNER JOIN {commerce_order_revision}
revision ON revision.revision_id = base.revision_id WHERE (base.order_id
IN (:db_condition_placeholder_0)) FOR UPDATE; Array (
[:db_condition_placeholder_0] => 9 ) in
DrupalDefaultEntityController->load() (line 196 of
/nfs/c06/h06/mnt/93760/domains/accuairtest.com/html/includes/entity.inc).
Additional
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone
away: INSERT INTO {watchdog} (uid, type, message, variables, severity,
link, location, referer, hostname, timestamp) VALUES
(:db_insert_placeholder_0, :db_insert_placeholder_1,
:db_insert_placeholder_2, :db_insert_placeholder_3,
:db_insert_placeholder_4, :db_insert_placeholder_5,
:db_insert_placeholder_6, :db_insert_placeholder_7,
:db_insert_placeholder_8, :db_insert_placeholder_9); Array (
[:db_insert_placeholder_0] => 1 [:db_insert_placeholder_1] => php
[:db_insert_placeholder_2] => %type: !message in %function (line %line of
%file). [:db_insert_placeholder_3] =>
a:6:{s:5:"%type";s:12:"PDOException";s:8:"!message";s:780:"SQLSTATE[70100]:
<<Unknown error>>: 1317 Query execution was interrupted:
SELECT revision.order_number AS order_number, revision.revision_id AS
revision_id, revision.revision_uid AS revision_uid, revision.mail AS mail,
revision.status AS status, revision.log AS log,
revision.revision_timestamp AS revision_timestamp,
revision.revision_hostname AS revision_hostname, revision.data AS data,
base.order_id AS order_id, base.type AS type, base.uid AS uid,
base.created AS created, base.changed AS changed, base.hostname AS
hostname FROM {commerce_order} base INNER JOIN {commerce_order_revision}
revision ON revision.revision_id = base.revision_id WHERE (base.order_id
IN (:db_condition_placeholder_0)) FOR UPDATE; Array (
[:db_condition_placeholder_0] => 9 )
";s:9:"%function";s:37:"DrupalDefaultEntityController->load()";s:5:"%file";s:71:"/nfs/c06/h06/mnt/93760/domains/accuairtest.com/html/includes/entity.inc";s:5:"%line";i:196;s:14:"severity_level";i:3;}
[:db_insert_placeholder_4] => 3 [:db_insert_placeholder_5] =>
[:db_insert_placeholder_6] => http://accuairtest.com/
[:db_insert_placeholder_7] => [:db_insert_placeholder_8] => 72.29.182.99
[:db_insert_placeholder_9] => 1376943825 ) in dblog_watchdog() (line 160
of
/nfs/c06/h06/mnt/93760/domains/accuairtest.com/html/modules/dblog/dblog.module).
Uncaught exception thrown in session handler.
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone
away: SAVEPOINT savepoint_1; Array ( ) in _drupal_session_write() (line
209 of
/nfs/c06/h06/mnt/93760/domains/accuairtest.com/html/includes/session.inc).
I am working with Drupal 7 from Commerce Kickstart 2.0. For random times
thoughout the day, while I am logged in as admin for the site I will get
"MySql Server has gone away" and Internal Server 500" errors. It will last
from only a few minutes to upwards of an hour and then be completely fine.
Does anybody have any insight as to what could be the issue? I have been
searching for quite a while to find a solution. So far I have changed my
php.ini/my.cnf to increase max_allowed_packet along with a few other
parameters without success. The database formats were switched to myisam
per the host's requests as well.
The site was transferred from a different host and the error did not exist
until after the move. WHen I can not access the site, it is still
available to authenticated and anonymous users as if nothing is wrong.
Here is the error I am presented when the error occurs:
Additional uncaught exception thrown while handling exception.
Original
PDOException: SQLSTATE[70100]: <<Unknown error>>: 1317 Query execution was
interrupted: SELECT revision.order_number AS order_number,
revision.revision_id AS revision_id, revision.revision_uid AS
revision_uid, revision.mail AS mail, revision.status AS status,
revision.log AS log, revision.revision_timestamp AS revision_timestamp,
revision.revision_hostname AS revision_hostname, revision.data AS data,
base.order_id AS order_id, base.type AS type, base.uid AS uid,
base.created AS created, base.changed AS changed, base.hostname AS
hostname FROM {commerce_order} base INNER JOIN {commerce_order_revision}
revision ON revision.revision_id = base.revision_id WHERE (base.order_id
IN (:db_condition_placeholder_0)) FOR UPDATE; Array (
[:db_condition_placeholder_0] => 9 ) in
DrupalDefaultEntityController->load() (line 196 of
/nfs/c06/h06/mnt/93760/domains/accuairtest.com/html/includes/entity.inc).
Additional
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone
away: INSERT INTO {watchdog} (uid, type, message, variables, severity,
link, location, referer, hostname, timestamp) VALUES
(:db_insert_placeholder_0, :db_insert_placeholder_1,
:db_insert_placeholder_2, :db_insert_placeholder_3,
:db_insert_placeholder_4, :db_insert_placeholder_5,
:db_insert_placeholder_6, :db_insert_placeholder_7,
:db_insert_placeholder_8, :db_insert_placeholder_9); Array (
[:db_insert_placeholder_0] => 1 [:db_insert_placeholder_1] => php
[:db_insert_placeholder_2] => %type: !message in %function (line %line of
%file). [:db_insert_placeholder_3] =>
a:6:{s:5:"%type";s:12:"PDOException";s:8:"!message";s:780:"SQLSTATE[70100]:
<<Unknown error>>: 1317 Query execution was interrupted:
SELECT revision.order_number AS order_number, revision.revision_id AS
revision_id, revision.revision_uid AS revision_uid, revision.mail AS mail,
revision.status AS status, revision.log AS log,
revision.revision_timestamp AS revision_timestamp,
revision.revision_hostname AS revision_hostname, revision.data AS data,
base.order_id AS order_id, base.type AS type, base.uid AS uid,
base.created AS created, base.changed AS changed, base.hostname AS
hostname FROM {commerce_order} base INNER JOIN {commerce_order_revision}
revision ON revision.revision_id = base.revision_id WHERE (base.order_id
IN (:db_condition_placeholder_0)) FOR UPDATE; Array (
[:db_condition_placeholder_0] => 9 )
";s:9:"%function";s:37:"DrupalDefaultEntityController->load()";s:5:"%file";s:71:"/nfs/c06/h06/mnt/93760/domains/accuairtest.com/html/includes/entity.inc";s:5:"%line";i:196;s:14:"severity_level";i:3;}
[:db_insert_placeholder_4] => 3 [:db_insert_placeholder_5] =>
[:db_insert_placeholder_6] => http://accuairtest.com/
[:db_insert_placeholder_7] => [:db_insert_placeholder_8] => 72.29.182.99
[:db_insert_placeholder_9] => 1376943825 ) in dblog_watchdog() (line 160
of
/nfs/c06/h06/mnt/93760/domains/accuairtest.com/html/modules/dblog/dblog.module).
Uncaught exception thrown in session handler.
PDOException: SQLSTATE[HY000]: General error: 2006 MySQL server has gone
away: SAVEPOINT savepoint_1; Array ( ) in _drupal_session_write() (line
209 of
/nfs/c06/h06/mnt/93760/domains/accuairtest.com/html/includes/session.inc).
gwt grid dont work with mouse
gwt grid dont work with mouse
I have a grid like this:
this.mygrid = new Grid<person>(this.Store, this.mygridcolummodel);
this.mygrid .getView().setAutoExpandColumn(docColumn);
this.mygrid .getView().setStripeRows(true);
this.mygrid .getView().setColumnLines(true);
this.mygrid .getView().setSortingEnabled(true);
public void onResultresearchRowDoubleClick(RowDoubleClickEvent event) {
person PSelected = (person)
event.getSource().getSelectionModel().getSelectedItem();
getPresenter().openperson(PSelected.getID());
}
With this, I get my grid exacly how I want it with the doubleclick working
exacly how it's supposed to.
My problem is that I can only select 1 row with my mouse, and it stay
locked to that row and if I double click on any other row, it open the row
that I selected first. I cant change row with the mouse, but strangely, I
can with the keyboard arrows(up and down). Do any of you know what I dont
get?
I have a grid like this:
this.mygrid = new Grid<person>(this.Store, this.mygridcolummodel);
this.mygrid .getView().setAutoExpandColumn(docColumn);
this.mygrid .getView().setStripeRows(true);
this.mygrid .getView().setColumnLines(true);
this.mygrid .getView().setSortingEnabled(true);
public void onResultresearchRowDoubleClick(RowDoubleClickEvent event) {
person PSelected = (person)
event.getSource().getSelectionModel().getSelectedItem();
getPresenter().openperson(PSelected.getID());
}
With this, I get my grid exacly how I want it with the doubleclick working
exacly how it's supposed to.
My problem is that I can only select 1 row with my mouse, and it stay
locked to that row and if I double click on any other row, it open the row
that I selected first. I cant change row with the mouse, but strangely, I
can with the keyboard arrows(up and down). Do any of you know what I dont
get?
TabbedView not displaying the Navigation bar
TabbedView not displaying the Navigation bar
iOS beginner here. I'm Using XCode 4.6.3 and doing some tutorials. I have
a question regarding a TabbedView not displaying the Navigation bar:
I set the Top Bar attribute here:
But it doesn't show here:
Below is the code in the AppDelegate:
self.navController = [[UINavigationController alloc]
initWithRootViewController:viewController1];
self.navController.navigationBar.barStyle = UIBarStyleBlack;
self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = @[viewController1,
viewController2];
self.window.rootViewController = self.tabBarController;
What am I doing wrong?
iOS beginner here. I'm Using XCode 4.6.3 and doing some tutorials. I have
a question regarding a TabbedView not displaying the Navigation bar:
I set the Top Bar attribute here:
But it doesn't show here:
Below is the code in the AppDelegate:
self.navController = [[UINavigationController alloc]
initWithRootViewController:viewController1];
self.navController.navigationBar.barStyle = UIBarStyleBlack;
self.tabBarController = [[UITabBarController alloc] init];
self.tabBarController.viewControllers = @[viewController1,
viewController2];
self.window.rootViewController = self.tabBarController;
What am I doing wrong?
Sunday, 18 August 2013
in golang, which value's kind is reflect.Interface
in golang, which value's kind is reflect.Interface
j:=1
i know the kind of j is reflect.Int
var j interface{} = 1
the kind of j is also reflect.Int
but which value's kind is reflect.Interface?
j:=1
i know the kind of j is reflect.Int
var j interface{} = 1
the kind of j is also reflect.Int
but which value's kind is reflect.Interface?
two functions are uniformly continuous on some interval I and each is bounded on I then their product is also uniformly continuous on I .
two functions are uniformly continuous on some interval I and each is
bounded on I then their product is also uniformly continuous on I .
prove that if two real valued functions are uniformly continuous on some
interval I and each is bounded on I then their product f.g=f(x).g(x) is
also uniformly continuous on I . Is boundedness of each function on I is
necessary for the product
bounded on I then their product is also uniformly continuous on I .
prove that if two real valued functions are uniformly continuous on some
interval I and each is bounded on I then their product f.g=f(x).g(x) is
also uniformly continuous on I . Is boundedness of each function on I is
necessary for the product
Javascript solution for table-cell on IE6/IE7
Javascript solution for table-cell on IE6/IE7
What is the best approach in javascript "vanilla" for solve the problem of
table-cell in IE6/IE7?
What is the best approach in javascript "vanilla" for solve the problem of
table-cell in IE6/IE7?
Disabling Windows Boot Manager And Using Grub2
Disabling Windows Boot Manager And Using Grub2
All, I'm in a wierd situation, I would like to use grub2 to boot my
Ubuntu, Windows 7 (old) and Windows 7 (new).
I purchased an SSD and installed Windows on it. My old Window installation
still exists and I would like to keep it around for the next few months as
I figure out what I need to copy over from it.
I currently have:
/dev/sda - disk drive -- part: 1 (linux), 2 (swap), 3(old windows), 4
(NTFS Data)
/dev/sdb - SSD -- part: 1(new windows)
I would like grub2 to display seperate entries for:
/dev/sda3
/dev/sdb1
However it only displays /dev/sda3, this leads to the Windows Boot
Manager, and there I can choose which Windows to boot. I've been trying to
figure out how to adjust this, but I can't seem to figure out where to
start.
Points of Interest:
/dev/sda3 is listed as Boot, Page File, Crash Dump (notice Boot is here!?)
/dev/sdb1 is listed as System, Active, Primary (this is weird?)
All, I'm in a wierd situation, I would like to use grub2 to boot my
Ubuntu, Windows 7 (old) and Windows 7 (new).
I purchased an SSD and installed Windows on it. My old Window installation
still exists and I would like to keep it around for the next few months as
I figure out what I need to copy over from it.
I currently have:
/dev/sda - disk drive -- part: 1 (linux), 2 (swap), 3(old windows), 4
(NTFS Data)
/dev/sdb - SSD -- part: 1(new windows)
I would like grub2 to display seperate entries for:
/dev/sda3
/dev/sdb1
However it only displays /dev/sda3, this leads to the Windows Boot
Manager, and there I can choose which Windows to boot. I've been trying to
figure out how to adjust this, but I can't seem to figure out where to
start.
Points of Interest:
/dev/sda3 is listed as Boot, Page File, Crash Dump (notice Boot is here!?)
/dev/sdb1 is listed as System, Active, Primary (this is weird?)
Incorrect Buddypress Links
Incorrect Buddypress Links
I recently installed Buddypress on a new Wordpress site. I'm having a
problem getting Buddypress links to work. My site's permalinks are set to
'post-name' (http://mysite.com/index.php/sample-post/) but when I click
'Register' for example (a Buddypress link) it goes to
http://mysite.com/register.
Anyone know how I can change Buddypress link structure?
I recently installed Buddypress on a new Wordpress site. I'm having a
problem getting Buddypress links to work. My site's permalinks are set to
'post-name' (http://mysite.com/index.php/sample-post/) but when I click
'Register' for example (a Buddypress link) it goes to
http://mysite.com/register.
Anyone know how I can change Buddypress link structure?
Turning all events .off() and .on() in jQuery
Turning all events .off() and .on() in jQuery
I'm looking at using .off() and .on() to turn event handlers off and on in
jQuery.
I can turn the all attached event handlers off perfectly by using:
$('.eventone').off();
or as a multiple selector:
$('.eventone, .eventtwo, .eventthree').off();
However, I'm not getting all (or even any) event handlers to turn back on.
I'm using this:
$('.eventone, .eventtwo, .eventthree').on();
Is there something I'm doing wrong?
Do I actually have to declare every event that's associated with the class
in order to turn it back on?
I'm looking at using .off() and .on() to turn event handlers off and on in
jQuery.
I can turn the all attached event handlers off perfectly by using:
$('.eventone').off();
or as a multiple selector:
$('.eventone, .eventtwo, .eventthree').off();
However, I'm not getting all (or even any) event handlers to turn back on.
I'm using this:
$('.eventone, .eventtwo, .eventthree').on();
Is there something I'm doing wrong?
Do I actually have to declare every event that's associated with the class
in order to turn it back on?
Saturday, 17 August 2013
UIGestureRecognizer with NSTimer that never dies
UIGestureRecognizer with NSTimer that never dies
I'm trying to set up a "FastForward/Next" button in a media player that
can be tapped to move to the next song or held to fast forward within the
current song. Mostly, it works: you can successfully fastforward and
successfully move to the next song, but the thing is, the NSTimer that
makes it work never invalidates, so once you start fastforwarding, you
never stop.
I set up the gesture recognizers in viewDidLoad:
UITapGestureRecognizer *singleTapFastForward = [[UITapGestureRecognizer
alloc] initWithTarget: self action:@selector(nextSong:)];
singleTapFastForward.numberOfTapsRequired = 1;
[_buttonNext addGestureRecognizer:singleTapFastForward];
_holdFastForward = [[UILongPressGestureRecognizer alloc] initWithTarget:
self action:@selector(startFastForward:)];
[_buttonNext addGestureRecognizer:_holdFastForward];
[singleTapFastForward requireGestureRecognizerToFail:_holdFastForward];
and here is the meat of the function:
- (IBAction)startFastForward:(id)sender {
_timerFastForward = [NSTimer scheduledTimerWithTimeInterval:0.5
target:self selector:@selector(executeFastForward) userInfo:nil
repeats:YES];
}
- (void)executeFastForward {
[_avPlayer seekToTime:CMTimeMake(CMTimeGetSeconds([_avPlayer
currentTime]) + 10, 1)];
if(_holdFastForward.state == 0) {
[self endFastForward:self];
}
}
- (IBAction)endFastForward:(id)sender {
[_timerFastForward invalidate];
}
Here's the tricky part: when I set a breakpoint at the
if(_holdFastForward.state == 0) line, it starts working as soon as I let
go of the button (as it should), and it successfully calls the
endFastForward method. By my reckoning, that should kill the timer and end
the whole cycle, but then executeFastForward gets called again, and then
again and again. The invalidate line just seems to do nothing (and there
are no other points in my code that call executeFastForward).
Any ideas? This seems like a simple thing, and if the invalidate line
worked everything would be perfect. I just don't know why
executeFastForward continues to be called. Is my NSTimer TRON's answer to
the Highlander, or is there something else going on?
I'm trying to set up a "FastForward/Next" button in a media player that
can be tapped to move to the next song or held to fast forward within the
current song. Mostly, it works: you can successfully fastforward and
successfully move to the next song, but the thing is, the NSTimer that
makes it work never invalidates, so once you start fastforwarding, you
never stop.
I set up the gesture recognizers in viewDidLoad:
UITapGestureRecognizer *singleTapFastForward = [[UITapGestureRecognizer
alloc] initWithTarget: self action:@selector(nextSong:)];
singleTapFastForward.numberOfTapsRequired = 1;
[_buttonNext addGestureRecognizer:singleTapFastForward];
_holdFastForward = [[UILongPressGestureRecognizer alloc] initWithTarget:
self action:@selector(startFastForward:)];
[_buttonNext addGestureRecognizer:_holdFastForward];
[singleTapFastForward requireGestureRecognizerToFail:_holdFastForward];
and here is the meat of the function:
- (IBAction)startFastForward:(id)sender {
_timerFastForward = [NSTimer scheduledTimerWithTimeInterval:0.5
target:self selector:@selector(executeFastForward) userInfo:nil
repeats:YES];
}
- (void)executeFastForward {
[_avPlayer seekToTime:CMTimeMake(CMTimeGetSeconds([_avPlayer
currentTime]) + 10, 1)];
if(_holdFastForward.state == 0) {
[self endFastForward:self];
}
}
- (IBAction)endFastForward:(id)sender {
[_timerFastForward invalidate];
}
Here's the tricky part: when I set a breakpoint at the
if(_holdFastForward.state == 0) line, it starts working as soon as I let
go of the button (as it should), and it successfully calls the
endFastForward method. By my reckoning, that should kill the timer and end
the whole cycle, but then executeFastForward gets called again, and then
again and again. The invalidate line just seems to do nothing (and there
are no other points in my code that call executeFastForward).
Any ideas? This seems like a simple thing, and if the invalidate line
worked everything would be perfect. I just don't know why
executeFastForward continues to be called. Is my NSTimer TRON's answer to
the Highlander, or is there something else going on?
Represent repeating decimals in Rails model
Represent repeating decimals in Rails model
What's a good way to represent repeating decimals in the database?
My current thought is to separate it into 2 pieces in the Rails model:
take 25.818181, use two floats non_repeat = 25.25 and repeat = .007
# Model
class Decimal < ActiveRecord::Base
attr_accessible :non_repeat, :repeat #both are floats
# this is approximate
def to_f
to_s.to_f
end
def to_s
"#{non_repeat + repeat}#{repeat.to_s.gsub(/0\./, '') * 3}"
end
def self.random_new
a = rand(100)
b = rand(100) / 100.0
self.new(non_repeat: a, repeat: b)
end
end
Is this a good way to randomly generate repeating decimals?
Alternately, I wasn't sure if using a random fraction is better, e.g.
Rational(rand(100), random_prime)
What's a good way to represent repeating decimals in the database?
My current thought is to separate it into 2 pieces in the Rails model:
take 25.818181, use two floats non_repeat = 25.25 and repeat = .007
# Model
class Decimal < ActiveRecord::Base
attr_accessible :non_repeat, :repeat #both are floats
# this is approximate
def to_f
to_s.to_f
end
def to_s
"#{non_repeat + repeat}#{repeat.to_s.gsub(/0\./, '') * 3}"
end
def self.random_new
a = rand(100)
b = rand(100) / 100.0
self.new(non_repeat: a, repeat: b)
end
end
Is this a good way to randomly generate repeating decimals?
Alternately, I wasn't sure if using a random fraction is better, e.g.
Rational(rand(100), random_prime)
Navbar-collapse is presented behind the rest of the content when active
Navbar-collapse is presented behind the rest of the content when active
See the effect here, click on the navbar-collapse button:
visualhaggard.org/illustrations
I think the problem is that I have some styling in place for sticky footer:
body {
min-height: 100%;
}
#wrap, .navbar-wrapper {
min-height: 100%;
max-width: 1120px;
padding-top: 5px;
}
#main {
overflow:auto;
padding-bottom: 42px;
}
footer {
position: absolute;
left: 0;
bottom: 0;
height: 42px;
margin: 0 auto;
width: 100%;
}
The content of the page is:
<body>
<header-bar></header-bar>
<div id="wrap">
<div id="main">
CONTENT
</div>
</div>
<footer></footer>
I tried many manipulations of the preceding styles with no luck. Has
anyone faced this problem before? Thanks.
See the effect here, click on the navbar-collapse button:
visualhaggard.org/illustrations
I think the problem is that I have some styling in place for sticky footer:
body {
min-height: 100%;
}
#wrap, .navbar-wrapper {
min-height: 100%;
max-width: 1120px;
padding-top: 5px;
}
#main {
overflow:auto;
padding-bottom: 42px;
}
footer {
position: absolute;
left: 0;
bottom: 0;
height: 42px;
margin: 0 auto;
width: 100%;
}
The content of the page is:
<body>
<header-bar></header-bar>
<div id="wrap">
<div id="main">
CONTENT
</div>
</div>
<footer></footer>
I tried many manipulations of the preceding styles with no luck. Has
anyone faced this problem before? Thanks.
Can i code Assambly for x86 Windows from x64 Linux ?
Can i code Assambly for x86 Windows from x64 Linux ?
i have 64bit Ubuntu but i need to code ASM code for Intel 8086 Windows...
Is there any software or IDE or emulator you can suggest?
I know that there is different instructions for each kind of processor...
i have 64bit Ubuntu but i need to code ASM code for Intel 8086 Windows...
Is there any software or IDE or emulator you can suggest?
I know that there is different instructions for each kind of processor...
How can I lifecycle managed object in a Dagger graph
How can I lifecycle managed object in a Dagger graph
I can't see any support for life-cycle management in Dagger. Only DI, and
nothing for @PostConstruct or @PreDestroy (which I could use methinks).
I don't think it's possible to traverse the graph either!
How can I go about this?
I can't see any support for life-cycle management in Dagger. Only DI, and
nothing for @PostConstruct or @PreDestroy (which I could use methinks).
I don't think it's possible to traverse the graph either!
How can I go about this?
Deleting the contents of the file not working
Deleting the contents of the file not working
I'm writing, reading and deleting the content of a file. Eeverything works
fine except the delete part, as when i press y it says deleted but doesn't
display any records.
typedef struct ch
{
char str[10];
};
void disp(ch d)
{
cout<<"\n"<<d.str<<"\n";
}
//delete part
cout<<"\nwant to delete??";
char c;
cin>>c;
if(c=='y')
{
char s[10];
cout<<"nter - ";
cin>>s;
file.seekg(0);
int found=0;
fstream temp("temp.dat",ios::in|ios::out|ios::app);
while(file.read((char *)&dta,sizeof(dta)))
{
if(strcmp(dta.str,s)==0)
{
found=1;
cout<<"deleted";
}
else
temp.write((char *)&dta,sizeof(dta));
}
if(!found)
cout<<"not found";
remove("new.dat");
rename("temp.dat","new.dat");
temp.close();
file.open("new.dat",ios::in|ios::out|ios::app);
}
I'm writing, reading and deleting the content of a file. Eeverything works
fine except the delete part, as when i press y it says deleted but doesn't
display any records.
typedef struct ch
{
char str[10];
};
void disp(ch d)
{
cout<<"\n"<<d.str<<"\n";
}
//delete part
cout<<"\nwant to delete??";
char c;
cin>>c;
if(c=='y')
{
char s[10];
cout<<"nter - ";
cin>>s;
file.seekg(0);
int found=0;
fstream temp("temp.dat",ios::in|ios::out|ios::app);
while(file.read((char *)&dta,sizeof(dta)))
{
if(strcmp(dta.str,s)==0)
{
found=1;
cout<<"deleted";
}
else
temp.write((char *)&dta,sizeof(dta));
}
if(!found)
cout<<"not found";
remove("new.dat");
rename("temp.dat","new.dat");
temp.close();
file.open("new.dat",ios::in|ios::out|ios::app);
}
where caluse sql not working for me
where caluse sql not working for me
I am a beginner in sql. So please do not downvote my question. In my code
below, $i1 is a string and $l1 is also a string. The code is not working.
Any help will be appreciated. Thanks in advance. The following is my
code:-
$result = mysqli_query($con,"SELECT Ltno FROM Dept1_Selfin WHERE
Item='".$i1."' AND
Ltno='".$l1."'");
I am a beginner in sql. So please do not downvote my question. In my code
below, $i1 is a string and $l1 is also a string. The code is not working.
Any help will be appreciated. Thanks in advance. The following is my
code:-
$result = mysqli_query($con,"SELECT Ltno FROM Dept1_Selfin WHERE
Item='".$i1."' AND
Ltno='".$l1."'");
Friday, 16 August 2013
Trying to add image for menu items
Trying to add image for menu items
This is menu items and giving the image class in City menu item for example
<p:submenu label="Address">
<p:menuitem value="Country" url="/secured/country.xhtml?redirect=true" />
<p:menuitem value="State" url="/secured/state.xhtml?redirect=true" />
<p:menuitem value="City" url="/secured/city.xhtml?redirect=true"
icon="images"/>
<p:menuitem value="Location" url="/secured/location.xhtml?redirect=true" />
</p:submenu>
And this is my CSS class
.images{
background: url('../resources/images/admini.ico') no-repeat;
height:16px;
width:16px;
}
a upword arrow mark appears instead of an image
help me out with this problem
This is menu items and giving the image class in City menu item for example
<p:submenu label="Address">
<p:menuitem value="Country" url="/secured/country.xhtml?redirect=true" />
<p:menuitem value="State" url="/secured/state.xhtml?redirect=true" />
<p:menuitem value="City" url="/secured/city.xhtml?redirect=true"
icon="images"/>
<p:menuitem value="Location" url="/secured/location.xhtml?redirect=true" />
</p:submenu>
And this is my CSS class
.images{
background: url('../resources/images/admini.ico') no-repeat;
height:16px;
width:16px;
}
a upword arrow mark appears instead of an image
help me out with this problem
Thursday, 8 August 2013
BootStrap have mobile navbar entire bar dropdown
BootStrap have mobile navbar entire bar dropdown
My site is gitlit.org and when I go mobile or scale my browser the navbar
switches to the mobiel design without issues and I can click the three
white lines (menu) button and it works but clicking Home does nothing. Is
there a way so that the entire bar is clickable?
My navbar code:
<button type="button" class="navbar-toggle" data-toggle="collapse"
data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Home</a>
<div class="nav-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="about.html">About us</a></li>
<li><a href="#about">resources</a></li>
<li><a href="sermons.php">sermons</a></li>
<li><a href="#contact">contact us</a></li>
<li><a href="#contact">ministries</a></li>
<li><a href="#contact">blog</a></li>
</ul>
</div>
</div>
Here is my custom CSS that is applied to the NavBar, I did not edit the
main bootstrap css:
.navbar {
background-color: #000;
float: none;
}
.navbar-toggle {
border: 0px solid #000;
border-radius: 6px;
}
.navbar-nav > li > a {
color: white;
font-size: 13px;
text-decoration: none;
text-transform: uppercase;
}
.navbar-nav > .active > a, .navbar-nav > .active > a:hover, .navbar-nav >
.active > a:focus {
background-color: #000;
color: white;
}
.navbar-nav > .active > a:hover {
color: #fdbb20;
}
.navbar-nav > li > a:hover, .navbar-nav > li > a:focus {
color: #fdbb20;
}
.navbar-brand {
color: white;
font-size: 13px;
text-decoration: none;
text-transform: uppercase;
}
.navbar-brand:hover, .navbar-brand:focus {
color: #fdbb20;
}
My site is gitlit.org and when I go mobile or scale my browser the navbar
switches to the mobiel design without issues and I can click the three
white lines (menu) button and it works but clicking Home does nothing. Is
there a way so that the entire bar is clickable?
My navbar code:
<button type="button" class="navbar-toggle" data-toggle="collapse"
data-target=".nav-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<a class="navbar-brand" href="#">Home</a>
<div class="nav-collapse collapse">
<ul class="nav navbar-nav">
<li><a href="about.html">About us</a></li>
<li><a href="#about">resources</a></li>
<li><a href="sermons.php">sermons</a></li>
<li><a href="#contact">contact us</a></li>
<li><a href="#contact">ministries</a></li>
<li><a href="#contact">blog</a></li>
</ul>
</div>
</div>
Here is my custom CSS that is applied to the NavBar, I did not edit the
main bootstrap css:
.navbar {
background-color: #000;
float: none;
}
.navbar-toggle {
border: 0px solid #000;
border-radius: 6px;
}
.navbar-nav > li > a {
color: white;
font-size: 13px;
text-decoration: none;
text-transform: uppercase;
}
.navbar-nav > .active > a, .navbar-nav > .active > a:hover, .navbar-nav >
.active > a:focus {
background-color: #000;
color: white;
}
.navbar-nav > .active > a:hover {
color: #fdbb20;
}
.navbar-nav > li > a:hover, .navbar-nav > li > a:focus {
color: #fdbb20;
}
.navbar-brand {
color: white;
font-size: 13px;
text-decoration: none;
text-transform: uppercase;
}
.navbar-brand:hover, .navbar-brand:focus {
color: #fdbb20;
}
In-app link to the review page when the app isn't deployed yet
In-app link to the review page when the app isn't deployed yet
I have an app I'm about to deploy. With help of some earlier SO questions
I ended up with this URL, which correctly works in the app to activate
itunes on the 'Review' page of Bloons TD 5 (randomly picked as a test):
NSUrl("itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=563718995&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software");
My app isn't yet released, but the 'link' page on my (setup but not yet
uploaded) app page is this:
https://itunes.apple.com/us/app/geometry-caddy-easy-shape/id685851272?ls=1&mt=8
Transplanting my ID into it like the below gives me a 'newnullresponse'
error instead of a page.
NSUrl("itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=685851272&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software");
I tried it with and without leaving the 'id' prefix in.
Can I be confident in uploading my app that this link will start working
once the app is live on the store?
I have an app I'm about to deploy. With help of some earlier SO questions
I ended up with this URL, which correctly works in the app to activate
itunes on the 'Review' page of Bloons TD 5 (randomly picked as a test):
NSUrl("itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=563718995&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software");
My app isn't yet released, but the 'link' page on my (setup but not yet
uploaded) app page is this:
https://itunes.apple.com/us/app/geometry-caddy-easy-shape/id685851272?ls=1&mt=8
Transplanting my ID into it like the below gives me a 'newnullresponse'
error instead of a page.
NSUrl("itms-apps://itunes.apple.com/WebObjects/MZStore.woa/wa/viewContentsUserReviews?id=685851272&onlyLatestVersion=true&pageNumber=0&sortOrdering=1&type=Purple+Software");
I tried it with and without leaving the 'id' prefix in.
Can I be confident in uploading my app that this link will start working
once the app is live on the store?
Reliably store webpage offline in Android
Reliably store webpage offline in Android
My app has a 'pin' button like the Google Docs app:
Part of storing an item offline in my app is to store a complete webpage
including associated javascript and css.
Now, there are mutiple roads I can take, but I have difficulty judging
which will work. Here are the options I am considering:
The associated website already makes use of HTML5 caching (e.g., has a
manifest file which says which files should be cached), and this seems to
work fine. I could load in the web page in an invisible WebView so that it
will get cached.
Use WebView.saveWebArchive() on an invisible WebView and then load it
again when needed. This requires at least API level 11.
Store the HTML, javascript and CSS files through 'old school' means, e.g.,
get the input streams from the URL and store them in some folder.
As it looks now, option 1 is my preferred route. But what I am fretting
about is that the cache might be cleared on low memory. Is this, indeed,
the case?
My app has a 'pin' button like the Google Docs app:
Part of storing an item offline in my app is to store a complete webpage
including associated javascript and css.
Now, there are mutiple roads I can take, but I have difficulty judging
which will work. Here are the options I am considering:
The associated website already makes use of HTML5 caching (e.g., has a
manifest file which says which files should be cached), and this seems to
work fine. I could load in the web page in an invisible WebView so that it
will get cached.
Use WebView.saveWebArchive() on an invisible WebView and then load it
again when needed. This requires at least API level 11.
Store the HTML, javascript and CSS files through 'old school' means, e.g.,
get the input streams from the URL and store them in some folder.
As it looks now, option 1 is my preferred route. But what I am fretting
about is that the cache might be cleared on low memory. Is this, indeed,
the case?
How to set rule using regex in scrapy for extracting urls?
How to set rule using regex in scrapy for extracting urls?
I want to crawl pages related to Disney on bloomberg websites. The url
follow pattern as
"http://bloomberg.com/news/2013-07-08/disney-welcometohomepageofdisney"
So, i have written below rule for it
rules = [
Rule(SgmlLinkExtractor(allow=('/news/*/disney*',)), follow=True),
]
but the above rule doesn't working as i want and i am getting crawled
pages output not related to Disney. please help to fix this rule.
I want to crawl pages related to Disney on bloomberg websites. The url
follow pattern as
"http://bloomberg.com/news/2013-07-08/disney-welcometohomepageofdisney"
So, i have written below rule for it
rules = [
Rule(SgmlLinkExtractor(allow=('/news/*/disney*',)), follow=True),
]
but the above rule doesn't working as i want and i am getting crawled
pages output not related to Disney. please help to fix this rule.
return queries result like two cols
return queries result like two cols
I have these two queries,
SELECT date(d1.date) AS date, d3.country_name AS country_name, COUNT(*) AS
male
FROM f1
INNER JOIN d1 ON f1.id_start_date = d1.id_start_date
INNER JOIN d2 ON f1.id_end_date = d2.id_end_date
INNER JOIN d3 ON f1.id_user = d3.id_user AND d3.gender = 'M'
GROUP BY date, country_name
ORDER BY country_name
SELECT date(d1.date) AS date, d3.country_name AS country_name, COUNT(*) AS
female
FROM f1
INNER JOIN d1 ON f1.id_start_date = d1.id_start_date
INNER JOIN d2 ON f1.id_end_date = d2.id_end_date
INNER JOIN d3 ON f1.id_user = d3.id_user AND d3.gender = 'F'
GROUP BY date, country_name
ORDER BY country_name
that return me something like this:
date, country, male
2009-01-01, Spain, 34
and
date, country, female
2009-01-01, Spain, 12
but I need a query that return me this:
date, country, male, female
Any suggestion?
I have these two queries,
SELECT date(d1.date) AS date, d3.country_name AS country_name, COUNT(*) AS
male
FROM f1
INNER JOIN d1 ON f1.id_start_date = d1.id_start_date
INNER JOIN d2 ON f1.id_end_date = d2.id_end_date
INNER JOIN d3 ON f1.id_user = d3.id_user AND d3.gender = 'M'
GROUP BY date, country_name
ORDER BY country_name
SELECT date(d1.date) AS date, d3.country_name AS country_name, COUNT(*) AS
female
FROM f1
INNER JOIN d1 ON f1.id_start_date = d1.id_start_date
INNER JOIN d2 ON f1.id_end_date = d2.id_end_date
INNER JOIN d3 ON f1.id_user = d3.id_user AND d3.gender = 'F'
GROUP BY date, country_name
ORDER BY country_name
that return me something like this:
date, country, male
2009-01-01, Spain, 34
and
date, country, female
2009-01-01, Spain, 12
but I need a query that return me this:
date, country, male, female
Any suggestion?
Query interceptors: Change response status code
Query interceptors: Change response status code
Is it possible to change the HTTP status code returned by WCF Data
Services when one of the query interceptors return false?
As a bonus, is there a way to selectively return different status codes
depending on the query interceptor that failed?
Is it possible to change the HTTP status code returned by WCF Data
Services when one of the query interceptors return false?
As a bonus, is there a way to selectively return different status codes
depending on the query interceptor that failed?
Robolectric with Gradle: package org.robolectric does not exist
Robolectric with Gradle: package org.robolectric does not exist
I am trying to run robolectric tests with gradle android build system. I
have followed the instructions given here to try to make it work but while
running tests using gradle robolectric I am badly stuck at the following
error -
/Users/Sreekanth/Documents/artoo/Code/Android/HelloWorld/src/test/java/com/example/helloworld/MyTest.java:8:
package org.robolectric does not exist
import org.robolectric.RobolectricTestRunner;
My Project has the following structure -
.
„¥„Ÿ„Ÿ AndroidManifest.xml
„¥„Ÿ„Ÿ assets
„¥„Ÿ„Ÿ bin
„¥„Ÿ„Ÿ build.gradle
„¥„Ÿ„Ÿ gen
„¥„Ÿ„Ÿ libs
„¥„Ÿ„Ÿ res
„¤„Ÿ„Ÿ src
„¥„Ÿ„Ÿ main
„ „¤„Ÿ„Ÿ java
„ „¤„Ÿ„Ÿ com
„ „¤„Ÿ„Ÿ example
„ „¤„Ÿ„Ÿ helloworld
„ „¥„Ÿ„Ÿ MainActivity.java
„¤„Ÿ„Ÿ test
„¤„Ÿ„Ÿ java
„¤„Ÿ„Ÿ com
„¤„Ÿ„Ÿ example
„¤„Ÿ„Ÿ helloworld
„¤„Ÿ„Ÿ MyTest.java
Here is my build.gradle:
import com.android.build.gradle.api.TestVariant
buildscript {
repositories {
mavenCentral()
maven {
url "https://oss.sonatype.org/content/repositories/snapshots"
}
}
dependencies {
classpath 'com.android.tools.build:gradle:0.5.+'
classpath 'com.novoda.gradle:robolectric-plugin:0.0.1-SNAPSHOT'
}
}
apply plugin: 'android'
apply plugin: 'robolectric'
apply plugin: 'maven'
dependencies {
compile 'com.android.support:support-v4:13.0.+'
robolectricCompile 'org.robolectric:robolectric:2.0'
robolectricCompile group: 'junit', name: 'junit', version: '4.11'
}
repositories {
mavenLocal()
mavenCentral()
maven {
url "https://oss.sonatype.org/content/repositories/snapshots"
}
}
android {
compileSdkVersion 17
buildToolsVersion "17.0.0"
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
instrumentTest.setRoot('tests')
}
defaultConfig {
minSdkVersion 7
targetSdkVersion 18
}
}
My MyTest.java file:
package com.example.helloworld;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class MyTest {
@Test
public void shouldHaveHappySmiles() throws Exception {
String appName = new
MainActivity().getResources().getString(R.string.app_name);
assertThat(appName, equalTo("My Application"));
}
}
I can successfully run robolectric tests if I am using the new gradle
project structure but not if I am using old eclipse project structure like
the one mentioned above.
I am trying to run robolectric tests with gradle android build system. I
have followed the instructions given here to try to make it work but while
running tests using gradle robolectric I am badly stuck at the following
error -
/Users/Sreekanth/Documents/artoo/Code/Android/HelloWorld/src/test/java/com/example/helloworld/MyTest.java:8:
package org.robolectric does not exist
import org.robolectric.RobolectricTestRunner;
My Project has the following structure -
.
„¥„Ÿ„Ÿ AndroidManifest.xml
„¥„Ÿ„Ÿ assets
„¥„Ÿ„Ÿ bin
„¥„Ÿ„Ÿ build.gradle
„¥„Ÿ„Ÿ gen
„¥„Ÿ„Ÿ libs
„¥„Ÿ„Ÿ res
„¤„Ÿ„Ÿ src
„¥„Ÿ„Ÿ main
„ „¤„Ÿ„Ÿ java
„ „¤„Ÿ„Ÿ com
„ „¤„Ÿ„Ÿ example
„ „¤„Ÿ„Ÿ helloworld
„ „¥„Ÿ„Ÿ MainActivity.java
„¤„Ÿ„Ÿ test
„¤„Ÿ„Ÿ java
„¤„Ÿ„Ÿ com
„¤„Ÿ„Ÿ example
„¤„Ÿ„Ÿ helloworld
„¤„Ÿ„Ÿ MyTest.java
Here is my build.gradle:
import com.android.build.gradle.api.TestVariant
buildscript {
repositories {
mavenCentral()
maven {
url "https://oss.sonatype.org/content/repositories/snapshots"
}
}
dependencies {
classpath 'com.android.tools.build:gradle:0.5.+'
classpath 'com.novoda.gradle:robolectric-plugin:0.0.1-SNAPSHOT'
}
}
apply plugin: 'android'
apply plugin: 'robolectric'
apply plugin: 'maven'
dependencies {
compile 'com.android.support:support-v4:13.0.+'
robolectricCompile 'org.robolectric:robolectric:2.0'
robolectricCompile group: 'junit', name: 'junit', version: '4.11'
}
repositories {
mavenLocal()
mavenCentral()
maven {
url "https://oss.sonatype.org/content/repositories/snapshots"
}
}
android {
compileSdkVersion 17
buildToolsVersion "17.0.0"
sourceSets {
main {
manifest.srcFile 'AndroidManifest.xml'
java.srcDirs = ['src']
resources.srcDirs = ['src']
aidl.srcDirs = ['src']
renderscript.srcDirs = ['src']
res.srcDirs = ['res']
assets.srcDirs = ['assets']
}
instrumentTest.setRoot('tests')
}
defaultConfig {
minSdkVersion 7
targetSdkVersion 18
}
}
My MyTest.java file:
package com.example.helloworld;
import static org.hamcrest.CoreMatchers.equalTo;
import static org.junit.Assert.assertThat;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.robolectric.RobolectricTestRunner;
@RunWith(RobolectricTestRunner.class)
public class MyTest {
@Test
public void shouldHaveHappySmiles() throws Exception {
String appName = new
MainActivity().getResources().getString(R.string.app_name);
assertThat(appName, equalTo("My Application"));
}
}
I can successfully run robolectric tests if I am using the new gradle
project structure but not if I am using old eclipse project structure like
the one mentioned above.
Wednesday, 7 August 2013
crawler4j compile error with class CrawlConfig - VariableDeclaratorId Expected
crawler4j compile error with class CrawlConfig - VariableDeclaratorId
Expected
The code will not compile. I changed the JRE to 1.7. The compiler does not
highlight the class in Eclipse and the CrawlConfig appears to fail in the
compiler. The class should be run from the command line in Linux.
Any ideas?
Compiler Error - Description Resource Path Location Type Syntax error on
token "crawlStorageFolder", VariableDeclaratorId expected after this token
zeocrawler.java /zeowebcrawler/src/main/java/com/example line 95 Java
Problem
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
import edu.uci.ics.crawler4j.url.WebURL;
public class Controller {
String crawlStorageFolder = "/data/crawl/root";
int numberOfCrawlers = 7;
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new
RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config,
pageFetcher, robotstxtServer);
controller.addSeed("http://www.senym.com");
controller.addSeed("http://www.merrows.co.uk");
controller.addSeed("http://www.zeoic.com");
controller.start(MyCrawler.class, numberOfCrawlers);
}
public URLConnection connectURL(String strURL) {
URLConnection conn =null;
try {
URL inputURL = new URL(strURL);
conn = inputURL.openConnection();
int test = 0;
}catch(MalformedURLException e) {
System.out.println("Please input a valid URL");
}catch(IOException ioe) {
System.out.println("Can not connect to the URL");
}
return conn;
}
public static void updatelongurl()
{
// System.out.println("Short URL: "+ shortURL);
// urlConn = connectURL(shortURL);
// urlConn.getHeaderFields();
// System.out.println("Original URL: "+ urlConn.getURL());
/* connectURL - This function will take a valid url and return a
URL object representing the url address. */
}
public class MyCrawler extends WebCrawler {
private Pattern FILTERS =
Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g"
+
"|png|tiff?|mid|mp2|mp3|mp4"
+
"|wav|avi|mov|mpeg|ram|m4v|pdf"
+
"|rm|smil|wmv|swf|wma|zip|rar|gz))$");
/**
* You should implement this function to specify whether
* the given url should be crawled or not (based on your
* crawling logic).
*/
@Override
public boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase();
return !FILTERS.matcher(href).matches() &&
href.startsWith("http://www.ics.uci.edu/");
}
/**
* This function is called when a page is fetched and ready
* to be processed by your program.
*/
@Override
public void visit(Page page) {
String url = page.getWebURL().getURL();
System.out.println("URL: " + url);
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData)
page.getParseData();
String text = htmlParseData.getText();
String html = htmlParseData.getHtml();
List<WebURL> links = htmlParseData.getOutgoingUrls();
System.out.println("Text length: " + text.length());
System.out.println("Html length: " + html.length());
System.out.println("Number of outgoing links: " +
links.size());
}
}
}
Expected
The code will not compile. I changed the JRE to 1.7. The compiler does not
highlight the class in Eclipse and the CrawlConfig appears to fail in the
compiler. The class should be run from the command line in Linux.
Any ideas?
Compiler Error - Description Resource Path Location Type Syntax error on
token "crawlStorageFolder", VariableDeclaratorId expected after this token
zeocrawler.java /zeowebcrawler/src/main/java/com/example line 95 Java
Problem
import edu.uci.ics.crawler4j.crawler.CrawlConfig;
import edu.uci.ics.crawler4j.crawler.CrawlController;
import edu.uci.ics.crawler4j.crawler.Page;
import edu.uci.ics.crawler4j.crawler.WebCrawler;
import edu.uci.ics.crawler4j.fetcher.PageFetcher;
import edu.uci.ics.crawler4j.parser.HtmlParseData;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtConfig;
import edu.uci.ics.crawler4j.robotstxt.RobotstxtServer;
import edu.uci.ics.crawler4j.url.WebURL;
public class Controller {
String crawlStorageFolder = "/data/crawl/root";
int numberOfCrawlers = 7;
CrawlConfig config = new CrawlConfig();
config.setCrawlStorageFolder(crawlStorageFolder);
PageFetcher pageFetcher = new PageFetcher(config);
RobotstxtConfig robotstxtConfig = new RobotstxtConfig();
RobotstxtServer robotstxtServer = new
RobotstxtServer(robotstxtConfig, pageFetcher);
CrawlController controller = new CrawlController(config,
pageFetcher, robotstxtServer);
controller.addSeed("http://www.senym.com");
controller.addSeed("http://www.merrows.co.uk");
controller.addSeed("http://www.zeoic.com");
controller.start(MyCrawler.class, numberOfCrawlers);
}
public URLConnection connectURL(String strURL) {
URLConnection conn =null;
try {
URL inputURL = new URL(strURL);
conn = inputURL.openConnection();
int test = 0;
}catch(MalformedURLException e) {
System.out.println("Please input a valid URL");
}catch(IOException ioe) {
System.out.println("Can not connect to the URL");
}
return conn;
}
public static void updatelongurl()
{
// System.out.println("Short URL: "+ shortURL);
// urlConn = connectURL(shortURL);
// urlConn.getHeaderFields();
// System.out.println("Original URL: "+ urlConn.getURL());
/* connectURL - This function will take a valid url and return a
URL object representing the url address. */
}
public class MyCrawler extends WebCrawler {
private Pattern FILTERS =
Pattern.compile(".*(\\.(css|js|bmp|gif|jpe?g"
+
"|png|tiff?|mid|mp2|mp3|mp4"
+
"|wav|avi|mov|mpeg|ram|m4v|pdf"
+
"|rm|smil|wmv|swf|wma|zip|rar|gz))$");
/**
* You should implement this function to specify whether
* the given url should be crawled or not (based on your
* crawling logic).
*/
@Override
public boolean shouldVisit(WebURL url) {
String href = url.getURL().toLowerCase();
return !FILTERS.matcher(href).matches() &&
href.startsWith("http://www.ics.uci.edu/");
}
/**
* This function is called when a page is fetched and ready
* to be processed by your program.
*/
@Override
public void visit(Page page) {
String url = page.getWebURL().getURL();
System.out.println("URL: " + url);
if (page.getParseData() instanceof HtmlParseData) {
HtmlParseData htmlParseData = (HtmlParseData)
page.getParseData();
String text = htmlParseData.getText();
String html = htmlParseData.getHtml();
List<WebURL> links = htmlParseData.getOutgoingUrls();
System.out.println("Text length: " + text.length());
System.out.println("Html length: " + html.length());
System.out.println("Number of outgoing links: " +
links.size());
}
}
}
Subscribe to:
Posts (Atom)