Creating mkfifo with GNU Coreutils on Windows 7
Running GNU Coreutils on Windows 7 successfully. But cannot create a
mkfifo . From all the documentation I've seen, this should be possible.
I start with:
C:\Users\Ed>mkfifo pipe
and get:
mkfifo: cannot create fifo `pipe'
Any suggestions ?
Saturday, 31 August 2013
Will a CRON job be suitable for this?
Will a CRON job be suitable for this?
I have a database with an email address, an interval of how often someone
wants an email sent to them (ranges from every 5 minutes to every couple
of days) and the time at which an email was last sent. I currently have a
PHP script that runs through the database and finds times before the
current time and sends them an email and updates the time at which it is
scheduled send the new email (using the interval).
Would it be OK to set this script up as a CRON job and run it every say 4
minutes? Or would this create too much overhead? I have 500+ tuples of
data that it will need to traverse every 4 minutes.
I have a database with an email address, an interval of how often someone
wants an email sent to them (ranges from every 5 minutes to every couple
of days) and the time at which an email was last sent. I currently have a
PHP script that runs through the database and finds times before the
current time and sends them an email and updates the time at which it is
scheduled send the new email (using the interval).
Would it be OK to set this script up as a CRON job and run it every say 4
minutes? Or would this create too much overhead? I have 500+ tuples of
data that it will need to traverse every 4 minutes.
Confused about the behaviour of concat() and the object it returns
Confused about the behaviour of concat() and the object it returns
Consider this example:
var a, b, c, d;
a = new Array(1,2,3);
b = "dog";
c = new Array(42, "cat");
d = a.concat(b, c);
document.write(d); // outputs 1, 2, 3, dog, 42, cat - makes sense
What I don't get is:
alert(b[0]); // d
alert(b[1]); // o
.. etc.
I understand concat() returns a new array object, but why does it slice
the string "dog" into individual array elements? I would've expected b[0]
to return "dog" and b[1] to return undefined. Sorry if this is a stupid
question :/
Consider this example:
var a, b, c, d;
a = new Array(1,2,3);
b = "dog";
c = new Array(42, "cat");
d = a.concat(b, c);
document.write(d); // outputs 1, 2, 3, dog, 42, cat - makes sense
What I don't get is:
alert(b[0]); // d
alert(b[1]); // o
.. etc.
I understand concat() returns a new array object, but why does it slice
the string "dog" into individual array elements? I would've expected b[0]
to return "dog" and b[1] to return undefined. Sorry if this is a stupid
question :/
explain me a preg_match if clause please
explain me a preg_match if clause please
if(preg_match("/^[\w_.]+$/",stripslashes($_GET['key']))) {
$key = $wpdb->escape(stripslashes($_GET['key']));
}
assuming the key value is = be4e53680e6518cca701ec091258642f0740fe3d
can someone please explain me the if condition ? I`m confused on what
exactly it checks for
if(preg_match("/^[\w_.]+$/",stripslashes($_GET['key']))) {
$key = $wpdb->escape(stripslashes($_GET['key']));
}
assuming the key value is = be4e53680e6518cca701ec091258642f0740fe3d
can someone please explain me the if condition ? I`m confused on what
exactly it checks for
Monitor Kill by task manager callback
Monitor Kill by task manager callback
How can I find out the moment, when my android application will be killed
by task manager. If there any callback in Activity class or something
else?
How can I find out the moment, when my android application will be killed
by task manager. If there any callback in Activity class or something
else?
Whats the point of i++ when ++i "can" be faster in c++?
Whats the point of i++ when ++i "can" be faster in c++?
I've been reading quite a few posts/questions about the micro-optimization
of ++i and i++ in C++. And from what I've learnt is that ++i "can", not
always, but can be faster than i++.
So this makes me ask this question, whats the point of i++ then? I thought
that ++i is that you increment the value first then return it. Where as
i++ you return the value then increment it. But I have made a very simple
test on this:
for(int i = 0; i < 10; ++i)
{
std::cout << i << std::endl;
}
is the same as:
for(int i = 0; i < 10; i++)
{
std::cout << i << std::endl;
}
Both prints out the same results. So my real question is that is there a
situation where you MUST use i++ rather than ++i? If there is, please
explain. Thanks
I've been reading quite a few posts/questions about the micro-optimization
of ++i and i++ in C++. And from what I've learnt is that ++i "can", not
always, but can be faster than i++.
So this makes me ask this question, whats the point of i++ then? I thought
that ++i is that you increment the value first then return it. Where as
i++ you return the value then increment it. But I have made a very simple
test on this:
for(int i = 0; i < 10; ++i)
{
std::cout << i << std::endl;
}
is the same as:
for(int i = 0; i < 10; i++)
{
std::cout << i << std::endl;
}
Both prints out the same results. So my real question is that is there a
situation where you MUST use i++ rather than ++i? If there is, please
explain. Thanks
Matlab functions and parallel_invoke
Matlab functions and parallel_invoke
In my project I have a lot of MATLAB functions. For each function I call
Initialize function, when the application starts. I tried to call this
functions using parallel_invoke. I tried it several times and allways it
takes more time, that code without this. Can somebody explain this ? Is
there is something specific in MATLAB or Initialize functions ?
In my project I have a lot of MATLAB functions. For each function I call
Initialize function, when the application starts. I tried to call this
functions using parallel_invoke. I tried it several times and allways it
takes more time, that code without this. Can somebody explain this ? Is
there is something specific in MATLAB or Initialize functions ?
Friday, 30 August 2013
How do I indicate collate order in Roxygen2?
How do I indicate collate order in Roxygen2?
Using roxygen2 documentation with devtools document function automatically
generates a Collate: field in the package DESCRIPTION, regardless of
whether or not it is necessary to load the package library files in a
particular order.
I'm working on a package with a bunch of S4 methods and want to be sure
the class definitions are loaded before any methods or other classes using
them, which I understand I can do with the Collate list, but I'm not sure
how to indicate this in the roxygen2 documentation format.
The roxygen2 manual makes some reference to an @import tag but that looks
like it actually imports code, for instance, for an example file.
Using roxygen2 documentation with devtools document function automatically
generates a Collate: field in the package DESCRIPTION, regardless of
whether or not it is necessary to load the package library files in a
particular order.
I'm working on a package with a bunch of S4 methods and want to be sure
the class definitions are loaded before any methods or other classes using
them, which I understand I can do with the Collate list, but I'm not sure
how to indicate this in the roxygen2 documentation format.
The roxygen2 manual makes some reference to an @import tag but that looks
like it actually imports code, for instance, for an example file.
Thursday, 29 August 2013
Textbox value in other textbox by clicking button not correct
Textbox value in other textbox by clicking button not correct
This program have a link which is fixed and never change. And it contains
5 textboxes. The fixed link is:
<seite>utm_source=<website>_<page>_de&utm_medium=banner&utm_campaign=<kampagne>&utm_content=<format>
Every value in <> should be changed by textbox value. Here you got an
image of my little program:
Now my problem is: the first value is correct, but the other values
aren't. So for example, if i type in second texbox: "website" it does not
only replace <website> with "website". it replaced <website> with
System.Windows.Forms.TextBox, Text: website.
My Code I tried:
private void btn_SendAll_Click(object sender, EventArgs e)
{
txt_FinishLink.Text = txt_Site.Text + "utm_source=" +
txt_Website + "_" + txt_Page +
"_de&utm_medium=banner&utm_campaign=" + txt_Campaign +
"&utm_content=" + txt_Format;
}
This program have a link which is fixed and never change. And it contains
5 textboxes. The fixed link is:
<seite>utm_source=<website>_<page>_de&utm_medium=banner&utm_campaign=<kampagne>&utm_content=<format>
Every value in <> should be changed by textbox value. Here you got an
image of my little program:
Now my problem is: the first value is correct, but the other values
aren't. So for example, if i type in second texbox: "website" it does not
only replace <website> with "website". it replaced <website> with
System.Windows.Forms.TextBox, Text: website.
My Code I tried:
private void btn_SendAll_Click(object sender, EventArgs e)
{
txt_FinishLink.Text = txt_Site.Text + "utm_source=" +
txt_Website + "_" + txt_Page +
"_de&utm_medium=banner&utm_campaign=" + txt_Campaign +
"&utm_content=" + txt_Format;
}
Database operation in one go (one transcation)
Database operation in one go (one transcation)
I am working on a driver-booking management system. What I want to do is
that I need to add a driver in booking table (which means assigning a
booking to driver). Before that I need to check whether or not booking
record has driver record associated with or not (booking is assigned or
not), If yes then do nothing.
It works fine with one user doing this. But issue comes with multiple
users doing this on same record, same time.
How to handle this situation. I know about @transactional annotation. Is
that the right solution? Should I apply this on single method rather than
on my booking Assigning Service?
Using sync block would slow down processing alot, so currently I am
against this option
I am working on a driver-booking management system. What I want to do is
that I need to add a driver in booking table (which means assigning a
booking to driver). Before that I need to check whether or not booking
record has driver record associated with or not (booking is assigned or
not), If yes then do nothing.
It works fine with one user doing this. But issue comes with multiple
users doing this on same record, same time.
How to handle this situation. I know about @transactional annotation. Is
that the right solution? Should I apply this on single method rather than
on my booking Assigning Service?
Using sync block would slow down processing alot, so currently I am
against this option
How to keep current JSESSIONID on multiple request calls?
How to keep current JSESSIONID on multiple request calls?
i am trying to keep current session id but i am failing. I have 2 separate
methods that call the same method
i.e.
$foo1->method
$foo2->method
inside the method there is cURL for sending data to servlet. What is
happening at the moment is that each request call generates new session
id, and thats not good. How do i keep set session id once and keep on
reusing it ??
Code below:
public function curlWithID($url, $value){
echo "session has id";
}
public function curlWithoutID($url, $value){
Global $result;
$m = array();
$size = sizeof($m);
if(isset($_SESSION['JSESSIONID'])? : null){
$this->curlWithID($url, $value);
}
else{
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
session_write_close();
$ch = curl_init();
//Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $value);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);
if(preg_match('/Set-Cookie: JSESSIONID=(.*?);/', $result, $m))
{
//set cookie
$_SESSION['JSESSIONID'] = $m[1];
echo $m[1];
}
}
This is my attempt so far. Help appreciated, thanks
i am trying to keep current session id but i am failing. I have 2 separate
methods that call the same method
i.e.
$foo1->method
$foo2->method
inside the method there is cURL for sending data to servlet. What is
happening at the moment is that each request call generates new session
id, and thats not good. How do i keep set session id once and keep on
reusing it ??
Code below:
public function curlWithID($url, $value){
echo "session has id";
}
public function curlWithoutID($url, $value){
Global $result;
$m = array();
$size = sizeof($m);
if(isset($_SESSION['JSESSIONID'])? : null){
$this->curlWithID($url, $value);
}
else{
if (!function_exists('curl_init')){
die('Sorry cURL is not installed!');
}
session_write_close();
$ch = curl_init();
//Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $value);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HEADER, 1);
$result = curl_exec($ch);
if(preg_match('/Set-Cookie: JSESSIONID=(.*?);/', $result, $m))
{
//set cookie
$_SESSION['JSESSIONID'] = $m[1];
echo $m[1];
}
}
This is my attempt so far. Help appreciated, thanks
Wednesday, 28 August 2013
ADMA0002E: A validation error occurred in task Binding enterprise Bean to JNDI
ADMA0002E: A validation error occurred in task Binding enterprise Bean to
JNDI
While installing the current package, the following error messages are
received: 1) WASX7017E: Exception received while running file
"/opt/Install_SIPR/updateSiprEar.py"; exception information:
com.ibm.ws.scripting.ScriptingException: WASX7108E: Invalid data specified
for install task: "BindJndiForEJBNonMessageBinding." Errors are: " 2)
ADMA0002E: A validation error occurred in task Binding enterprise Bean to
JNDI names. The Java Naming and Directory Interface (JNDI) name is not
specified for enterprise bean DqEvalPersistService in module GfmEjb. 3)
ADMA0002E: A validation error occurred in task Binding enterprise Bean to
JNDI names. The Java Naming and Directory Interface (JNDI) name is not
specified for enterprise bean JumService in module GfmEjb."
The messages are associated to the following statement:
AdminApp.update(appName, 'app', '[ -operation update -contents ' +
earFileName + ' -nopreCompileJSPs -installed.ear.destination
$(APP_INSTALL_ROOT)/' + cell + ' -distributeApp -nouseMetaDataFromBinary
-deployejb -createMBeansForResources -noreloadEnabled -nodeployws
-validateinstall warn -noprocessEmbeddedConfig -filepermission
.*\.dll=755#.*\.so=755#.*\.a=755#.*\.sl=755 -noallowDispatchRemoteInclude
-noallowServiceRemoteInclude -asyncRequestDispatchType DISABLED
-nouseAutoLink -MapResRefToEJB [[ GfmEjb EventHandlerMDB
GfmEjb.jar,META-INF/ejb-jar.xml mail/DefaultMail javax.mail.Session
mail/DefaultMail "" "" "" ][ GfmWebServices "" GfmWeb.war,WEB-INF/web.xml
mail/DefaultMail javax.mail.Session mail/DefaultMail "" "" "" ][
GfmWebServices "" GfmWeb.war,WEB-INF/web.xml GfmOracle
javax.sql.DataSource jdbc/GFMDS "" "" "" ][ GfmEjb EventHandlerMDB
GfmEjb.jar,META-INF/ejb-jar.xml GfmOracle javax.sql.DataSource jdbc/GFMDS
"" "" "" ]] -MapModulesToServers [[ GfmEjb GfmEjb.jar,META-INF/ejb-jar.xml
' + installString + ' ][ GfmWebServices GfmWeb.war,WEB-INF/web.xml ' +
installString + ' ]]]' )
NOTE: the installString contains cell, node, appServer, allwebservers, and
allwebserverNodes information.
What am I doing wrong?
Thanks for the assistance.
JNDI
While installing the current package, the following error messages are
received: 1) WASX7017E: Exception received while running file
"/opt/Install_SIPR/updateSiprEar.py"; exception information:
com.ibm.ws.scripting.ScriptingException: WASX7108E: Invalid data specified
for install task: "BindJndiForEJBNonMessageBinding." Errors are: " 2)
ADMA0002E: A validation error occurred in task Binding enterprise Bean to
JNDI names. The Java Naming and Directory Interface (JNDI) name is not
specified for enterprise bean DqEvalPersistService in module GfmEjb. 3)
ADMA0002E: A validation error occurred in task Binding enterprise Bean to
JNDI names. The Java Naming and Directory Interface (JNDI) name is not
specified for enterprise bean JumService in module GfmEjb."
The messages are associated to the following statement:
AdminApp.update(appName, 'app', '[ -operation update -contents ' +
earFileName + ' -nopreCompileJSPs -installed.ear.destination
$(APP_INSTALL_ROOT)/' + cell + ' -distributeApp -nouseMetaDataFromBinary
-deployejb -createMBeansForResources -noreloadEnabled -nodeployws
-validateinstall warn -noprocessEmbeddedConfig -filepermission
.*\.dll=755#.*\.so=755#.*\.a=755#.*\.sl=755 -noallowDispatchRemoteInclude
-noallowServiceRemoteInclude -asyncRequestDispatchType DISABLED
-nouseAutoLink -MapResRefToEJB [[ GfmEjb EventHandlerMDB
GfmEjb.jar,META-INF/ejb-jar.xml mail/DefaultMail javax.mail.Session
mail/DefaultMail "" "" "" ][ GfmWebServices "" GfmWeb.war,WEB-INF/web.xml
mail/DefaultMail javax.mail.Session mail/DefaultMail "" "" "" ][
GfmWebServices "" GfmWeb.war,WEB-INF/web.xml GfmOracle
javax.sql.DataSource jdbc/GFMDS "" "" "" ][ GfmEjb EventHandlerMDB
GfmEjb.jar,META-INF/ejb-jar.xml GfmOracle javax.sql.DataSource jdbc/GFMDS
"" "" "" ]] -MapModulesToServers [[ GfmEjb GfmEjb.jar,META-INF/ejb-jar.xml
' + installString + ' ][ GfmWebServices GfmWeb.war,WEB-INF/web.xml ' +
installString + ' ]]]' )
NOTE: the installString contains cell, node, appServer, allwebservers, and
allwebserverNodes information.
What am I doing wrong?
Thanks for the assistance.
How to properly declare a an empty list as a default parameter [duplicate]
How to properly declare a an empty list as a default parameter [duplicate]
This question already has an answer here:
"Least Astonishment" in Python: The Mutable Default Argument 20 answers
I've been told I should use;
def some_method(self,a,b=[]):
etc...
instead of
def some_method(self,a,b=list()):
etc...
'just because' .. well, I want to know 'why'!
As far as I am aware, there is no real difference between the two?
This question already has an answer here:
"Least Astonishment" in Python: The Mutable Default Argument 20 answers
I've been told I should use;
def some_method(self,a,b=[]):
etc...
instead of
def some_method(self,a,b=list()):
etc...
'just because' .. well, I want to know 'why'!
As far as I am aware, there is no real difference between the two?
Special Case to Replace String Using Python with Regex
Special Case to Replace String Using Python with Regex
I'd like to replace decimal point but not period in one content.
For example:
Original Content:
This is a cake. It is 1.45 dollars and 2.38 kg.
Replaced Content:
This is a cake. It cost 1<replace>45 dollars and 2<replace>38 kg.
How can I use Python Regex to do it ?
Thank you very much.
I'd like to replace decimal point but not period in one content.
For example:
Original Content:
This is a cake. It is 1.45 dollars and 2.38 kg.
Replaced Content:
This is a cake. It cost 1<replace>45 dollars and 2<replace>38 kg.
How can I use Python Regex to do it ?
Thank you very much.
Tuesday, 27 August 2013
CSS - How to apply rule to classes when they are children of either of two parent classes?
CSS - How to apply rule to classes when they are children of either of two
parent classes?
I have parents .category-view and .search-results.
Each of those can have child .special-price that I want to style.
But I do not want to style .product-view .special-price.
Must I spell out multiple paths like this:
.category-view .special-price, .search-results .special-price {
}
Or is there a shorter way, something like
.category-view/.search-results .special-price {
}
Furthermore, I actually want to style both .special-price and .old-price,
so is there some way to do that? Like
.category-view/.search-results .special-price/.old-price {
}
... that would affect both of those children when they are below either of
those parents?
parent classes?
I have parents .category-view and .search-results.
Each of those can have child .special-price that I want to style.
But I do not want to style .product-view .special-price.
Must I spell out multiple paths like this:
.category-view .special-price, .search-results .special-price {
}
Or is there a shorter way, something like
.category-view/.search-results .special-price {
}
Furthermore, I actually want to style both .special-price and .old-price,
so is there some way to do that? Like
.category-view/.search-results .special-price/.old-price {
}
... that would affect both of those children when they are below either of
those parents?
FuelPHP Get "Not null violation" on foreign key trying to insert into related model
FuelPHP Get "Not null violation" on foreign key trying to insert into
related model
I'm trying to insert into the table of a model with multiple levels of
HasMany relationships. Here's the breakdown so far
Customer->(HasMany)->Members->(HasMany)->Incomes
However, on when trying to insert into the Incomes table, I get a "Not
null violation" with the foreign key from the Members table not being
carried to Incomes. I know the most common problem is screwing up the
$_has_many and $_belongs_to properties, but as far as I can tell they are
fine. Plus, Just inserting into the Member table works fine so I know at
least for the first layer it's working! The only thing I can think of is
if since it's a second level down, it's screwing up because of that.
Here's my code:
Relation Link (Member)
protected static $_has_many = array(
'incomes' => array(
'key_from' => 'id',
'model_to' => 'Model_Income',
'key_to' => 'member_id',
'cascade_save' => true,
'cascade_delete' => true,
),
);
Relation Link (Income)
protected static $_belongs_to = array(
'member' => array(
'key_from' => 'member_id',
'model_to' => 'Model_Member',
'key_to' => 'id',
'cascade_save' => true,
'cascade_delete' => true,
),
);
The Controller Code
// code to set up $customer
$customer->members[] = Model_Member::forge();
// set $member_vals here
$customer->members[0]->set($member_vals);
$customer->members[0]->incomes[] = Model_Income::forge();
// set $income_vals here
$customer->members[0]->incomes[0]->set($income_vals);
$customer->save();
related model
I'm trying to insert into the table of a model with multiple levels of
HasMany relationships. Here's the breakdown so far
Customer->(HasMany)->Members->(HasMany)->Incomes
However, on when trying to insert into the Incomes table, I get a "Not
null violation" with the foreign key from the Members table not being
carried to Incomes. I know the most common problem is screwing up the
$_has_many and $_belongs_to properties, but as far as I can tell they are
fine. Plus, Just inserting into the Member table works fine so I know at
least for the first layer it's working! The only thing I can think of is
if since it's a second level down, it's screwing up because of that.
Here's my code:
Relation Link (Member)
protected static $_has_many = array(
'incomes' => array(
'key_from' => 'id',
'model_to' => 'Model_Income',
'key_to' => 'member_id',
'cascade_save' => true,
'cascade_delete' => true,
),
);
Relation Link (Income)
protected static $_belongs_to = array(
'member' => array(
'key_from' => 'member_id',
'model_to' => 'Model_Member',
'key_to' => 'id',
'cascade_save' => true,
'cascade_delete' => true,
),
);
The Controller Code
// code to set up $customer
$customer->members[] = Model_Member::forge();
// set $member_vals here
$customer->members[0]->set($member_vals);
$customer->members[0]->incomes[] = Model_Income::forge();
// set $income_vals here
$customer->members[0]->incomes[0]->set($income_vals);
$customer->save();
Slow MySQL in VMWare, but Apache works ok
Slow MySQL in VMWare, but Apache works ok
I have OSX running VMWare with W7 Pro. This machine is configured to
bridge the network adapter, so it's in the same network of OSX but with a
different local IP. I installed Apache and MySQL, and I use virtual hosts;
so far, so good. Any virtual hosts that I create that don't use MySQL
(just static HTML or PHP sites) load really fast on OSX's browsers, but
sites that need to use MySQL take a long time to load. I've investigated a
lot (as far as my language understanding allows) and the only solution
that worked partially is to use
skip-name-resolve
This accelerated the loading time from 10 seconds to 8 or 7, but it's
still annoying for development, and more if other sites load immediately.
I appreciate any help you could give me.
I have OSX running VMWare with W7 Pro. This machine is configured to
bridge the network adapter, so it's in the same network of OSX but with a
different local IP. I installed Apache and MySQL, and I use virtual hosts;
so far, so good. Any virtual hosts that I create that don't use MySQL
(just static HTML or PHP sites) load really fast on OSX's browsers, but
sites that need to use MySQL take a long time to load. I've investigated a
lot (as far as my language understanding allows) and the only solution
that worked partially is to use
skip-name-resolve
This accelerated the loading time from 10 seconds to 8 or 7, but it's
still annoying for development, and more if other sites load immediately.
I appreciate any help you could give me.
create sql table in SQLServer with the name of the current session variable c#
create sql table in SQLServer with the name of the current session
variable c#
I am developing an application in c #. Net and I need to create a table in
sql with the name of the current session variable. How I can send the
value of the session variable to current sql server to create this query?
My idea is something like this: In sql server:
CREATE TABLE Customer_ + 'current user name' // current session variable
in c#
(First_Name char(50),
Last_Name char(50),
Address char(50),
City char(50),
Country char(25),
Birth_Date datetime);
Thank you very much for your help.
variable c#
I am developing an application in c #. Net and I need to create a table in
sql with the name of the current session variable. How I can send the
value of the session variable to current sql server to create this query?
My idea is something like this: In sql server:
CREATE TABLE Customer_ + 'current user name' // current session variable
in c#
(First_Name char(50),
Last_Name char(50),
Address char(50),
City char(50),
Country char(25),
Birth_Date datetime);
Thank you very much for your help.
Is it possible to cancel a Google Maps API polyline while it's being drawn?
Is it possible to cancel a Google Maps API polyline while it's being drawn?
I've built a Google Maps API toolset that allows the user to draw shapes
over the map, give them names and record areas. On the completion of each
shape, they are prompted to give it a name and set a few other options
such as whether or not to show a label on the map.
I'd like to give the user the option to right click and cancel a polyline
(or polygon) whilst placing the points, i.e. while they're drawing it.
Based on what I've read in the documentation, I should be able to detect
that the user right clicked on the map, but I'm not sure how to cancel the
overlay they were drawing, as it won't have been committed to the map yet,
which means I won't be able to refer to it as an object.
Any ideas?
I've built a Google Maps API toolset that allows the user to draw shapes
over the map, give them names and record areas. On the completion of each
shape, they are prompted to give it a name and set a few other options
such as whether or not to show a label on the map.
I'd like to give the user the option to right click and cancel a polyline
(or polygon) whilst placing the points, i.e. while they're drawing it.
Based on what I've read in the documentation, I should be able to detect
that the user right clicked on the map, but I'm not sure how to cancel the
overlay they were drawing, as it won't have been committed to the map yet,
which means I won't be able to refer to it as an object.
Any ideas?
how to sum how many days from text fields in the 3rd textbox using datepicker
how to sum how many days from text fields in the 3rd textbox using datepicker
i have the following code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Sum Of Total Days</title>
<link rel="stylesheet" href="jquery-ui.css" />
<script src="jquery-1.9.1.js"></script>
<script src="jquery-ui.js"></script>
<script>
$(function sum() {
datepickerln1 = $( "#datepickerln1" ).datepicker().value;
datepickerln2 = $( "#datepickerln2" ).datepicker().value;
document.getElementById('#total').value = parseFloat(datepickerln2) -
parseFloat(datepickerln1) +1;
});
</script>
</head>
<body>
<p>Date 1: <input name="datepickerln1" id="datepickerln1" type="text"
onblur="sum()"/></p>
<p>Date 2: <input name="datepickerln2" id="datepickerln2" type="text"
onblur="sum()"/></p>
<input name="total" id ="total" type="text" readonly />
</body>
</html>
it is not doing sum of the total days when i put the date using datepicker
in Date 1 & Date 2.
Please help
thanks
i have the following code:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Sum Of Total Days</title>
<link rel="stylesheet" href="jquery-ui.css" />
<script src="jquery-1.9.1.js"></script>
<script src="jquery-ui.js"></script>
<script>
$(function sum() {
datepickerln1 = $( "#datepickerln1" ).datepicker().value;
datepickerln2 = $( "#datepickerln2" ).datepicker().value;
document.getElementById('#total').value = parseFloat(datepickerln2) -
parseFloat(datepickerln1) +1;
});
</script>
</head>
<body>
<p>Date 1: <input name="datepickerln1" id="datepickerln1" type="text"
onblur="sum()"/></p>
<p>Date 2: <input name="datepickerln2" id="datepickerln2" type="text"
onblur="sum()"/></p>
<input name="total" id ="total" type="text" readonly />
</body>
</html>
it is not doing sum of the total days when i put the date using datepicker
in Date 1 & Date 2.
Please help
thanks
Monday, 26 August 2013
How to intercept double click event on a folder on osx?
How to intercept double click event on a folder on osx?
experts. what I want is like this: I create a folder named RootDir, then I
double click the folder in Finder , I hope I can intercept the action and
trigger specific action such as mounting this RootDir to another folder
named MountDir and then open MountDir, not RootDir. how should I do it
(Using objective-c)? my platform is mountain lion (osx10.8) and I've tried
using fsevent to monitor, but i don't think i can catch the action of
folder open/close.... and is it the only way for me to use Finder
injection to achieve this function? any suggestions would be appreciated.
experts. what I want is like this: I create a folder named RootDir, then I
double click the folder in Finder , I hope I can intercept the action and
trigger specific action such as mounting this RootDir to another folder
named MountDir and then open MountDir, not RootDir. how should I do it
(Using objective-c)? my platform is mountain lion (osx10.8) and I've tried
using fsevent to monitor, but i don't think i can catch the action of
folder open/close.... and is it the only way for me to use Finder
injection to achieve this function? any suggestions would be appreciated.
Evaluating the output of a program as an integer
Evaluating the output of a program as an integer
pI'm trying to create a script that will evaluate the output of a command
line, and then print if it's larger than 200./p pThe program
code/exc/list/code will count the number of stories I have in a directory
as an expression. For example:/p precode/exc/list q show.today1.rundown
/code/pre pwill return 161 if there are 161 stories in the today1
rundown./p pI have to figure this for 23 different directories. If the
number of stories is greater than 200, I need it to print it to a temp
file (code/tmp/StoryCount.$date/code)./p pWhat's the best method to handle
this comparison?/p
pI'm trying to create a script that will evaluate the output of a command
line, and then print if it's larger than 200./p pThe program
code/exc/list/code will count the number of stories I have in a directory
as an expression. For example:/p precode/exc/list q show.today1.rundown
/code/pre pwill return 161 if there are 161 stories in the today1
rundown./p pI have to figure this for 23 different directories. If the
number of stories is greater than 200, I need it to print it to a temp
file (code/tmp/StoryCount.$date/code)./p pWhat's the best method to handle
this comparison?/p
Add parameters vimeo videos using wordpress embeds
Add parameters vimeo videos using wordpress embeds
I am using a custom field to embed any supported video on Wordpress so for
example the user enters a video address on the custom field box :
http://vimeo.com/72104173
and I implemented the following code on my theme :
<?php
$videourl = my_meta('video'); // get custom field value
if($videourl!=''){ // if custom field exist ?>
<?php
$htmlcode = wp_oembed_get("{$videourl}"); //use oembed
echo "<div class='video'>{$htmlcode}</div>"; //output the video ?>
...
the result/output is below :
<iframe ... src="http://player.vimeo.com/video/72104173"></iframe>
the problem is that I want to add extra parameters to the vimeo so I can
hide the Title and Byline of the video by adding the following to the src
:
?title=0&byline=0&portrait=0
so the final result will be :
<iframe ...
src="http://player.vimeo.com/video/72104173?title=0&byline=0&portrait=0"></iframe>
I tried to user str_replace but the problem is that the parameters are
added to the end of each video src and the surce is going to be different
each time,
really appreciate any help, thanks
I am using a custom field to embed any supported video on Wordpress so for
example the user enters a video address on the custom field box :
http://vimeo.com/72104173
and I implemented the following code on my theme :
<?php
$videourl = my_meta('video'); // get custom field value
if($videourl!=''){ // if custom field exist ?>
<?php
$htmlcode = wp_oembed_get("{$videourl}"); //use oembed
echo "<div class='video'>{$htmlcode}</div>"; //output the video ?>
...
the result/output is below :
<iframe ... src="http://player.vimeo.com/video/72104173"></iframe>
the problem is that I want to add extra parameters to the vimeo so I can
hide the Title and Byline of the video by adding the following to the src
:
?title=0&byline=0&portrait=0
so the final result will be :
<iframe ...
src="http://player.vimeo.com/video/72104173?title=0&byline=0&portrait=0"></iframe>
I tried to user str_replace but the problem is that the parameters are
added to the end of each video src and the surce is going to be different
each time,
really appreciate any help, thanks
Listing terms used by a custom post type (the taxonomy is shared across multiple CPT)
Listing terms used by a custom post type (the taxonomy is shared across
multiple CPT)
I have multiple custom post types and they share some custom taxonomies. I
want to a (hierarchy format) drop down of only the terms used by a
specific custom post type - the drop down will be the filter for the
archive-post-type.php page.
CPTs: Winery, Wines, plus others (but not relevant)
Taxonomies: Regions, Wine Types, plus others (but not relevant)
Wineries will not exist in all regions that wines do - but when listing
the terms it shows all of them. I need to hide any terms that are not
being used by the Winery custom post type.
The output would be a url in the format
http://website.com/winery-profiles/?regions=victoria (which works) just
need to get the list of terms ONLY used by the winery CPT
Any help would be appreciated!
Here is where i'm at:
function get_terms_by_cpt($taxonomy, $post_types=array() ){ global $wpdb;
$post_types=(array) $post_types;
$key = 'wpse_terms'.md5($taxonomy.serialize($post_types));
$results = wp_cache_get($key);
if ( false === $results ) {
$where =" WHERE 1=1";
if( !empty($post_types) ){
$post_types_str = implode(',',$post_types);
$where.= $wpdb->prepare(" AND p.post_type IN(%s)", $post_types_str);
}
$where .= $wpdb->prepare(" AND tt.taxonomy = %s",$taxonomy);
$query = "
SELECT t.*
FROM $wpdb->terms AS t
INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id
INNER JOIN $wpdb->term_relationships AS r ON r.term_taxonomy_id =
tt.term_taxonomy_id
INNER JOIN $wpdb->posts AS p ON p.ID = r.object_id
$where
GROUP BY t.term_id";
$results = $wpdb->get_results( $query );
wp_cache_set( $key, $results );
}
return $results;
But I can't get it to output the terms in their hierarchy (which i need
for the select list). I've tried grouping by tt.parent_id but then it only
returns one of the terms (and it's children) and i know i have selected
more.
Help?
multiple CPT)
I have multiple custom post types and they share some custom taxonomies. I
want to a (hierarchy format) drop down of only the terms used by a
specific custom post type - the drop down will be the filter for the
archive-post-type.php page.
CPTs: Winery, Wines, plus others (but not relevant)
Taxonomies: Regions, Wine Types, plus others (but not relevant)
Wineries will not exist in all regions that wines do - but when listing
the terms it shows all of them. I need to hide any terms that are not
being used by the Winery custom post type.
The output would be a url in the format
http://website.com/winery-profiles/?regions=victoria (which works) just
need to get the list of terms ONLY used by the winery CPT
Any help would be appreciated!
Here is where i'm at:
function get_terms_by_cpt($taxonomy, $post_types=array() ){ global $wpdb;
$post_types=(array) $post_types;
$key = 'wpse_terms'.md5($taxonomy.serialize($post_types));
$results = wp_cache_get($key);
if ( false === $results ) {
$where =" WHERE 1=1";
if( !empty($post_types) ){
$post_types_str = implode(',',$post_types);
$where.= $wpdb->prepare(" AND p.post_type IN(%s)", $post_types_str);
}
$where .= $wpdb->prepare(" AND tt.taxonomy = %s",$taxonomy);
$query = "
SELECT t.*
FROM $wpdb->terms AS t
INNER JOIN $wpdb->term_taxonomy AS tt ON t.term_id = tt.term_id
INNER JOIN $wpdb->term_relationships AS r ON r.term_taxonomy_id =
tt.term_taxonomy_id
INNER JOIN $wpdb->posts AS p ON p.ID = r.object_id
$where
GROUP BY t.term_id";
$results = $wpdb->get_results( $query );
wp_cache_set( $key, $results );
}
return $results;
But I can't get it to output the terms in their hierarchy (which i need
for the select list). I've tried grouping by tt.parent_id but then it only
returns one of the terms (and it's children) and i know i have selected
more.
Help?
Is there something like a scope of \NewDocumentCommand=?iso-8859-1?Q?=3F_=96_tex.stackexchange.com?=
Is there something like a scope of \NewDocumentCommand? –
tex.stackexchange.com
Following along the line of my (confused) post on xparse and expl3, but
this time hopefully with no typos or missing characters, I've devised a
small package just to check a l3keys-based definition …
tex.stackexchange.com
Following along the line of my (confused) post on xparse and expl3, but
this time hopefully with no typos or missing characters, I've devised a
small package just to check a l3keys-based definition …
Sunday, 25 August 2013
Cocos2d-x - Chosing Server for Action MMO Game?
Cocos2d-x - Chosing Server for Action MMO Game?
We are exploring possibilities of realtime multiplayer action game using
cocos2d-x for iPhone and Andriod. We are thinking about SmartFox or Photon
Server. We are looking for some guides or template like stuff as we are
new to cocos2d-x. Also if someone has already implemented cocos2d-x +
SmartFox for realtime action mmo game ? How much difference it will make
in terms of bandwidth, speed and latency when using Photon vs SmartFox,
first one uses binary format and second uses String XML format when doing
network communication ?
We are exploring possibilities of realtime multiplayer action game using
cocos2d-x for iPhone and Andriod. We are thinking about SmartFox or Photon
Server. We are looking for some guides or template like stuff as we are
new to cocos2d-x. Also if someone has already implemented cocos2d-x +
SmartFox for realtime action mmo game ? How much difference it will make
in terms of bandwidth, speed and latency when using Photon vs SmartFox,
first one uses binary format and second uses String XML format when doing
network communication ?
event bubbling after an overlay is created then removed?
event bubbling after an overlay is created then removed?
I have a game that plays fine until I hit I add a retry screen. When the
player clicks on retry it is removed with .empty() on the containing
element. After the retry the mouse down happens more than once. The
greater the number of retries the player has the more times the mousedown
event fires.
http://jsfiddle.net/otherDewi/gNjSH/3/
Below is the mousedown event which is bound to the wrapper
$wrapper.mousedown(function(e) {
e.stopPropagation();
x=e.pageX-14;
y=e.pageY-14;
var $target = $(e.target);
console.log($target);
shells--;
var gotone = false;
if(shells>=0){
for(i=2;i>=0;i--){
if(x>duckPosX[i]+15 && y>duckPosY[i]+10){
if(x<(duckPosX[i]+90)&& y<(duckPosY[i]+60)){
ducks[i].hit=true;
gotone=true;
}
}
};
if(gotone){
console.log("hit");
}else{
console.log("miss");
}
}
if(shells===0){
$winner.fadeTo('400',1).show('fast');
if(hit>=5){
alert('you won game over');
}else{
$winner.empty().html('<div><h1>click to try
again</h1></div>').fadeTo('400',1).show('fast');
}
}
});
If the player does not hit 5 ducks, html is dynamically added to the <div
id="winner"></div>. Clicking retry the div is emptied and the init.start
function is called.
$winner.on("click", function(e) {
e.stopImmediatePropagation();
e.stopPropagation();
$('#winner').empty();
//------------------reset-------------------------//
tryAgain=true;
shells=7;
init.start();
});
I assume its event bubbling that is causing the problem. Been trying for
days to solve this. Would love to be able to edit the question and pin
point the problem. I tried targeting the element but the only object that
appears is the crosshair that is tracking the cursor.
My html is
<div class="wrapper">
<div id="splashScreen"><h1>Click to Play</h1></div>
<div id="duck1" class="ducks"></div>
<div id="duck2" class="ducks"></div>
<div id="duck3" class="ducks"></div>
<img src="http://s21.postimg.org/hfmq4wts3/sight.png" alt=""
id="crosshair">
<h5 id="score"></h5>
<div id="winner">
</div>
</div>
I have a game that plays fine until I hit I add a retry screen. When the
player clicks on retry it is removed with .empty() on the containing
element. After the retry the mouse down happens more than once. The
greater the number of retries the player has the more times the mousedown
event fires.
http://jsfiddle.net/otherDewi/gNjSH/3/
Below is the mousedown event which is bound to the wrapper
$wrapper.mousedown(function(e) {
e.stopPropagation();
x=e.pageX-14;
y=e.pageY-14;
var $target = $(e.target);
console.log($target);
shells--;
var gotone = false;
if(shells>=0){
for(i=2;i>=0;i--){
if(x>duckPosX[i]+15 && y>duckPosY[i]+10){
if(x<(duckPosX[i]+90)&& y<(duckPosY[i]+60)){
ducks[i].hit=true;
gotone=true;
}
}
};
if(gotone){
console.log("hit");
}else{
console.log("miss");
}
}
if(shells===0){
$winner.fadeTo('400',1).show('fast');
if(hit>=5){
alert('you won game over');
}else{
$winner.empty().html('<div><h1>click to try
again</h1></div>').fadeTo('400',1).show('fast');
}
}
});
If the player does not hit 5 ducks, html is dynamically added to the <div
id="winner"></div>. Clicking retry the div is emptied and the init.start
function is called.
$winner.on("click", function(e) {
e.stopImmediatePropagation();
e.stopPropagation();
$('#winner').empty();
//------------------reset-------------------------//
tryAgain=true;
shells=7;
init.start();
});
I assume its event bubbling that is causing the problem. Been trying for
days to solve this. Would love to be able to edit the question and pin
point the problem. I tried targeting the element but the only object that
appears is the crosshair that is tracking the cursor.
My html is
<div class="wrapper">
<div id="splashScreen"><h1>Click to Play</h1></div>
<div id="duck1" class="ducks"></div>
<div id="duck2" class="ducks"></div>
<div id="duck3" class="ducks"></div>
<img src="http://s21.postimg.org/hfmq4wts3/sight.png" alt=""
id="crosshair">
<h5 id="score"></h5>
<div id="winner">
</div>
</div>
Problem with Ubuntu Software Center--can't install anything
Problem with Ubuntu Software Center--can't install anything
About 3 weeks ago I downloaded Ubuntu 12.04 and I've been running it since
then. Initially everything worked great, but about 10 days ago the Ubuntu
Software Center quit working (I previously used it with no problems).Now,
I can open it up and find programs, but when I click the Install button
for one of them, nothing happens. This issue seems to be specific to the
Software Center--I can still use apt-get from the command line with no
problems.
I've tried removing and reinstalling the Software Center, and I've tried
running it from the terminal using sudo software-center (in case there was
some issue with permissions). When I use the terminal, upon starting up
software-center a long error message is printed to the terminal (yes, an
apparently identical traceback is printed twice):
2013-08-25 12:38:50,829 - softwarecenter.ui.gtk3.app - INFO - setting up
proxy 'None'
2013-08-25 12:38:50,833 - softwarecenter.db.database - INFO - open()
database: path=None use_axi=True use_agent=True
2013-08-25 12:38:51,079 - softwarecenter.backend.reviews - WARNING - Could
not get usefulness from server, no username in config file
2013-08-25 12:38:51,178 - softwarecenter.ui.gtk3.app - INFO -
show_available_packages: search_text is '', app is None.
2013-08-25 12:38:51,181 - softwarecenter.db.pkginfo_impl.aptcache - INFO -
aptcache.open()
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/dbus/connection.py", line 607, in
msg_reply_handler
*message.get_args_list()))
File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 69, in error_cb
callback('')
File
"/usr/share/software-center/softwarecenter/backend/installbackend_impl/aptd.py",
line 153, in _register_active_transactions_watch
apt_daemon = client.get_aptdaemon(bus=bus)
File "/usr/lib/python2.7/dist-packages/aptdaemon/client.py", line 1696,
in get_aptdaemon
False),
File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 241, in
get_object
follow_name_owner_changes=follow_name_owner_changes)
File "/usr/lib/python2.7/dist-packages/dbus/proxies.py", line 248, in
__init__
self._named_service = conn.activate_name_owner(bus_name)
File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 180, in
activate_name_owner
self.start_service_by_name(bus_name)
File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 278, in
start_service_by_name
'su', (bus_name, flags)))
File "/usr/lib/python2.7/dist-packages/dbus/connection.py", line 651, in
call_blocking
message, timeout)
dbus.exceptions.DBusException:
org.freedesktop.DBus.Error.Spawn.ChildExited: Launch helper exited with
unknown return code 1
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/dbus/connection.py", line 607, in
msg_reply_handler
*message.get_args_list()))
File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 69, in error_cb
callback('')
File
"/usr/share/software-center/softwarecenter/backend/installbackend_impl/aptd.py",
line 153, in _register_active_transactions_watch
apt_daemon = client.get_aptdaemon(bus=bus)
File "/usr/lib/python2.7/dist-packages/aptdaemon/client.py", line 1696,
in get_aptdaemon
False),
File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 241, in
get_object
follow_name_owner_changes=follow_name_owner_changes)
File "/usr/lib/python2.7/dist-packages/dbus/proxies.py", line 248, in
__init__
self._named_service = conn.activate_name_owner(bus_name)
File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 180, in
activate_name_owner
self.start_service_by_name(bus_name)
File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 278, in
start_service_by_name
'su', (bus_name, flags)))
File "/usr/lib/python2.7/dist-packages/dbus/connection.py", line 651, in
call_blocking
message, timeout)
dbus.exceptions.DBusException:
org.freedesktop.DBus.Error.Spawn.ChildExited: Launch helper exited with
unknown return code 1
2013-08-25 12:38:53,215 - softwarecenter.ui.gtk3.widgets.exhibits -
WARNING - download failed: '<class 'gi._glib.GError'>', 'Operation not
supported'
Any suggestions?
About 3 weeks ago I downloaded Ubuntu 12.04 and I've been running it since
then. Initially everything worked great, but about 10 days ago the Ubuntu
Software Center quit working (I previously used it with no problems).Now,
I can open it up and find programs, but when I click the Install button
for one of them, nothing happens. This issue seems to be specific to the
Software Center--I can still use apt-get from the command line with no
problems.
I've tried removing and reinstalling the Software Center, and I've tried
running it from the terminal using sudo software-center (in case there was
some issue with permissions). When I use the terminal, upon starting up
software-center a long error message is printed to the terminal (yes, an
apparently identical traceback is printed twice):
2013-08-25 12:38:50,829 - softwarecenter.ui.gtk3.app - INFO - setting up
proxy 'None'
2013-08-25 12:38:50,833 - softwarecenter.db.database - INFO - open()
database: path=None use_axi=True use_agent=True
2013-08-25 12:38:51,079 - softwarecenter.backend.reviews - WARNING - Could
not get usefulness from server, no username in config file
2013-08-25 12:38:51,178 - softwarecenter.ui.gtk3.app - INFO -
show_available_packages: search_text is '', app is None.
2013-08-25 12:38:51,181 - softwarecenter.db.pkginfo_impl.aptcache - INFO -
aptcache.open()
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/dbus/connection.py", line 607, in
msg_reply_handler
*message.get_args_list()))
File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 69, in error_cb
callback('')
File
"/usr/share/software-center/softwarecenter/backend/installbackend_impl/aptd.py",
line 153, in _register_active_transactions_watch
apt_daemon = client.get_aptdaemon(bus=bus)
File "/usr/lib/python2.7/dist-packages/aptdaemon/client.py", line 1696,
in get_aptdaemon
False),
File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 241, in
get_object
follow_name_owner_changes=follow_name_owner_changes)
File "/usr/lib/python2.7/dist-packages/dbus/proxies.py", line 248, in
__init__
self._named_service = conn.activate_name_owner(bus_name)
File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 180, in
activate_name_owner
self.start_service_by_name(bus_name)
File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 278, in
start_service_by_name
'su', (bus_name, flags)))
File "/usr/lib/python2.7/dist-packages/dbus/connection.py", line 651, in
call_blocking
message, timeout)
dbus.exceptions.DBusException:
org.freedesktop.DBus.Error.Spawn.ChildExited: Launch helper exited with
unknown return code 1
Traceback (most recent call last):
File "/usr/lib/python2.7/dist-packages/dbus/connection.py", line 607, in
msg_reply_handler
*message.get_args_list()))
File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 69, in error_cb
callback('')
File
"/usr/share/software-center/softwarecenter/backend/installbackend_impl/aptd.py",
line 153, in _register_active_transactions_watch
apt_daemon = client.get_aptdaemon(bus=bus)
File "/usr/lib/python2.7/dist-packages/aptdaemon/client.py", line 1696,
in get_aptdaemon
False),
File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 241, in
get_object
follow_name_owner_changes=follow_name_owner_changes)
File "/usr/lib/python2.7/dist-packages/dbus/proxies.py", line 248, in
__init__
self._named_service = conn.activate_name_owner(bus_name)
File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 180, in
activate_name_owner
self.start_service_by_name(bus_name)
File "/usr/lib/python2.7/dist-packages/dbus/bus.py", line 278, in
start_service_by_name
'su', (bus_name, flags)))
File "/usr/lib/python2.7/dist-packages/dbus/connection.py", line 651, in
call_blocking
message, timeout)
dbus.exceptions.DBusException:
org.freedesktop.DBus.Error.Spawn.ChildExited: Launch helper exited with
unknown return code 1
2013-08-25 12:38:53,215 - softwarecenter.ui.gtk3.widgets.exhibits -
WARNING - download failed: '<class 'gi._glib.GError'>', 'Operation not
supported'
Any suggestions?
Modulo Problem, Fermat's little theorem
Modulo Problem, Fermat's little theorem
Find the value of the unique integer x satisfying $O \le x \le 17$ for
which $$ 4^{1024000000002} \cong x(mod.17) $$ I think this is related to
fermat's little theorm, i'm knowledgeable with the Chinese remainder
theorm and just need some advice on solving this.
Find the value of the unique integer x satisfying $O \le x \le 17$ for
which $$ 4^{1024000000002} \cong x(mod.17) $$ I think this is related to
fermat's little theorm, i'm knowledgeable with the Chinese remainder
theorm and just need some advice on solving this.
Are random effects justified if there is no variability between groups?
Are random effects justified if there is no variability between groups?
I'm looking for more of a substantive ( but also a statistical ) answer.
If in the empty model (just intercept) there is no variability at level-2,
should HLM still be applied just because the data is theoretically nested
(employees in teams) ? Will a linear model suffice in this case?
If you have an answer for me I would appreciate a bibliographical
reference as well.
I'm looking for more of a substantive ( but also a statistical ) answer.
If in the empty model (just intercept) there is no variability at level-2,
should HLM still be applied just because the data is theoretically nested
(employees in teams) ? Will a linear model suffice in this case?
If you have an answer for me I would appreciate a bibliographical
reference as well.
Saturday, 24 August 2013
wordpress for development big web application
wordpress for development big web application
Wordpress and Wordpress MU is more popular blogging CMS in the world.
Plugin/Theme (Biggest community) system make it more powerful, i know
that. But what can i do or can't do more with WP in web application
development? If i use custom database and custom db query, i think it
possible to make any kind of web application. Am i right ? Is there any
disadvantage to use WP as develop web application? In my view i think WP =
PHP/Mysql framework + HTML/CSS/JS framework for develop a web application.
What is the most impossible think that developer can't develop big web
application with WP ?
Wordpress and Wordpress MU is more popular blogging CMS in the world.
Plugin/Theme (Biggest community) system make it more powerful, i know
that. But what can i do or can't do more with WP in web application
development? If i use custom database and custom db query, i think it
possible to make any kind of web application. Am i right ? Is there any
disadvantage to use WP as develop web application? In my view i think WP =
PHP/Mysql framework + HTML/CSS/JS framework for develop a web application.
What is the most impossible think that developer can't develop big web
application with WP ?
Mac Server setup for small office
Mac Server setup for small office
We have a mac mini with osX server for our small web design company's office.
We want to move toward a local setup and to then push up to the live server.
In the past I have used MAMP PRO and Sequel Pro to create an environment
on my personal computer.
Our setup is basically 1 mac mini with Server osX and then 5 iMacs.
I would like to be able to type in http://clients/client-name
and pull up the sites from all of our computers.
My initial plan is to mount the the individual sites with Transmit 4, have
codekit watch it for preprocessing(SASS), and Sublime Text as our editor.
I know I should ask a specific answerable question... But the real
question is, What is the the best way for us to set up our server to our
sites? We do a lot of custom WordPress builds so Apache and mySQL are key.
Any direction to what I can read about this would be great. Everything I
have found is "osX server, does it all - have fun!"
Another issue is that I want to be able to push to live with beanstalk
maybe, and migrate DB pro.
Any thoughts would be appreciated.
-sheriffderek c/o nouveau
We have a mac mini with osX server for our small web design company's office.
We want to move toward a local setup and to then push up to the live server.
In the past I have used MAMP PRO and Sequel Pro to create an environment
on my personal computer.
Our setup is basically 1 mac mini with Server osX and then 5 iMacs.
I would like to be able to type in http://clients/client-name
and pull up the sites from all of our computers.
My initial plan is to mount the the individual sites with Transmit 4, have
codekit watch it for preprocessing(SASS), and Sublime Text as our editor.
I know I should ask a specific answerable question... But the real
question is, What is the the best way for us to set up our server to our
sites? We do a lot of custom WordPress builds so Apache and mySQL are key.
Any direction to what I can read about this would be great. Everything I
have found is "osX server, does it all - have fun!"
Another issue is that I want to be able to push to live with beanstalk
maybe, and migrate DB pro.
Any thoughts would be appreciated.
-sheriffderek c/o nouveau
Java loading and saving system flawed
Java loading and saving system flawed
I cant seam to resolve the problem. I'm trying to make a loading and
saving system but I came across a weird problem. When I first load it up
and generate the level, it saves fine, but when I save it for a second
time, it saves all 0 (nothing). Please help me.
Here is my level class:
package level;
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
import Window.Game;
public class level {
public level() {
}
public static void loadlevel() {
try {
Game.scanner = new Scanner(new File("res//leveldata.txt"));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "WARNING:Error loading
level: "
+ e.getMessage() + " Hit ok to create the file",
"ERROR!",
JOptionPane.ERROR_MESSAGE);
level.generatelevel();
}
try {
Game.levelwidth = Game.scanner.nextInt();
Game.levelheight = Game.scanner.nextInt();
while (Game.scanner.hasNext()) {
int data = Game.scanner.nextInt();
System.out.println(data);
for (int i = 0; i < Game.levelpixelstotal; i++) {
Game.leveldata[i] = data;
}
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "WARNING:Error loading
level: "
+ e.getMessage() + " Hit ok to create the level",
"ERROR",
JOptionPane.ERROR_MESSAGE);
level.generatelevel();
}
}
public static void savelevel() {
try {
Game.formatter = new Formatter("res//leveldata.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Game.formatter.format("%d %d\n", Game.levelwidth, Game.levelheight);
for (int i = 0; i < Game.levelpixelstotal; i++) {
System.out.println(Game.leveldata[i]);
Game.formatter.format(" %d\n", Game.leveldata[i]);
}
Game.formatter.close();
}
public static void generatelevel() {
Game.levelheight = 160;
Game.levelwidth = 240;
for (int i = 0; i < Game.levelpixelstotal; i++) {
if (i < (Game.levelwidth * (Game.levelheight / 2))) {
Game.leveldata[i] = Game.Dirtid;
}
if ((i > ((Game.levelwidth * (Game.levelheight) / 2)))
&& (i < (Game.levelwidth * (Game.levelheight) / 2)
+ Game.levelwidth)) {
Game.leveldata[i] = Game.Grassid;
}
}
try {
Game.stop();
} catch (IOException e) {
e.printStackTrace();
}
}
}
I cant seam to resolve the problem. I'm trying to make a loading and
saving system but I came across a weird problem. When I first load it up
and generate the level, it saves fine, but when I save it for a second
time, it saves all 0 (nothing). Please help me.
Here is my level class:
package level;
import java.io.*;
import java.util.*;
import javax.swing.JOptionPane;
import Window.Game;
public class level {
public level() {
}
public static void loadlevel() {
try {
Game.scanner = new Scanner(new File("res//leveldata.txt"));
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "WARNING:Error loading
level: "
+ e.getMessage() + " Hit ok to create the file",
"ERROR!",
JOptionPane.ERROR_MESSAGE);
level.generatelevel();
}
try {
Game.levelwidth = Game.scanner.nextInt();
Game.levelheight = Game.scanner.nextInt();
while (Game.scanner.hasNext()) {
int data = Game.scanner.nextInt();
System.out.println(data);
for (int i = 0; i < Game.levelpixelstotal; i++) {
Game.leveldata[i] = data;
}
}
} catch (Exception e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "WARNING:Error loading
level: "
+ e.getMessage() + " Hit ok to create the level",
"ERROR",
JOptionPane.ERROR_MESSAGE);
level.generatelevel();
}
}
public static void savelevel() {
try {
Game.formatter = new Formatter("res//leveldata.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Game.formatter.format("%d %d\n", Game.levelwidth, Game.levelheight);
for (int i = 0; i < Game.levelpixelstotal; i++) {
System.out.println(Game.leveldata[i]);
Game.formatter.format(" %d\n", Game.leveldata[i]);
}
Game.formatter.close();
}
public static void generatelevel() {
Game.levelheight = 160;
Game.levelwidth = 240;
for (int i = 0; i < Game.levelpixelstotal; i++) {
if (i < (Game.levelwidth * (Game.levelheight / 2))) {
Game.leveldata[i] = Game.Dirtid;
}
if ((i > ((Game.levelwidth * (Game.levelheight) / 2)))
&& (i < (Game.levelwidth * (Game.levelheight) / 2)
+ Game.levelwidth)) {
Game.leveldata[i] = Game.Grassid;
}
}
try {
Game.stop();
} catch (IOException e) {
e.printStackTrace();
}
}
}
What does one call a NON-wireless router?
What does one call a NON-wireless router?
I want to buy a simple ethernet router. Every online store I try I get
those that include Wi-Fi. Still I can explicitly state that I want Wi-Fi,
I can't state that I only want a non-Wi-Fi router. Is there a specific
name for those type of routers?
I want to buy a simple ethernet router. Every online store I try I get
those that include Wi-Fi. Still I can explicitly state that I want Wi-Fi,
I can't state that I only want a non-Wi-Fi router. Is there a specific
name for those type of routers?
Does java recursion algorithms consume more heap causing additional garbage collection?
Does java recursion algorithms consume more heap causing additional
garbage collection?
If I have two alternative algorithms where the first is based on recursion
and the other is a loop based one, which will cause more garbage
collection ?
garbage collection?
If I have two alternative algorithms where the first is based on recursion
and the other is a loop based one, which will cause more garbage
collection ?
Ransack search not working if there is 'space' in search term
Ransack search not working if there is 'space' in search term
I am using ransack for search in my rails 3.2 application using postgres
as database.
I have a Invoice model and every invoice belongs_to a buyer. Below is my
search form in index page.
views/invoices/index.html.erb
<%= search_form_for @search do |f| %>
<%= f.text_field :buyer_name_cont %>
<%= f.submit "Search"%>
<% end %>
And here is my controller code.
controllers/invoices_controller.rb
def index
@search = Invoice.search(params[:q])
@invoices=@search.result(:distinct => true).paginate(:page =>
params[:page], :per_page => GlobalConstants::PER_PAGE )
respond_to do |format|
format.html # index.html.erb
format.json { render json: @invoices }
end
end
Let's say a invoice is there of a buyer having name "Bat Man".
If I search "Bat", I get the invoice in results. Again if I search "Man",
I get the invoice in results. But if I search "Bat Man", I don't get the
invoice in results.
I know it might be something trivial but I am not able to resolve.
Please help.
Thanks.
I am using ransack for search in my rails 3.2 application using postgres
as database.
I have a Invoice model and every invoice belongs_to a buyer. Below is my
search form in index page.
views/invoices/index.html.erb
<%= search_form_for @search do |f| %>
<%= f.text_field :buyer_name_cont %>
<%= f.submit "Search"%>
<% end %>
And here is my controller code.
controllers/invoices_controller.rb
def index
@search = Invoice.search(params[:q])
@invoices=@search.result(:distinct => true).paginate(:page =>
params[:page], :per_page => GlobalConstants::PER_PAGE )
respond_to do |format|
format.html # index.html.erb
format.json { render json: @invoices }
end
end
Let's say a invoice is there of a buyer having name "Bat Man".
If I search "Bat", I get the invoice in results. Again if I search "Man",
I get the invoice in results. But if I search "Bat Man", I don't get the
invoice in results.
I know it might be something trivial but I am not able to resolve.
Please help.
Thanks.
copy my exchange server settings password
copy my exchange server settings password
The password field under "exchange server settings" is blocked out. I want
to add my business email to another phone. Is there any way to reveal the
password?
Thanks.
The password field under "exchange server settings" is blocked out. I want
to add my business email to another phone. Is there any way to reveal the
password?
Thanks.
Friday, 23 August 2013
How to access to file in a separated assembly?
How to access to file in a separated assembly?
I have a project that i put my reports files into it,now i want to
refrence them in another ptoject,i tried this code:
StiReport.Load(new
Uri("pack://application:,/GoldAccountingSystem.Reports;component/StimulReports/TBank.mrt")
.LocalPath);
but i get this error:
Could not find a part of the path
'E:\GoldAccountingSystem.Reports;component\StimulReports\TBank.mrt'.
GoldAccountingSystem.Reports is the assembly name of report,but idon't
know why it's lookinh in E for this assembly although the right address is
E:\Projects\GoldAccountingSystem\GoldAccountingSystem.Reports.
any idea?
I have a project that i put my reports files into it,now i want to
refrence them in another ptoject,i tried this code:
StiReport.Load(new
Uri("pack://application:,/GoldAccountingSystem.Reports;component/StimulReports/TBank.mrt")
.LocalPath);
but i get this error:
Could not find a part of the path
'E:\GoldAccountingSystem.Reports;component\StimulReports\TBank.mrt'.
GoldAccountingSystem.Reports is the assembly name of report,but idon't
know why it's lookinh in E for this assembly although the right address is
E:\Projects\GoldAccountingSystem\GoldAccountingSystem.Reports.
any idea?
Get result of joining multiple tables as one row
Get result of joining multiple tables as one row
I have these 2 tables:
table1:
id | name
---------
1 | john
2 | jack
table2:
id | profile_id | institution
-----------------------------
1 | 1 | SFU
2 | 1 | UBC
3 | 2 | BU
4 | 2 | USC
5 | 2 | SFU
If I want to get all the information about a user using his userid, I can
simply join them using this:
select a.id, a.name, b.institution from table1 a, table2 b where a.id =
USER_ID and a.id = b.profile_id
which for USER_ID = 1 returns:
id | name | institution
-----------------------
1 | john | SFU
1 | john | UBC
What I need is actually 1 unique row instead of multiple rows. Is it in
any way possible to get something like this? (I haven't seen something to
do it but am not sure)
id | name | institution
-----------------------
1 | john | [SFU, UBC]
I have these 2 tables:
table1:
id | name
---------
1 | john
2 | jack
table2:
id | profile_id | institution
-----------------------------
1 | 1 | SFU
2 | 1 | UBC
3 | 2 | BU
4 | 2 | USC
5 | 2 | SFU
If I want to get all the information about a user using his userid, I can
simply join them using this:
select a.id, a.name, b.institution from table1 a, table2 b where a.id =
USER_ID and a.id = b.profile_id
which for USER_ID = 1 returns:
id | name | institution
-----------------------
1 | john | SFU
1 | john | UBC
What I need is actually 1 unique row instead of multiple rows. Is it in
any way possible to get something like this? (I haven't seen something to
do it but am not sure)
id | name | institution
-----------------------
1 | john | [SFU, UBC]
Can someone explain this angular code?
Can someone explain this angular code?
app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.updated = 0;
$scope.stop = function() {
textWatch();
};
var textWatch = $scope.$watch('text', function(newVal, oldVal) {
if (newVal === oldVal) { return; }
$scope.updated++;
});
});
<body ng-controller="MainCtrl">
<input type="text" ng-model="text" /> {{updated}} times updated.
<button ng-click="stop()">Stop count</button>
</body>
and http://jsbin.com/emenuf/3/edit
and i have a question,why after i click the button and type {{updated}}
doesnt update?
app = angular.module('app', []);
app.controller('MainCtrl', function($scope) {
$scope.updated = 0;
$scope.stop = function() {
textWatch();
};
var textWatch = $scope.$watch('text', function(newVal, oldVal) {
if (newVal === oldVal) { return; }
$scope.updated++;
});
});
<body ng-controller="MainCtrl">
<input type="text" ng-model="text" /> {{updated}} times updated.
<button ng-click="stop()">Stop count</button>
</body>
and http://jsbin.com/emenuf/3/edit
and i have a question,why after i click the button and type {{updated}}
doesnt update?
Problems with vim, i removed it
Problems with vim, i removed it
I'm a new user in linux. The problem is that when i tried to run the VI
(or vim) text editor, i realised that it worked really different as i
remembered it used to. Example, when i try to put in mode of "insert", in
the downside doesn't appear "INSERT", or when i try to delete with the
backspace key, it doesn't delete... it moves the cursor back, and does
nothing.
So i thought that removing it and re-installing it again would work, and
removed it by:
apt-get --purge remove vim-common
But now when i try:
apt-cache search vim
it throws nothing, and now i don't know how to install it again. Any help?
thanks people
I'm a new user in linux. The problem is that when i tried to run the VI
(or vim) text editor, i realised that it worked really different as i
remembered it used to. Example, when i try to put in mode of "insert", in
the downside doesn't appear "INSERT", or when i try to delete with the
backspace key, it doesn't delete... it moves the cursor back, and does
nothing.
So i thought that removing it and re-installing it again would work, and
removed it by:
apt-get --purge remove vim-common
But now when i try:
apt-cache search vim
it throws nothing, and now i don't know how to install it again. Any help?
thanks people
How to update PHP form when user click submit button?
How to update PHP form when user click submit button?
I have a form that updates data. When I click on update button, it updates
the data in the database but shows the old data in the form, and I have to
refresh the page again to view the updated data. If I change the action of
the page, it stops updating the data.
I want the update page to update data when the user clicks on 'Submit'
Button.
Kindly tell me the way to overcome this problem.
Thanks
I have a form that updates data. When I click on update button, it updates
the data in the database but shows the old data in the form, and I have to
refresh the page again to view the updated data. If I change the action of
the page, it stops updating the data.
I want the update page to update data when the user clicks on 'Submit'
Button.
Kindly tell me the way to overcome this problem.
Thanks
Changing textfield between enabled and disabled
Changing textfield between enabled and disabled
I have 2 radio buttons and 1 TextField and now I want to do changing
between enabled and disabled TextField. If radioFindText is selected then
TextField must be enabled otherwise it must be disabled. I was trying with
such code but it doesn't work and I am running out of possible solutions.
final TextField<String> searchedText = new
TextField<String>("searchfield", Model.of(""));
searchedText.setEnabled(false);
searchedText.setOutputMarkupId(true);
IModel<String> selected = new Model<String>("ERRORS");
RadioGroup group = new RadioGroup("group", selected) {
@Override
protected void onSelectionChanged(Object newSelection) {
super.onSelectionChanged(newSelection);
if (newSelection.toString().equals("Find text")) {
searchedText.setEnabled(true);
}
}
};
group.setOutputMarkupId(true);
group.add(new AjaxSelfUpdatingTimerBehavior(Duration.seconds(1)));
Radio radioErrors = new Radio("errors", new Model<String>("ERRORS"));
Radio radioFindText = new Radio("text", new Model<String>("Find text"));
group.add(radioErrors);
group.add(radioFindText);
group.add(searchedText);
form.add(group);
I have 2 radio buttons and 1 TextField and now I want to do changing
between enabled and disabled TextField. If radioFindText is selected then
TextField must be enabled otherwise it must be disabled. I was trying with
such code but it doesn't work and I am running out of possible solutions.
final TextField<String> searchedText = new
TextField<String>("searchfield", Model.of(""));
searchedText.setEnabled(false);
searchedText.setOutputMarkupId(true);
IModel<String> selected = new Model<String>("ERRORS");
RadioGroup group = new RadioGroup("group", selected) {
@Override
protected void onSelectionChanged(Object newSelection) {
super.onSelectionChanged(newSelection);
if (newSelection.toString().equals("Find text")) {
searchedText.setEnabled(true);
}
}
};
group.setOutputMarkupId(true);
group.add(new AjaxSelfUpdatingTimerBehavior(Duration.seconds(1)));
Radio radioErrors = new Radio("errors", new Model<String>("ERRORS"));
Radio radioFindText = new Radio("text", new Model<String>("Find text"));
group.add(radioErrors);
group.add(radioFindText);
group.add(searchedText);
form.add(group);
Thursday, 22 August 2013
andriod app, Image does not display on Face book wall
andriod app, Image does not display on Face book wall
I want to post photo on user's wall.I have given a error message in
onCompleted() function.when i run my app logCat shows photo upload
complete ..but no uploaded photo is shown on my wall..where is the mistake
..Please guide me..Here is my Code
protected Void doInBackground(Void... params) { // start Facebook Login
Session.openActiveSession(ImageActivity.this, true, new
Session.StatusCallback() {
// callback when session changes state
@Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Request request=Request.newUploadPhotoRequest(session,bitmap, new
Request.Callback() {
@Override
public void onCompleted(Response response) {
if (response.getError() != null) { // [IF Failed Posting]
Log.d("error", "photo upload problem. Error="+response.getError() );
}
else {
Log.d("error", "photo upload complete.");
}
}
});
request.executeAsync();
}
}
});
return null;
}
I want to post photo on user's wall.I have given a error message in
onCompleted() function.when i run my app logCat shows photo upload
complete ..but no uploaded photo is shown on my wall..where is the mistake
..Please guide me..Here is my Code
protected Void doInBackground(Void... params) { // start Facebook Login
Session.openActiveSession(ImageActivity.this, true, new
Session.StatusCallback() {
// callback when session changes state
@Override
public void call(Session session, SessionState state, Exception exception) {
if (session.isOpened()) {
Request request=Request.newUploadPhotoRequest(session,bitmap, new
Request.Callback() {
@Override
public void onCompleted(Response response) {
if (response.getError() != null) { // [IF Failed Posting]
Log.d("error", "photo upload problem. Error="+response.getError() );
}
else {
Log.d("error", "photo upload complete.");
}
}
});
request.executeAsync();
}
}
});
return null;
}
Converting values with Arabic numbers
Converting values with Arabic numbers
The problem states "Write a program that accepts a 10-digit telephone
number that may contain one or more alphabetic characters. Display the
corresponding number using numerals...etc" ABC:2 through WXYZ:9
This chapter teaches about loops but I found myself really lost at this
problem. I completed the code but I think it sucks...
My question: Is there a better way to shorten this code up? And I only
figured to use the c# keyword case, is there another way?
EDIT: Arabic as in you could type in 1800WALLTO and it will give you
1800925586
ALSO I am not asking for a code that doesn't work, this does EXACTLY what
I want and asked it to do. I am just asking for any advise or input on how
to make it better. I really wanted to know a way to do it without switch
and case break etc...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int x = 0;
char userInput = ' ';
string inputString = "",
outputString = "";
Console.WriteLine("Enter the digits from the phone number");
do
{
userInput = Console.ReadKey(false).KeyChar;
inputString += userInput;
if (Char.IsLetter(userInput))
userInput = userInput.ToString().ToUpper().ToCharArray()[0];
switch (userInput)
{
case '1':
outputString += '1';
x++;
break;
case '2':
case 'A':
case 'B':
case 'C':
outputString += '2';
x++;
break;
case '3':
case 'D':
case 'E':
case 'F':
outputString += '3';
x++;
break;
case '4':
case 'G':
case 'H':
case 'I':
outputString += '4';
x++;
break;
case '5':
case 'J':
case 'K':
case 'L':
outputString += '5';
x++;
break;
case '6':
case 'M':
case 'N':
case 'O':
outputString += '6';
x++;
break;
case '7':
case 'P':
case 'Q':
case 'R':
case 'S':
outputString += '7';
x++;
break;
case '8':
case 'T':
case 'U':
case 'V':
outputString += '8';
x++;
break;
case '9':
case 'W':
case 'X':
case 'Y':
case 'Z':
outputString += '9';
x++;
break;
case '0':
outputString += '0';
x++;
break;
default:
Console.WriteLine("You entered an incorrect value-Try
again");
x--;
break;
}
}
while (x < 10);
Console.WriteLine("\nYou entered {0}", inputString);
Console.WriteLine("Your number is {0}", outputString);
}
}
}
The problem states "Write a program that accepts a 10-digit telephone
number that may contain one or more alphabetic characters. Display the
corresponding number using numerals...etc" ABC:2 through WXYZ:9
This chapter teaches about loops but I found myself really lost at this
problem. I completed the code but I think it sucks...
My question: Is there a better way to shorten this code up? And I only
figured to use the c# keyword case, is there another way?
EDIT: Arabic as in you could type in 1800WALLTO and it will give you
1800925586
ALSO I am not asking for a code that doesn't work, this does EXACTLY what
I want and asked it to do. I am just asking for any advise or input on how
to make it better. I really wanted to know a way to do it without switch
and case break etc...
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
int x = 0;
char userInput = ' ';
string inputString = "",
outputString = "";
Console.WriteLine("Enter the digits from the phone number");
do
{
userInput = Console.ReadKey(false).KeyChar;
inputString += userInput;
if (Char.IsLetter(userInput))
userInput = userInput.ToString().ToUpper().ToCharArray()[0];
switch (userInput)
{
case '1':
outputString += '1';
x++;
break;
case '2':
case 'A':
case 'B':
case 'C':
outputString += '2';
x++;
break;
case '3':
case 'D':
case 'E':
case 'F':
outputString += '3';
x++;
break;
case '4':
case 'G':
case 'H':
case 'I':
outputString += '4';
x++;
break;
case '5':
case 'J':
case 'K':
case 'L':
outputString += '5';
x++;
break;
case '6':
case 'M':
case 'N':
case 'O':
outputString += '6';
x++;
break;
case '7':
case 'P':
case 'Q':
case 'R':
case 'S':
outputString += '7';
x++;
break;
case '8':
case 'T':
case 'U':
case 'V':
outputString += '8';
x++;
break;
case '9':
case 'W':
case 'X':
case 'Y':
case 'Z':
outputString += '9';
x++;
break;
case '0':
outputString += '0';
x++;
break;
default:
Console.WriteLine("You entered an incorrect value-Try
again");
x--;
break;
}
}
while (x < 10);
Console.WriteLine("\nYou entered {0}", inputString);
Console.WriteLine("Your number is {0}", outputString);
}
}
}
Alternatives to view log on android device
Alternatives to view log on android device
what alternatives are there to see the log of logcat on android device ?
I think maybe I could see the log file in an android console as the tail
of linux, or maybe there is any graphical application which redirect the
log.
what alternatives are there to see the log of logcat on android device ?
I think maybe I could see the log file in an android console as the tail
of linux, or maybe there is any graphical application which redirect the
log.
unable to perform delivery on clearcase because of checked out file in snapshot view?
unable to perform delivery on clearcase because of checked out file in
snapshot view?
I have having an issue in clearcase delivery. There are some files that
are checked out from a snapshot view and the view has been removed. I am
trying to deliver from a dynamic view in unix. Since I can see those files
checked out in the activity, is there a way to check in those files and
proceed the delivery operation?
snapshot view?
I have having an issue in clearcase delivery. There are some files that
are checked out from a snapshot view and the view has been removed. I am
trying to deliver from a dynamic view in unix. Since I can see those files
checked out in the activity, is there a way to check in those files and
proceed the delivery operation?
Unique nodes and c#
Unique nodes and c#
Is there a good way in c# to look through an XML node list using DOM and
get a node list of only the unique nodes and also a list of each nodes
unique possible attributes.
The XMl file in question has nodes of the same name but with different
attributes, i want a list of all the possible ones. Also the list of nodes
i would like to be only of the unique nodes, rather than having repeats
(so node lists i generate at the moment might have contact twice, three
time ect within it). And it needs to work for any XML document. Any ideas?
Is there a good way in c# to look through an XML node list using DOM and
get a node list of only the unique nodes and also a list of each nodes
unique possible attributes.
The XMl file in question has nodes of the same name but with different
attributes, i want a list of all the possible ones. Also the list of nodes
i would like to be only of the unique nodes, rather than having repeats
(so node lists i generate at the moment might have contact twice, three
time ect within it). And it needs to work for any XML document. Any ideas?
best way to compare two strings and their upper and lower case signs
best way to compare two strings and their upper and lower case signs
Let's say I have 2 strings.First string is x = "abc" and the second one is
y = "ABC".When I write in c# following code:
if(x == y)
or
if(x.Equals(y))
return value is true.How can I check their upper and lower case?
Let's say I have 2 strings.First string is x = "abc" and the second one is
y = "ABC".When I write in c# following code:
if(x == y)
or
if(x.Equals(y))
return value is true.How can I check their upper and lower case?
JQuery Undefined Error
JQuery Undefined Error
I need to Perform image sliding. I am using the following code.
My Javascript
<script src="Scripts/jquery-ui.min.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.8.3.min.js" type="text/javascript"></script>
<link href="Styles/StyleSheet1.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(".hero").cycle({
fx: 'scrollDown',
timeout: 7000,
pause: 1,
pager: '#slideshow-nav div'
});
</script>
Source:-
<div class="page-slideshow narrow">
<div class="hero">
<img src="Image\img1.jpg" width="460" height="235" alt="" />
<img src="Image\img2.jpg" width="460" height="235" alt="" />
<img src="Image\img3" width="460" height="235" alt="" />
<img src="Image\img4" width="460" height="235" alt="" />
</div>
<div id="slideshow-nav">
<div>
</div>
</div>
</div>
CSS
body
{ }
#slideshow-nav
{
width: 700px;
height: 30px;
position: absolute;
z-index: 999;
bottom: 0;
left: 11px;
text-align: center;
text-decoration:none;
}
#slideshow-nav a
{
background: transparent url('../Image/bullet_grey - 1.png') 0 0 no-repeat;
width: 26px;
height: 26px;
text-indent: -999px;
display: inline-block;
text-decoration: none;
margin: 7px;
text-indent: -9999px !important;
margin: 7px;
text-decoration: none;
background-position:center;
border:none;
outline:none;
}
#slideshow-nav a.activeSlide
{
background-position: 0 -1000px;
background: transparent url('../Image/bullet_red.png') 0 0 no-repeat;
display: inline-block;
background-position :center;
text-decoration:none;
border:none;
outline:none;
}
.page-slideshow
{
position: relative;
margin-bottom: 15px;
text-decoration: none;
}
.page-slideshow.narrow #slideshow-nav
{
width: 460px;
left: 0;
text-decoration: none;
}
I am using :- Visual Studio 2010, .Net Framework 4.0 I have created an
.aspx page in VS2010 and provided above Js,CSS and Design. The CSS given
above is included in the source as StyleSheet1.css But I am getting the
error:- 'jQuery' is undefined Please help me to solve this error.
I need to Perform image sliding. I am using the following code.
My Javascript
<script src="Scripts/jquery-ui.min.js" type="text/javascript"></script>
<script src="Scripts/jquery-1.8.3.min.js" type="text/javascript"></script>
<link href="Styles/StyleSheet1.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(".hero").cycle({
fx: 'scrollDown',
timeout: 7000,
pause: 1,
pager: '#slideshow-nav div'
});
</script>
Source:-
<div class="page-slideshow narrow">
<div class="hero">
<img src="Image\img1.jpg" width="460" height="235" alt="" />
<img src="Image\img2.jpg" width="460" height="235" alt="" />
<img src="Image\img3" width="460" height="235" alt="" />
<img src="Image\img4" width="460" height="235" alt="" />
</div>
<div id="slideshow-nav">
<div>
</div>
</div>
</div>
CSS
body
{ }
#slideshow-nav
{
width: 700px;
height: 30px;
position: absolute;
z-index: 999;
bottom: 0;
left: 11px;
text-align: center;
text-decoration:none;
}
#slideshow-nav a
{
background: transparent url('../Image/bullet_grey - 1.png') 0 0 no-repeat;
width: 26px;
height: 26px;
text-indent: -999px;
display: inline-block;
text-decoration: none;
margin: 7px;
text-indent: -9999px !important;
margin: 7px;
text-decoration: none;
background-position:center;
border:none;
outline:none;
}
#slideshow-nav a.activeSlide
{
background-position: 0 -1000px;
background: transparent url('../Image/bullet_red.png') 0 0 no-repeat;
display: inline-block;
background-position :center;
text-decoration:none;
border:none;
outline:none;
}
.page-slideshow
{
position: relative;
margin-bottom: 15px;
text-decoration: none;
}
.page-slideshow.narrow #slideshow-nav
{
width: 460px;
left: 0;
text-decoration: none;
}
I am using :- Visual Studio 2010, .Net Framework 4.0 I have created an
.aspx page in VS2010 and provided above Js,CSS and Design. The CSS given
above is included in the source as StyleSheet1.css But I am getting the
error:- 'jQuery' is undefined Please help me to solve this error.
Wednesday, 21 August 2013
asp.net textbox focus problems
Python: How to use requests library to access a url through several different proxy servers?
Python: How to use requests library to access a url through several
different proxy servers?
As it says in the title, I am trying to access a url through several
different proxies sequentially (using for loop). Right now this is my
code:
import requests
import json
with open('proxies.txt') as proxies:
for line in proxies:
proxy=json.loads(line)
with open('urls.txt') as urls:
for line in urls:
url=line.rstrip()
data=requests.get(url, proxies={'http':line})
data1=data.text
print data1
and my urls.txt file:
http://api.exip.org/?call=ip
and my proxies.txt file:
{"https": "84.22.41.1:3128"}
{"http":"194.126.181.47:81"}
{"http":"218.108.170.170:82"}
that I got at [www.hidemyass.com][1]
for some reason, the output is
68.6.34.253
68.6.34.253
68.6.34.253
as if it is accessing that website through my own router ip address. In
other words, it is not trying to access through the proxies I give it, it
is just looping through and using my own over and over again. What am I
doing wrong?
different proxy servers?
As it says in the title, I am trying to access a url through several
different proxies sequentially (using for loop). Right now this is my
code:
import requests
import json
with open('proxies.txt') as proxies:
for line in proxies:
proxy=json.loads(line)
with open('urls.txt') as urls:
for line in urls:
url=line.rstrip()
data=requests.get(url, proxies={'http':line})
data1=data.text
print data1
and my urls.txt file:
http://api.exip.org/?call=ip
and my proxies.txt file:
{"https": "84.22.41.1:3128"}
{"http":"194.126.181.47:81"}
{"http":"218.108.170.170:82"}
that I got at [www.hidemyass.com][1]
for some reason, the output is
68.6.34.253
68.6.34.253
68.6.34.253
as if it is accessing that website through my own router ip address. In
other words, it is not trying to access through the proxies I give it, it
is just looping through and using my own over and over again. What am I
doing wrong?
Parse error: syntax error, unexpected '{'
Parse error: syntax error, unexpected '{'
Tried a few things, I am sure this is a minor error but I have been
staring at it for ages!
if (isset ($_GET['id']) { $product_id = strip_tags($_GET['id']); }
Can anyone see what is wrong?
Tried a few things, I am sure this is a minor error but I have been
staring at it for ages!
if (isset ($_GET['id']) { $product_id = strip_tags($_GET['id']); }
Can anyone see what is wrong?
Is Java byte code compiled in JDK 6 and runs on JDK7 open to vulnerability fixed in JDK 7?
Is Java byte code compiled in JDK 6 and runs on JDK7 open to vulnerability
fixed in JDK 7?
The motivation of my question is simple: Unfortunately Oracle stopped
development of Java 6 and will not provide any additional build. If Oracle
will discover any security issue they will fix it only in Java 7. We have
big project that developed in Java 6 and I do not have resources to
convert it to Java 7.
So, I want to compile the code in last build of JDK 6 (6u45) and to run it
in most updated build of JDK 7.
Is in this case my byte code will be open to vulnerability fixed in JDK 7?
fixed in JDK 7?
The motivation of my question is simple: Unfortunately Oracle stopped
development of Java 6 and will not provide any additional build. If Oracle
will discover any security issue they will fix it only in Java 7. We have
big project that developed in Java 6 and I do not have resources to
convert it to Java 7.
So, I want to compile the code in last build of JDK 6 (6u45) and to run it
in most updated build of JDK 7.
Is in this case my byte code will be open to vulnerability fixed in JDK 7?
How do I show an element using the below JQuery code?
How do I show an element using the below JQuery code?
CODE:
$(document).ready(function() {
$('.clicker').on('click', function(e){
e.preventDefault();
var $btn = $(this);
$btn.toggleClass('opened');
var heights = $btn.hasClass('opened') ? 300 : 100 ;
$('#thiswillexpand').stop().animate({height: heights });
});
});
By default I want #thiswillexpand to be hidden so I am going to use
display:none; But when .clicker is clicked I want it to show and then
expand as the script is supposed to.
Question:
How do I show #thiswillexpand when .clicker is clicked while still
retaining whatever the script is doing?
CODE:
$(document).ready(function() {
$('.clicker').on('click', function(e){
e.preventDefault();
var $btn = $(this);
$btn.toggleClass('opened');
var heights = $btn.hasClass('opened') ? 300 : 100 ;
$('#thiswillexpand').stop().animate({height: heights });
});
});
By default I want #thiswillexpand to be hidden so I am going to use
display:none; But when .clicker is clicked I want it to show and then
expand as the script is supposed to.
Question:
How do I show #thiswillexpand when .clicker is clicked while still
retaining whatever the script is doing?
How can $_POST pass input variables to MySQL query as integers, not 1?
How can $_POST pass input variables to MySQL query as integers, not 1?
I have a table of numbers where the user should be able to edit the values
and have the database updated on submit.
So far, my faulty code is updating every field with the value 1 on submit,
regardless of what has been inputted.
Code on submit:
//If the confirm button has been hit:
if (isset($_POST['submit'])) {
//Create the foreach loop
foreach($_POST['classtoupdate'] as $classes){
//Grab the POST data and turn it into integers
$class_id = (int)$classes;
$totalspcs = (int)$_POST['allspaces'];
$totalbkgs = (int)$_POST['allbookings'];
$newbies = (int)$_POST['noobs'];
//Change the booking numbers:
$newdeets = "UPDATE classes SET total_spaces = '$totalspcs',
total_bookings = '$totalbkgs', free_spaces = ('$totalspcs' -
'$totalbkgs'), newbies = '$newbies' WHERE class_id = '$class_id')";
echo $newdeets;
mysqli_query($dbc, $newdeets);
}
mysqli_close($dbc);
echo 'All good, yay! <a href="admin.php">Go look</a>';
}
Form:
//create the form
echo '<form method="post" action="' . $_SERVER['PHP_SELF'] . '" >';
echo '<tr><td>' . $class . '</td>';
echo'<td>' . $new_date . '</td>';
echo '<td>' . $new_time . '</td>';
echo '<td><input type="text" maxlength="2" class="input-mini"
name="noobs[]" id="noobs[]" value="' . $newbies . '">';
echo '<td><input type="text" maxlength="2" class="input-mini"
name="allspaces[]" id="allspaces[]" value="' . $totalspaces . '">';
echo '<td><input type="text" maxlength="2" class="input-mini"
name="allbookings[]" id="allbookings[]" value="' . $bookings . '"
>';
echo '<td>' . $freespaces . '</td>';
echo' <input type="hidden" name="classtoupdate[]"
id="classtoupdate[]" value="' . $class . '" />';
}
echo'</table>';
// Make booking button
echo '<input type="submit" name="submit" class="btn btn-large
btn-primary pull-right" value="Update">';
echo '</form>';
The echoed query results after inputting random values (not 1) in the form:
UPDATE classes SET total_spaces = '1', total_bookings = '1', free_spaces =
('1' - '1'), newbies = '1' WHERE class_id = '26')
UPDATE classes SET total_spaces = '1', total_bookings = '1', free_spaces =
('1' - '1'), newbies = '1' WHERE class_id = '16')
..and so on for each table row. I can't find the problem replicated after
extensive searching on SO and in the manuals.
I've tried intval(), serialize and array_map on the POST results (probably
incorrectly); I've tried different foreach loops to translate them into
integers, still no joy.
Any advice?
I have a table of numbers where the user should be able to edit the values
and have the database updated on submit.
So far, my faulty code is updating every field with the value 1 on submit,
regardless of what has been inputted.
Code on submit:
//If the confirm button has been hit:
if (isset($_POST['submit'])) {
//Create the foreach loop
foreach($_POST['classtoupdate'] as $classes){
//Grab the POST data and turn it into integers
$class_id = (int)$classes;
$totalspcs = (int)$_POST['allspaces'];
$totalbkgs = (int)$_POST['allbookings'];
$newbies = (int)$_POST['noobs'];
//Change the booking numbers:
$newdeets = "UPDATE classes SET total_spaces = '$totalspcs',
total_bookings = '$totalbkgs', free_spaces = ('$totalspcs' -
'$totalbkgs'), newbies = '$newbies' WHERE class_id = '$class_id')";
echo $newdeets;
mysqli_query($dbc, $newdeets);
}
mysqli_close($dbc);
echo 'All good, yay! <a href="admin.php">Go look</a>';
}
Form:
//create the form
echo '<form method="post" action="' . $_SERVER['PHP_SELF'] . '" >';
echo '<tr><td>' . $class . '</td>';
echo'<td>' . $new_date . '</td>';
echo '<td>' . $new_time . '</td>';
echo '<td><input type="text" maxlength="2" class="input-mini"
name="noobs[]" id="noobs[]" value="' . $newbies . '">';
echo '<td><input type="text" maxlength="2" class="input-mini"
name="allspaces[]" id="allspaces[]" value="' . $totalspaces . '">';
echo '<td><input type="text" maxlength="2" class="input-mini"
name="allbookings[]" id="allbookings[]" value="' . $bookings . '"
>';
echo '<td>' . $freespaces . '</td>';
echo' <input type="hidden" name="classtoupdate[]"
id="classtoupdate[]" value="' . $class . '" />';
}
echo'</table>';
// Make booking button
echo '<input type="submit" name="submit" class="btn btn-large
btn-primary pull-right" value="Update">';
echo '</form>';
The echoed query results after inputting random values (not 1) in the form:
UPDATE classes SET total_spaces = '1', total_bookings = '1', free_spaces =
('1' - '1'), newbies = '1' WHERE class_id = '26')
UPDATE classes SET total_spaces = '1', total_bookings = '1', free_spaces =
('1' - '1'), newbies = '1' WHERE class_id = '16')
..and so on for each table row. I can't find the problem replicated after
extensive searching on SO and in the manuals.
I've tried intval(), serialize and array_map on the POST results (probably
incorrectly); I've tried different foreach loops to translate them into
integers, still no joy.
Any advice?
Tuesday, 20 August 2013
Oracle spatial SDO_RELATE: why better performance result from UNION ALL/INTERSECT combined individual specified mask
Oracle spatial SDO_RELATE: why better performance result from UNION
ALL/INTERSECT combined individual specified mask
Initially I was trying to find out why it's so slow to do a spatial query
with multiple SDO_REALTE in a single SELECT statement like this one:
SELECT * FROM geom_table a
WHERE SDO_RELATE(a.geom_column, SDO_GEOMETRY(...), 'mask=inside')='TRUE' AND
SDO_RELATE(a.geom_column, SDO_GEOMETRY(...), 'mask=anyinteract')='TRUE';
Note the two SDO_GEOMETRY may not be necessary the same. So it's a bit
different from SDO_GEOMETRY(a.geom_column, the_same_geometry,
'mask=inside+anyinteract')='TRUE'
Then I found this paragraph from oracle documentation for SDO_RELATE:
Although multiple masks can be combined using the logical Boolean operator
OR, for example, 'mask=touch+coveredby', better performance may result if
the spatial query specifies each mask individually and uses the UNION ALL
syntax to combine the results. This is due to internal optimizations that
Spatial can apply under certain conditions when masks are specified singly
rather than grouped within the same SDO_RELATE operator call. (There are
two exceptions, inside+coveredby and contains+covers, where the
combination performs better than the UNION ALL alternative.) For example,
consider the following query using the logical Boolean operator OR to
group multiple masks:
SELECT a.gid FROM polygons a, query_polys B WHERE B.gid = 1 AND
SDO_RELATE(A.Geometry, B.Geometry,
'mask=touch+coveredby') = 'TRUE';The preceding query
may result in better performance if it is expressed as
follows, using UNION ALL to combine results of multiple
SDO_RELATE operator calls, each with a single mask:
SELECT a.gid
FROM polygons a, query_polys B
WHERE B.gid = 1
AND SDO_RELATE(A.Geometry, B.Geometry,
'mask=touch') = 'TRUE' UNION ALL SELECT a.gid
FROM polygons a, query_polys B
WHERE B.gid = 1
AND SDO_RELATE(A.Geometry, B.Geometry,
'mask=coveredby') = 'TRUE';It somehow gives the answer
for my question, but still it only says: "due to
internal optimizations that Spatial can apply under
certain conditions". So I have two questions:
What does it mean with "internal optimization", is it something to do with
spatial index? (I'm not sure if I'm too demanding on this question, maybe
only developers in oracle know about it.)
The oracle documentation doesn't say anything about my original problem,
i.e. SDO_RELATE(..., 'mask=inside') AND SDO_RELATE(...,
'maks=anyinteract') in a single SELECT. Why does it also have very bad
performance? Does it work similarly to SDO_RELATE(...,
'mask=inside+anyinteract')?
ALL/INTERSECT combined individual specified mask
Initially I was trying to find out why it's so slow to do a spatial query
with multiple SDO_REALTE in a single SELECT statement like this one:
SELECT * FROM geom_table a
WHERE SDO_RELATE(a.geom_column, SDO_GEOMETRY(...), 'mask=inside')='TRUE' AND
SDO_RELATE(a.geom_column, SDO_GEOMETRY(...), 'mask=anyinteract')='TRUE';
Note the two SDO_GEOMETRY may not be necessary the same. So it's a bit
different from SDO_GEOMETRY(a.geom_column, the_same_geometry,
'mask=inside+anyinteract')='TRUE'
Then I found this paragraph from oracle documentation for SDO_RELATE:
Although multiple masks can be combined using the logical Boolean operator
OR, for example, 'mask=touch+coveredby', better performance may result if
the spatial query specifies each mask individually and uses the UNION ALL
syntax to combine the results. This is due to internal optimizations that
Spatial can apply under certain conditions when masks are specified singly
rather than grouped within the same SDO_RELATE operator call. (There are
two exceptions, inside+coveredby and contains+covers, where the
combination performs better than the UNION ALL alternative.) For example,
consider the following query using the logical Boolean operator OR to
group multiple masks:
SELECT a.gid FROM polygons a, query_polys B WHERE B.gid = 1 AND
SDO_RELATE(A.Geometry, B.Geometry,
'mask=touch+coveredby') = 'TRUE';The preceding query
may result in better performance if it is expressed as
follows, using UNION ALL to combine results of multiple
SDO_RELATE operator calls, each with a single mask:
SELECT a.gid
FROM polygons a, query_polys B
WHERE B.gid = 1
AND SDO_RELATE(A.Geometry, B.Geometry,
'mask=touch') = 'TRUE' UNION ALL SELECT a.gid
FROM polygons a, query_polys B
WHERE B.gid = 1
AND SDO_RELATE(A.Geometry, B.Geometry,
'mask=coveredby') = 'TRUE';It somehow gives the answer
for my question, but still it only says: "due to
internal optimizations that Spatial can apply under
certain conditions". So I have two questions:
What does it mean with "internal optimization", is it something to do with
spatial index? (I'm not sure if I'm too demanding on this question, maybe
only developers in oracle know about it.)
The oracle documentation doesn't say anything about my original problem,
i.e. SDO_RELATE(..., 'mask=inside') AND SDO_RELATE(...,
'maks=anyinteract') in a single SELECT. Why does it also have very bad
performance? Does it work similarly to SDO_RELATE(...,
'mask=inside+anyinteract')?
Error in Google Apps Script: mime type error when using getPlainText
Error in Google Apps Script: mime type error when using getPlainText
When I tried to use the getPlainBody() method of GmailMessage class. When
I execute the following code, the error message "Invalid MIME type" show
up. Can anyone help me to verify what's wrong in my code?
function processLabel(labelName) {
var targetLabel = GmailApp.getUserLabelByName(labelName);
var targetThreads = targetLabel.getThreads();
return targetThreads;
};
function getEmailPlainText() {
var targetThreads = processLabel('@today');
var threadsCount = targetThreads.length;
for (var i = 0; i < threadsCount; i++) {
var targetThread = targetThreads[i];
var messageCount = targetThread.getMessageCount();
var subject = targetThread.getFirstMessageSubject();
var lastMessage = targetThread.getMessages()[messageCount-1];
var lastMessageContent = lastMessageContent = lastMessage.getPlainBody();
};
When I tried to use the getPlainBody() method of GmailMessage class. When
I execute the following code, the error message "Invalid MIME type" show
up. Can anyone help me to verify what's wrong in my code?
function processLabel(labelName) {
var targetLabel = GmailApp.getUserLabelByName(labelName);
var targetThreads = targetLabel.getThreads();
return targetThreads;
};
function getEmailPlainText() {
var targetThreads = processLabel('@today');
var threadsCount = targetThreads.length;
for (var i = 0; i < threadsCount; i++) {
var targetThread = targetThreads[i];
var messageCount = targetThread.getMessageCount();
var subject = targetThread.getFirstMessageSubject();
var lastMessage = targetThread.getMessages()[messageCount-1];
var lastMessageContent = lastMessageContent = lastMessage.getPlainBody();
};
Java file input not working after compile
Java file input not working after compile
so I trying to import a file that's in my res folder, so far I have been
using this method.
File f = new File("src/resources/levels/" + part + "/" + filename + ".txt");
But after I compile it and run it as a jar it no longer works, I
understand this is because its looking for the file on the disk instead of
the jar, I had the same problem with importing my images and font but I
managed to fix that but after researching and I just can't find a
different way. I'm not getting any errors when I run the jar, instead the
information just doesn't show up, and this is compiling and running fine
in eclipse.
This is my resource file:
package scrolls;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import org.imgscalr.Scalr;
public class Resources
{
static BufferedImage[] textures = new BufferedImage[8];
static BufferedImage[] mapTextures = new BufferedImage[9];
static BufferedImage texture;
static BufferedImage[] waterAnimated = new BufferedImage[64];
static BufferedImage water;
static BufferedImage icon;
public static Font f, fs;
static int imageCounter = 0;
public Resources()
{
textures();
createArray(texture, textures, 32, 1, 8);
createArray(water, waterAnimated, 32, 64, 1);
getFont();
buildMapTextures(textures, mapTextures);
}
public static void counter()
{
imageCounter++;
if (imageCounter >= 500)
imageCounter = 0;
//System.out.println(imageCounter / 8);
}
private void buildMapTextures(BufferedImage[] textures,
BufferedImage[] mapTextures)
{
for (int i = 0; i <= 7; i++)
{
mapTextures[i] = resize(textures[i], 3, 3);
}
mapTextures[8] = resize(waterAnimated[2], 3, 3);
}
private BufferedImage resize(BufferedImage image, int newW, int newH)
{
BufferedImage thumbnail = Scalr.resize(image,
Scalr.Method.ULTRA_QUALITY, Scalr.Mode.FIT_EXACT, newW, newH,
Scalr.OP_ANTIALIAS);
return thumbnail;
}
public static BufferedImage waterAnimation()
{
return waterAnimated[imageCounter / 8];
}
private void textures()
{
try
{
texture =
ImageIO.read(Resource.class.getResource("/resources/textures.png"));
} catch (IOException e)
{
}
try
{
water =
ImageIO.read(Resource.class.getResource("/resources/water.png"));
} catch (IOException e)
{
}
try
{
icon =
ImageIO.read(Resource.class.getResource("/resources/icon.png"));
} catch (IOException e)
{
}
}
static BufferedImage player()
{
BufferedImage player = null;
try
{
player =
ImageIO.read(Resource.class.getResource("/resources/player.png"));
} catch (IOException e)
{
}
return player;
}
static void createArray(BufferedImage image, BufferedImage[] images,
int size, int rows, int cols)
{
BufferedImage temp = image;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
images[(i * cols) + j] = temp.getSubimage(j * size, i *
size, size, size);
}
}
}
void readLevel(String filename, int[][] level, int part)
{
try
{
File f = new File("src/resources/levels/" + part + "/" +
filename + ".txt");
FileReader fr = new FileReader(f);
BufferedReader in = new BufferedReader(fr);
StringBuilder sb = new StringBuilder();
byte b = 0;
while ((b = (byte) in.read()) != -1)
{
sb.append("" + ((char) b));
}
String str = sb.toString();
String[] lines = str.split("(\n|\r)+");
for (int i = 0; i < lines.length; i++)
{
for (int j = 0; j < lines[i].length(); j++)
{
level[i][j] = Integer.parseInt("" + lines[i].charAt(j));
}
}
in.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
private void getFont()
{
try
{
f = Font.createFont(Font.TRUETYPE_FONT,
getClass().getResourceAsStream("/resources/Jet Set.ttf"));
fs = Font.createFont(Font.TRUETYPE_FONT,
getClass().getResourceAsStream("/resources/Jet Set.ttf"));
} catch (Exception e)
{
System.out.println(e);
}
f = f.deriveFont(22f);
fs = fs.deriveFont(13f);
}
}
So how would I import my file so it can be read when compiled into a jar?
so I trying to import a file that's in my res folder, so far I have been
using this method.
File f = new File("src/resources/levels/" + part + "/" + filename + ".txt");
But after I compile it and run it as a jar it no longer works, I
understand this is because its looking for the file on the disk instead of
the jar, I had the same problem with importing my images and font but I
managed to fix that but after researching and I just can't find a
different way. I'm not getting any errors when I run the jar, instead the
information just doesn't show up, and this is compiling and running fine
in eclipse.
This is my resource file:
package scrolls;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import org.imgscalr.Scalr;
public class Resources
{
static BufferedImage[] textures = new BufferedImage[8];
static BufferedImage[] mapTextures = new BufferedImage[9];
static BufferedImage texture;
static BufferedImage[] waterAnimated = new BufferedImage[64];
static BufferedImage water;
static BufferedImage icon;
public static Font f, fs;
static int imageCounter = 0;
public Resources()
{
textures();
createArray(texture, textures, 32, 1, 8);
createArray(water, waterAnimated, 32, 64, 1);
getFont();
buildMapTextures(textures, mapTextures);
}
public static void counter()
{
imageCounter++;
if (imageCounter >= 500)
imageCounter = 0;
//System.out.println(imageCounter / 8);
}
private void buildMapTextures(BufferedImage[] textures,
BufferedImage[] mapTextures)
{
for (int i = 0; i <= 7; i++)
{
mapTextures[i] = resize(textures[i], 3, 3);
}
mapTextures[8] = resize(waterAnimated[2], 3, 3);
}
private BufferedImage resize(BufferedImage image, int newW, int newH)
{
BufferedImage thumbnail = Scalr.resize(image,
Scalr.Method.ULTRA_QUALITY, Scalr.Mode.FIT_EXACT, newW, newH,
Scalr.OP_ANTIALIAS);
return thumbnail;
}
public static BufferedImage waterAnimation()
{
return waterAnimated[imageCounter / 8];
}
private void textures()
{
try
{
texture =
ImageIO.read(Resource.class.getResource("/resources/textures.png"));
} catch (IOException e)
{
}
try
{
water =
ImageIO.read(Resource.class.getResource("/resources/water.png"));
} catch (IOException e)
{
}
try
{
icon =
ImageIO.read(Resource.class.getResource("/resources/icon.png"));
} catch (IOException e)
{
}
}
static BufferedImage player()
{
BufferedImage player = null;
try
{
player =
ImageIO.read(Resource.class.getResource("/resources/player.png"));
} catch (IOException e)
{
}
return player;
}
static void createArray(BufferedImage image, BufferedImage[] images,
int size, int rows, int cols)
{
BufferedImage temp = image;
for (int i = 0; i < rows; i++)
{
for (int j = 0; j < cols; j++)
{
images[(i * cols) + j] = temp.getSubimage(j * size, i *
size, size, size);
}
}
}
void readLevel(String filename, int[][] level, int part)
{
try
{
File f = new File("src/resources/levels/" + part + "/" +
filename + ".txt");
FileReader fr = new FileReader(f);
BufferedReader in = new BufferedReader(fr);
StringBuilder sb = new StringBuilder();
byte b = 0;
while ((b = (byte) in.read()) != -1)
{
sb.append("" + ((char) b));
}
String str = sb.toString();
String[] lines = str.split("(\n|\r)+");
for (int i = 0; i < lines.length; i++)
{
for (int j = 0; j < lines[i].length(); j++)
{
level[i][j] = Integer.parseInt("" + lines[i].charAt(j));
}
}
in.close();
} catch (Exception e)
{
e.printStackTrace();
}
}
private void getFont()
{
try
{
f = Font.createFont(Font.TRUETYPE_FONT,
getClass().getResourceAsStream("/resources/Jet Set.ttf"));
fs = Font.createFont(Font.TRUETYPE_FONT,
getClass().getResourceAsStream("/resources/Jet Set.ttf"));
} catch (Exception e)
{
System.out.println(e);
}
f = f.deriveFont(22f);
fs = fs.deriveFont(13f);
}
}
So how would I import my file so it can be read when compiled into a jar?
php post data is always empty
php post data is always empty
i am trying to send myself an email message using jquery and php i want
the contents of the message to be decided by jquery this is my sending
code
$.ajax({
url: 'http://mywebpage.com/email.php',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data:'test',
dataType: "text",
success: function(data){
console.log(data);
console.log("IT WORKED");
},
failure: function(result){
console.log("FAILED");
console.log(result);
}
});
this is my php script
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header("Access-Control-Allow-Headers: Origin, X-Requested-With,
Content-Type, Accept");
$to = "myemail@gmail.com";
$subject = "Test mail";
$message = $_POST["data"];
echo var_dump($_POST);
echo $message;
$from = "someonelse@example.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>
the email gets sent, but the $_POST["data"] always comes back empty what
to do ?
i am trying to send myself an email message using jquery and php i want
the contents of the message to be decided by jquery this is my sending
code
$.ajax({
url: 'http://mywebpage.com/email.php',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data:'test',
dataType: "text",
success: function(data){
console.log(data);
console.log("IT WORKED");
},
failure: function(result){
console.log("FAILED");
console.log(result);
}
});
this is my php script
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header("Access-Control-Allow-Headers: Origin, X-Requested-With,
Content-Type, Accept");
$to = "myemail@gmail.com";
$subject = "Test mail";
$message = $_POST["data"];
echo var_dump($_POST);
echo $message;
$from = "someonelse@example.com";
$headers = "From:" . $from;
mail($to,$subject,$message,$headers);
echo "Mail Sent.";
?>
the email gets sent, but the $_POST["data"] always comes back empty what
to do ?
Passing parameter to a function in C#
Passing parameter to a function in C#
I have a small program. It includes a listbox and few textboxes. There are
few elements in the listbox and depending on the selected index it outputs
the corresponding values into the textboxes.
Code example: http://notepad.cc/share/AGh5zLNjfJ
I want to use a function to print the values into the textboxes instead of
typing them over and over again in switch cases.
Something like this:
switch(personList.SelectedIndex)
{
case 0:
output(person1);
break;
case 1;
output(person2);
break;
}
I couldn't pass the person object and access its properties with the
function I created. SOS.
I have a small program. It includes a listbox and few textboxes. There are
few elements in the listbox and depending on the selected index it outputs
the corresponding values into the textboxes.
Code example: http://notepad.cc/share/AGh5zLNjfJ
I want to use a function to print the values into the textboxes instead of
typing them over and over again in switch cases.
Something like this:
switch(personList.SelectedIndex)
{
case 0:
output(person1);
break;
case 1;
output(person2);
break;
}
I couldn't pass the person object and access its properties with the
function I created. SOS.
Theorem numeration shift
Theorem numeration shift
I would like to numerate my theorems not by chapters but by shifted
chapters in such a way that the theorems in chapter 2 would read Theorem
1.1, Theorem 1.2 and so on.
I need something along the lines of
\newteorem{thm}{Theorem}["chapter - 1"]
where I don't know the correct syntax for "chapter - 1".
I would like to numerate my theorems not by chapters but by shifted
chapters in such a way that the theorems in chapter 2 would read Theorem
1.1, Theorem 1.2 and so on.
I need something along the lines of
\newteorem{thm}{Theorem}["chapter - 1"]
where I don't know the correct syntax for "chapter - 1".
Can java access the text on websites?
Can java access the text on websites?
This question comes up in my past exam papers over and over.
I can do the bottom two classes and make them extend etc. What I do not
understand is the objectlist class.
What is the point of it? I assume it just holds the data but would it not
be better to hold the data in the tenantList class?
If someone can explain what it is for and what it does I would be very
thankful!
Here is the image: http://s10.postimg.org/ry7lwdeuh/stackover.png
This question comes up in my past exam papers over and over.
I can do the bottom two classes and make them extend etc. What I do not
understand is the objectlist class.
What is the point of it? I assume it just holds the data but would it not
be better to hold the data in the tenantList class?
If someone can explain what it is for and what it does I would be very
thankful!
Here is the image: http://s10.postimg.org/ry7lwdeuh/stackover.png
Monday, 19 August 2013
Error uploading zip file on dropbox
Error uploading zip file on dropbox
-(void) uploadToDropbox {
NSString *targetFile = PATH_ZIP_FILE;
DropboxListingView *dropboxView = [[DropboxListingView alloc]
initWithPath:@"/" withDelegate:self mode:ImportExportModeExport];
dropboxView.uploadFiles = [NSArray arrayWithObject:targetFile];
UINavigationController *navigationController = [[UINavigationController
alloc] initWithRootViewController:dropboxView];
[self presentViewController:navigationController animated:YES
completion:nil];
}
i am getting this warning
[WARNING] DropboxSDK: error making request to
/1/files_put/dropbox/CurrentDocument.zip - (403) Forbidden
-(void) uploadToDropbox {
NSString *targetFile = PATH_ZIP_FILE;
DropboxListingView *dropboxView = [[DropboxListingView alloc]
initWithPath:@"/" withDelegate:self mode:ImportExportModeExport];
dropboxView.uploadFiles = [NSArray arrayWithObject:targetFile];
UINavigationController *navigationController = [[UINavigationController
alloc] initWithRootViewController:dropboxView];
[self presentViewController:navigationController animated:YES
completion:nil];
}
i am getting this warning
[WARNING] DropboxSDK: error making request to
/1/files_put/dropbox/CurrentDocument.zip - (403) Forbidden
how to round an odd integer towards the nearest power of two
how to round an odd integer towards the nearest power of two
Add one to or subtract one from an odd integer such that the even result
is closer to the nearest power of two.
if ( ??? ) x += 1; else x -= 1;// x > 2 and odd
For example, 25 through 47 round towards 32, adding one to 25 through 31
and subtracting one from 33 through 47. 23 rounds down towards 16 to 22
and 49 rounds up towards 64 to 50.
Is there a way to do this without finding the specific power of two that
is being rounded towards. I know how to use a logarithm or count bits to
get the specific power of two.
My specific use case for this is in splitting odd sized inputs to
karatsuba multiplication.
Add one to or subtract one from an odd integer such that the even result
is closer to the nearest power of two.
if ( ??? ) x += 1; else x -= 1;// x > 2 and odd
For example, 25 through 47 round towards 32, adding one to 25 through 31
and subtracting one from 33 through 47. 23 rounds down towards 16 to 22
and 49 rounds up towards 64 to 50.
Is there a way to do this without finding the specific power of two that
is being rounded towards. I know how to use a logarithm or count bits to
get the specific power of two.
My specific use case for this is in splitting odd sized inputs to
karatsuba multiplication.
How to stop TFS from checking out after a get latest
How to stop TFS from checking out after a get latest
I have this issue where if I do a 'get latest' on a file in TFS it
straight away prompts to do a check out of the file. It actually greys out
the cancel button. I am not sure why getting a latest version should make
a file be automatically checked out since I thought the idea was the you
only check out a file if you wish to edit it and then check it in again -
not just because you have downloaded the latest version.
Any ideas much appreciated!
I have this issue where if I do a 'get latest' on a file in TFS it
straight away prompts to do a check out of the file. It actually greys out
the cancel button. I am not sure why getting a latest version should make
a file be automatically checked out since I thought the idea was the you
only check out a file if you wish to edit it and then check it in again -
not just because you have downloaded the latest version.
Any ideas much appreciated!
accessing json inside request body
accessing json inside request body
I am using an API provided to us by someone else and it returns it this way:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://ywers.com">
[{"Name":"Edward", "LastName":"Jones", "Address":"{accepted}"}
,{"Name":"Carlos", "LastName":"Ramirez", "Address":"{Rejected}"}]</string>
what is the best way to extract the JSON and also, how can I brake the
JSON into separate objects like
{"Name":"Edward", "LastName":"Jones", "Address":"{accepted}"}
and
{"Name":"Carlos", "LastName":"Ramirez", "Address":"{Rejected}"}
As you can see one of the fields returns with a bracket inside. Another
issue i am having is that i think the brackets are coming as question
signs when i print the response.
I am using an API provided to us by someone else and it returns it this way:
<?xml version="1.0" encoding="utf-8"?>
<string xmlns="http://ywers.com">
[{"Name":"Edward", "LastName":"Jones", "Address":"{accepted}"}
,{"Name":"Carlos", "LastName":"Ramirez", "Address":"{Rejected}"}]</string>
what is the best way to extract the JSON and also, how can I brake the
JSON into separate objects like
{"Name":"Edward", "LastName":"Jones", "Address":"{accepted}"}
and
{"Name":"Carlos", "LastName":"Ramirez", "Address":"{Rejected}"}
As you can see one of the fields returns with a bracket inside. Another
issue i am having is that i think the brackets are coming as question
signs when i print the response.
TSQL Primary key over too many columns?
TSQL Primary key over too many columns?
I have table A and B which cannot be edited and both using composite
primary keys (region_id, number).
I have N tables, so called Information, each has its own ID as primary key.
A(or B) <-> Info Tables are M:N relationship and I need such a table. So I
designed a table CtoInfo (where C is either A or B) with these columns
CREATE TABLE CtoInfo (
region_id ..
c_number ..
c_type // either A or B
info_id
info_type
.. //some other columns
)
first 3 columns identify A or B, other 2 columns, the info. (type says
which table and id is the PK)
Now I want to make a Primary key on this table. But it looks like I need
to include 5 columns in that PK constraint !?
I have table A and B which cannot be edited and both using composite
primary keys (region_id, number).
I have N tables, so called Information, each has its own ID as primary key.
A(or B) <-> Info Tables are M:N relationship and I need such a table. So I
designed a table CtoInfo (where C is either A or B) with these columns
CREATE TABLE CtoInfo (
region_id ..
c_number ..
c_type // either A or B
info_id
info_type
.. //some other columns
)
first 3 columns identify A or B, other 2 columns, the info. (type says
which table and id is the PK)
Now I want to make a Primary key on this table. But it looks like I need
to include 5 columns in that PK constraint !?
get integer sub array from string javascript
get integer sub array from string javascript
I have string like
string sHTMLTable = "John,5,3,4,7,2|Jane,2,2,3,2,1|Joe,3,4,4,2,5";
I am using following code to get output like
series: [{
name: 'John',
data: [5, 3, 4, 7, 2]
}, {
name: 'Jane',
data: [2, 2, 3, 2, 1]
}, {
name: 'Joe',
data: [3, 4, 4, 2, 5]
}]
Code :-
var res = sHTMLTable.split("|").map(function (s) {
var arr = s.split(",");
return { name: arr.shift(), data: arr.map(Number) };
});
still my highcharts does not load My suspect is data: [3, 4, 4, 2, 5] is a
string array i want it as integer array
how to convert it as integer array
I have string like
string sHTMLTable = "John,5,3,4,7,2|Jane,2,2,3,2,1|Joe,3,4,4,2,5";
I am using following code to get output like
series: [{
name: 'John',
data: [5, 3, 4, 7, 2]
}, {
name: 'Jane',
data: [2, 2, 3, 2, 1]
}, {
name: 'Joe',
data: [3, 4, 4, 2, 5]
}]
Code :-
var res = sHTMLTable.split("|").map(function (s) {
var arr = s.split(",");
return { name: arr.shift(), data: arr.map(Number) };
});
still my highcharts does not load My suspect is data: [3, 4, 4, 2, 5] is a
string array i want it as integer array
how to convert it as integer array
Sunday, 18 August 2013
How to add another language to a Samsung Galaxy Chat physical keyboard?
How to add another language to a Samsung Galaxy Chat physical keyboard?
Having got a Samsung Galaxy Chat (B5330) I'd like to use its physical
keyboard to to enter not only english but also central european (czech)
and cyrillic (russian) letters (I am ok with english-only key labels). So,
any directions on where and how?
Having got a Samsung Galaxy Chat (B5330) I'd like to use its physical
keyboard to to enter not only english but also central european (czech)
and cyrillic (russian) letters (I am ok with english-only key labels). So,
any directions on where and how?
NavigationCommand CommandBinding does not seem to be working in my unit tests
NavigationCommand CommandBinding does not seem to be working in my unit tests
I have a Wizard implementation in my WPF application. It's moreso setup as
a framework that people can plug a list of "pages". Part of this Wizard
implementation is to bind to the NavigationCommands.NextPage and
PreviousPage commands. This is done in code.
The bindings work just fine when running the application. They do not,
however, seem to work during unit testing.
Based on the code below, anytime NavigationCommands.NextPage(null, null)
is called, the nextCommand_executed() method should be hit.
Again...this works just fine during normal running of the application.
Under test, however, it does not.
Is there something obvious that I'm missing? My unit test does require
STAThread...but this is ok under the current testing circumstances (more
tests which require STAThread).
private readonly CommandBindingCollection _commandBindings = new
CommandBindingCollection();
public CommandBindingCollection CommandBindings
{ get { return _commandBindings; } }
public WizardMainViewModel(IWizardContent wizardContent)
{
var nextPageBinding = new CommandBinding(NavigationCommands.NextPage,
nextCommand_Executed, nextCommand_CanExecute);
var previousPageBinding = new
CommandBinding(NavigationCommands.PreviousPage, backCommand_Executed,
backCommand_CanExecute);
var browseBackBinding = new
CommandBinding(NavigationCommands.BrowseBack, okCommand_Executed,
okCommand_CanExecute);
//Register the bindings to this class
CommandManager.RegisterClassCommandBinding(typeof(WizardMainViewModel),
nextPageBinding);
CommandManager.RegisterClassCommandBinding(typeof(WizardMainViewModel),
previousPageBinding);
CommandManager.RegisterClassCommandBinding(typeof(WizardMainViewModel),
browseBackBinding);
//Adds the binding to the CommandBindingCollection
CommandBindings.Add(nextPageBinding);
CommandBindings.Add(previousPageBinding);
CommandBindings.Add(browseBackBinding);
}
private void nextCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
if (!WizardViewModel.CurrentPageVM.Validate())
{
}
//bunch of unnecessary to post code
}
THE TEST:
[Test]
public void MakeNextWork()
{
var vm = new FakeWizardViewModel();
var wizContent = new FakeWizardContent(vm);
var wiz = new Wizard(wizContent);
wiz.Show();
try
{
var dataContext = wiz.DataContext as WizardMainViewModel;
//wiz.Dispatcher.Invoke(new Action(() =>
NavigationCommands.NextPage.Execute(null, null)));
NavigationCommands.NextPage.Execute(null, null)));
var currentPageVM = vm.CurrentPageVM;
if (currentPageVM == null) Console.WriteLine("boo");
}
finally
{
wiz.Close();
}
}
public class FakeWizardContent : WizardContent
{
public FakeWizardContent(WizardViewModelBase viewModel)
: base(viewModel)
{
}
}
public class FakeWizardViewModel : WizardViewModelBase
{
public FakeWizardViewModel()
{
}
private List<WizardStepBaseViewModel> _vmPages;
public override List<WizardStepBaseViewModel> VMPages
{
get
{
if (_vmPages == null)
{
_vmPages = new List<WizardStepBaseViewModel>
{
Mock.Of<WizardStepBaseViewModel>(),
Mock.Of<WizardStepBaseViewModel>(),
Mock.Of<WizardStepBaseViewModel>()
};
CurrentPageVM = _vmPages[0];
}
return _vmPages;
}
}
public override string WizardTitleCaption
{
get { return string.Empty; }
}
}
I have a Wizard implementation in my WPF application. It's moreso setup as
a framework that people can plug a list of "pages". Part of this Wizard
implementation is to bind to the NavigationCommands.NextPage and
PreviousPage commands. This is done in code.
The bindings work just fine when running the application. They do not,
however, seem to work during unit testing.
Based on the code below, anytime NavigationCommands.NextPage(null, null)
is called, the nextCommand_executed() method should be hit.
Again...this works just fine during normal running of the application.
Under test, however, it does not.
Is there something obvious that I'm missing? My unit test does require
STAThread...but this is ok under the current testing circumstances (more
tests which require STAThread).
private readonly CommandBindingCollection _commandBindings = new
CommandBindingCollection();
public CommandBindingCollection CommandBindings
{ get { return _commandBindings; } }
public WizardMainViewModel(IWizardContent wizardContent)
{
var nextPageBinding = new CommandBinding(NavigationCommands.NextPage,
nextCommand_Executed, nextCommand_CanExecute);
var previousPageBinding = new
CommandBinding(NavigationCommands.PreviousPage, backCommand_Executed,
backCommand_CanExecute);
var browseBackBinding = new
CommandBinding(NavigationCommands.BrowseBack, okCommand_Executed,
okCommand_CanExecute);
//Register the bindings to this class
CommandManager.RegisterClassCommandBinding(typeof(WizardMainViewModel),
nextPageBinding);
CommandManager.RegisterClassCommandBinding(typeof(WizardMainViewModel),
previousPageBinding);
CommandManager.RegisterClassCommandBinding(typeof(WizardMainViewModel),
browseBackBinding);
//Adds the binding to the CommandBindingCollection
CommandBindings.Add(nextPageBinding);
CommandBindings.Add(previousPageBinding);
CommandBindings.Add(browseBackBinding);
}
private void nextCommand_Executed(object sender, ExecutedRoutedEventArgs e)
{
if (!WizardViewModel.CurrentPageVM.Validate())
{
}
//bunch of unnecessary to post code
}
THE TEST:
[Test]
public void MakeNextWork()
{
var vm = new FakeWizardViewModel();
var wizContent = new FakeWizardContent(vm);
var wiz = new Wizard(wizContent);
wiz.Show();
try
{
var dataContext = wiz.DataContext as WizardMainViewModel;
//wiz.Dispatcher.Invoke(new Action(() =>
NavigationCommands.NextPage.Execute(null, null)));
NavigationCommands.NextPage.Execute(null, null)));
var currentPageVM = vm.CurrentPageVM;
if (currentPageVM == null) Console.WriteLine("boo");
}
finally
{
wiz.Close();
}
}
public class FakeWizardContent : WizardContent
{
public FakeWizardContent(WizardViewModelBase viewModel)
: base(viewModel)
{
}
}
public class FakeWizardViewModel : WizardViewModelBase
{
public FakeWizardViewModel()
{
}
private List<WizardStepBaseViewModel> _vmPages;
public override List<WizardStepBaseViewModel> VMPages
{
get
{
if (_vmPages == null)
{
_vmPages = new List<WizardStepBaseViewModel>
{
Mock.Of<WizardStepBaseViewModel>(),
Mock.Of<WizardStepBaseViewModel>(),
Mock.Of<WizardStepBaseViewModel>()
};
CurrentPageVM = _vmPages[0];
}
return _vmPages;
}
}
public override string WizardTitleCaption
{
get { return string.Empty; }
}
}
How can I handle file uploading to other apps and sites? Android
How can I handle file uploading to other apps and sites? Android
I am working on a simple android file manager. The problem I am facing is
getting my app to upload files to another app or site when someone wants
to send files and such. I tried reading through the developer docs, but
they were a bit confusing. How can I set up my MainActivity(If that is a
good place to put this) to handle this and allow the uploading of files?
Here is what I have in my manifest...
<activity android:name="com.myapp.MainActivity"
android:label="@string/app_name"
android:configChanges="keyboardHidden|screenSize|orientation">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.GET_CONTENT"/>
<category android:name="android.intent.category.OPENABLE"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="*/*"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.PICK"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="file"/>
<data android:scheme="folder"/>
<data android:scheme="directory"/>
</intent-filter>
<meta-data android:name="android.app.searchable"
android:resource="@xml/searchable"/>
</activity>
I am working on a simple android file manager. The problem I am facing is
getting my app to upload files to another app or site when someone wants
to send files and such. I tried reading through the developer docs, but
they were a bit confusing. How can I set up my MainActivity(If that is a
good place to put this) to handle this and allow the uploading of files?
Here is what I have in my manifest...
<activity android:name="com.myapp.MainActivity"
android:label="@string/app_name"
android:configChanges="keyboardHidden|screenSize|orientation">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.GET_CONTENT"/>
<category android:name="android.intent.category.OPENABLE"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="*/*"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.PICK"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="file"/>
<data android:scheme="folder"/>
<data android:scheme="directory"/>
</intent-filter>
<meta-data android:name="android.app.searchable"
android:resource="@xml/searchable"/>
</activity>
Running PHP, Ruby or Python processes in sandbox mode
Running PHP, Ruby or Python processes in sandbox mode
I'm working on a small weekend project, which is basically an online IDE
that allows you to run PHP, Ruby or Python code from the browser. I have
everything setup and working, but the way i created the system, if a user
runs a badly-written script, or a script with heavy-calculation, the
system might slow down for everyone until i reach the timeout (15
seconds).
My system does not pass the fibonacci test. How can i run the process in
isolation, that would allow users to create:
while (true) { fibonacci() } // pseudo-code
Without crashing the server? I have considered the following courses of
action:
Running each process inside a Docker (https://www.docker.io) container,
but i'm not sure how docker deals with slow containers
Running each process inside a VM
Running each process in an instantly-created EC2 instance (which is not
really an option, since this is slow and expensive)
I'm working on a small weekend project, which is basically an online IDE
that allows you to run PHP, Ruby or Python code from the browser. I have
everything setup and working, but the way i created the system, if a user
runs a badly-written script, or a script with heavy-calculation, the
system might slow down for everyone until i reach the timeout (15
seconds).
My system does not pass the fibonacci test. How can i run the process in
isolation, that would allow users to create:
while (true) { fibonacci() } // pseudo-code
Without crashing the server? I have considered the following courses of
action:
Running each process inside a Docker (https://www.docker.io) container,
but i'm not sure how docker deals with slow containers
Running each process inside a VM
Running each process in an instantly-created EC2 instance (which is not
really an option, since this is slow and expensive)
What cause the session is recreate or gone after refresh page?
What cause the session is recreate or gone after refresh page?
im using codeigniter on my project, and i have a login module and i have
authenticate the each module when the session is not exist then redirect
to the login page. so, this is work but sometimes it may happen when i
login then i refresh the page then i redirect to the login page (means
session is gone!).
Don't try to call me use other library such as php native or etc. i just
want to know what is the problem to cause this happen?
function _admin_login()
{
$this->form_validation->set_rules($this->login_rules);
$data['title'] = "Login";
$data['form_url'] = $this->uri->uri_string();
$data['login_btn'] = form_submit('login','Sign In','class="btn
btn-large btn-block btn-primary"');
if($this->form_validation->run($this) == FALSE){
$data['user'] =
form_input('username','','class="input-block-level
input-large" placeholder="Username"');
$data['passw'] =
form_password('password','','class="input-block-level
input-large" placeholder="Password"');
$this->template->set('title','Login');
$this->template->load('template_login','login_view',$data);
}else{
$username = $this->input->post('username',true);
$row = $this->authentication_model->get_user_info($username);
$this->session->set_userdata('user',$row['user_id']);
$this->session->set_userdata('username',$row['username']);
$this->session->set_userdata('login_state',true);
$this->authentication_model->update_last_login();
redirect('product');
}
}
this is my login script, if validation pass then set the session... and in
every controller i had check the session script. example below
$this->authentication_plugin->check_logged_in();
function check_logged_in()
{
if(logged_in() === FALSE){
set_alert('Login in to view this page!!','error');
set_bookmark('login_url');
redirect("login");
}
}
function logged_in()
{
$CI =& get_instance();
$user = $CI->session->userdata('user');
if(!$CI->load->library('session')){
echo "no session is loaded";
die;
}
if(!empty($user)){
return true;
}else{
return false;
}
}
so any idea? thank~!!
im using codeigniter on my project, and i have a login module and i have
authenticate the each module when the session is not exist then redirect
to the login page. so, this is work but sometimes it may happen when i
login then i refresh the page then i redirect to the login page (means
session is gone!).
Don't try to call me use other library such as php native or etc. i just
want to know what is the problem to cause this happen?
function _admin_login()
{
$this->form_validation->set_rules($this->login_rules);
$data['title'] = "Login";
$data['form_url'] = $this->uri->uri_string();
$data['login_btn'] = form_submit('login','Sign In','class="btn
btn-large btn-block btn-primary"');
if($this->form_validation->run($this) == FALSE){
$data['user'] =
form_input('username','','class="input-block-level
input-large" placeholder="Username"');
$data['passw'] =
form_password('password','','class="input-block-level
input-large" placeholder="Password"');
$this->template->set('title','Login');
$this->template->load('template_login','login_view',$data);
}else{
$username = $this->input->post('username',true);
$row = $this->authentication_model->get_user_info($username);
$this->session->set_userdata('user',$row['user_id']);
$this->session->set_userdata('username',$row['username']);
$this->session->set_userdata('login_state',true);
$this->authentication_model->update_last_login();
redirect('product');
}
}
this is my login script, if validation pass then set the session... and in
every controller i had check the session script. example below
$this->authentication_plugin->check_logged_in();
function check_logged_in()
{
if(logged_in() === FALSE){
set_alert('Login in to view this page!!','error');
set_bookmark('login_url');
redirect("login");
}
}
function logged_in()
{
$CI =& get_instance();
$user = $CI->session->userdata('user');
if(!$CI->load->library('session')){
echo "no session is loaded";
die;
}
if(!empty($user)){
return true;
}else{
return false;
}
}
so any idea? thank~!!
My App keeps on crashing without calling "didFinishLaunchingWithOptions:" method
My App keeps on crashing without calling "didFinishLaunchingWithOptions:"
method
My App keeps on crashing even it is not calling the AppDelegate Method.
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
What is happening that. It runs First time smoothly now When I run second
time it crashes. This is happening even times (One by one) I run the App.
Means First time run, it runs, then second time crashes, third time runs,
fourth time crashes, etc....
MAC OSX version: 10.8.4
XCode Version: 4.6.2
Suggest me What should I do?
method
My App keeps on crashing even it is not calling the AppDelegate Method.
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
What is happening that. It runs First time smoothly now When I run second
time it crashes. This is happening even times (One by one) I run the App.
Means First time run, it runs, then second time crashes, third time runs,
fourth time crashes, etc....
MAC OSX version: 10.8.4
XCode Version: 4.6.2
Suggest me What should I do?
Saturday, 17 August 2013
Show total number of related records?
Show total number of related records?
I am new to SugarCRm Development. I built a custom module for Projects,
Project Tasks, and Project Files.
Projects has a One to Many Relationship with Project Tasks, and Project Files
So when you view a Projects ViewDetails page, it has 2 subpanels for the 2
other modules.
What I would like to do is on the Projects page, show some stats about the
other items. For example I would like to show...
the total number of Project Files related to the current project.
the total number of Project Tasks related to the current project.
the total number of Project Tasks marked as completed.
I know how to edit a variable in the Project view and make it use my
custom code, I just don't know how to get the data I am after to insert
into that place.
Any help in the right direction would be great, thank you
I am new to SugarCRm Development. I built a custom module for Projects,
Project Tasks, and Project Files.
Projects has a One to Many Relationship with Project Tasks, and Project Files
So when you view a Projects ViewDetails page, it has 2 subpanels for the 2
other modules.
What I would like to do is on the Projects page, show some stats about the
other items. For example I would like to show...
the total number of Project Files related to the current project.
the total number of Project Tasks related to the current project.
the total number of Project Tasks marked as completed.
I know how to edit a variable in the Project view and make it use my
custom code, I just don't know how to get the data I am after to insert
into that place.
Any help in the right direction would be great, thank you
Simplest Schrödinger equation with both continuous and residual spectrum
Simplest Schrödinger equation with both continuous and residual spectrum
Consider a Schrödinger equation:
$$-\frac{\text{d}^2}{\text{d}x^2}f(x)+U(x)f(x)=Ef(x),$$
I need a $U(x)$ satisfying the following:
The Schrödinger equation with it must be solvable purely analytically,
without need for any numerics (but using special functions is acceptable)
$\displaystyle \lim_{x\to\infty} U(\pm x)=0$
$\exists a,b: U(x)<0\;\forall x\in[a,b]$
I.e. $U(x)$ should represent some potential well, which would have both
free and bound states.
Are there any such $U(x)$? If yes, what are examples?
Examples of what does not answer the question are:
finite square potential well, because to solve it one has to solve
transcendental equations, which need numerics
$\delta$-shaped potential well, since despite it can be solved
analytically for infinite space, it still results in transcendental
equation when $x\in[q,r]$
Consider a Schrödinger equation:
$$-\frac{\text{d}^2}{\text{d}x^2}f(x)+U(x)f(x)=Ef(x),$$
I need a $U(x)$ satisfying the following:
The Schrödinger equation with it must be solvable purely analytically,
without need for any numerics (but using special functions is acceptable)
$\displaystyle \lim_{x\to\infty} U(\pm x)=0$
$\exists a,b: U(x)<0\;\forall x\in[a,b]$
I.e. $U(x)$ should represent some potential well, which would have both
free and bound states.
Are there any such $U(x)$? If yes, what are examples?
Examples of what does not answer the question are:
finite square potential well, because to solve it one has to solve
transcendental equations, which need numerics
$\delta$-shaped potential well, since despite it can be solved
analytically for infinite space, it still results in transcendental
equation when $x\in[q,r]$
what is oriented watershed tranform ?
what is oriented watershed tranform ?
I read a paper "from contours to regions: an empirical evaluation". In it,
it mentions oriented watershed transform. However, I do not understand it.
Any one can help ?
I read a paper "from contours to regions: an empirical evaluation". In it,
it mentions oriented watershed transform. However, I do not understand it.
Any one can help ?
How to set up brush extent in d3 js while using time scale?
How to set up brush extent in d3 js while using time scale?
I have a problem with brushing using brush.extent([val1, val2])
Regarding documentation: https://github.com/mbostock/d3/wiki/SVG-Controls
when I set up brush.extent like this:
var xScale = d3.scale.linear()
.domain(data)
.range([0, 500]);
var brush = d3.svg.brush()
.x(xScale)
.on('brushstart', function() {
this.brushStart();
})
.on('brushend', function() {
this.brushEnd();
})
.extent([100, 300]);
It will display brushed area from 100 to 200 on xAxis (brush is visible
and on right position).
Unfortunately when I'm using d3.time.scale() it doesn't work at all:
var xScale = d3.time.scale()
.domain(data)
.range([0, 500]);
var brush = d3.svg.brush()
.x(xScale)
.on('brushstart', function() {
this.brushStart();
})
.on('brushend', function() {
this.brushEnd();
})
.extent([100, 300]);
// or
// .extent(['2013-08-01T00:00:00Z', '2013-08-10T23:59:59Z']);
// or
// .extent(['2013-08-01 00:00:00', '2013-08-10 23:59:59']);
// or even
// .extent([new Date(2013, 8, 1, 00, 00, 00), new Date(2013, 8, 10,
23, 59, 59)]);
It does not display brushed area.
How to set brushed area when I'm using d3.tim.scale()?
Of course data contain date ranges which can fit brushed are even with
margins.
Mariusz
I have a problem with brushing using brush.extent([val1, val2])
Regarding documentation: https://github.com/mbostock/d3/wiki/SVG-Controls
when I set up brush.extent like this:
var xScale = d3.scale.linear()
.domain(data)
.range([0, 500]);
var brush = d3.svg.brush()
.x(xScale)
.on('brushstart', function() {
this.brushStart();
})
.on('brushend', function() {
this.brushEnd();
})
.extent([100, 300]);
It will display brushed area from 100 to 200 on xAxis (brush is visible
and on right position).
Unfortunately when I'm using d3.time.scale() it doesn't work at all:
var xScale = d3.time.scale()
.domain(data)
.range([0, 500]);
var brush = d3.svg.brush()
.x(xScale)
.on('brushstart', function() {
this.brushStart();
})
.on('brushend', function() {
this.brushEnd();
})
.extent([100, 300]);
// or
// .extent(['2013-08-01T00:00:00Z', '2013-08-10T23:59:59Z']);
// or
// .extent(['2013-08-01 00:00:00', '2013-08-10 23:59:59']);
// or even
// .extent([new Date(2013, 8, 1, 00, 00, 00), new Date(2013, 8, 10,
23, 59, 59)]);
It does not display brushed area.
How to set brushed area when I'm using d3.tim.scale()?
Of course data contain date ranges which can fit brushed are even with
margins.
Mariusz
Can we install cracked softwares in a virtual box guest OS and keep the host OS intact?
Can we install cracked softwares in a virtual box guest OS and keep the
host OS intact?
I want to root my android phone but it seems the root tools often contain
virus/trojan.
I wonder if I would install and use those tools in a virtual guest OS
machine, e.g. VirtualBox from Oracle, and keep my PC the host OS machine
safe from virus?
host OS intact?
I want to root my android phone but it seems the root tools often contain
virus/trojan.
I wonder if I would install and use those tools in a virtual guest OS
machine, e.g. VirtualBox from Oracle, and keep my PC the host OS machine
safe from virus?
How to add a unique identifier or number to a google.maps.Geocode request (Google Maps API v3)
How to add a unique identifier or number to a google.maps.Geocode request
(Google Maps API v3)
I want to be able to determine when the final request from my array of
addresses has been processed so I can alert the user. Is there a way to
determine when the request from the last address in an array has been
processed? Can you attach an identifier to a request such that when it
returns a call back function can see it and let the user know?
Otherwise the user is going to be sitting there waiting for markers that
don't exist to appear. I've dealt with most of the issues arising from the
asynchronous nature of the technology, but this one has me a little
stumped and i haven't seen anything with the documentation.
(Google Maps API v3)
I want to be able to determine when the final request from my array of
addresses has been processed so I can alert the user. Is there a way to
determine when the request from the last address in an array has been
processed? Can you attach an identifier to a request such that when it
returns a call back function can see it and let the user know?
Otherwise the user is going to be sitting there waiting for markers that
don't exist to appear. I've dealt with most of the issues arising from the
asynchronous nature of the technology, but this one has me a little
stumped and i haven't seen anything with the documentation.
ShowDialog on top of another process?
ShowDialog on top of another process?
How is the following can be done? I tried using WinApi to attach a dialog
on top of "NotePad", but that failed. I want to be able to attach a login
form ON TOP of the notepad process (for example), making it unclickable
(like a showdialog) until loginform disappears. How can it be done in C#
winform? Thanks. I've searched the web and found nothing.
How is the following can be done? I tried using WinApi to attach a dialog
on top of "NotePad", but that failed. I want to be able to attach a login
form ON TOP of the notepad process (for example), making it unclickable
(like a showdialog) until loginform disappears. How can it be done in C#
winform? Thanks. I've searched the web and found nothing.
Friday, 16 August 2013
MVC4 calling Javascript function from View
MVC4 calling Javascript function from View
The code below works if you enter a city and state, then click outside of
the text box but NOT directly on the Search submit button. Clicking
outside of the text box triggers the onblur event which fires the
javascript code to run a bing maps geocode on the city and state and
populates the two hidden text boxes with the latitude and longitude. THEN
when you click the submit button the code passes the latitude and
longitude into the CityDistanceSort action on the Job controller which
sorts the cities in the database based on their distance from the latitude
and longitude passed in, then posts that sorted model to the view.
Everything works except that you need to be able to enter the City and
State and then of course just click the Submit button directly. But doing
so doesn't give the JS code time to geocode and causes an error: The
parameters dictionary contains a null entry for parameter 'SearchLatitude'
of non-nullable type 'System.Double...
@using(Html.BeginForm("CityDistanceSort", "Job"))
{
<input type="hidden" name="SearchLatitude" id="SearchLatitude">
<input type="hidden" name="SearchLongitude" id="SearchLongitude">
<input type="text" name="CityStateName" id="CityStateName"
placeholder="CITY, BY DISTANCE" onblur="GeocodeSearchCityState()">
<input type="submit" value="SEARCH" />
}
[HttpPost]
public ActionResult CityDistanceSort(double SearchLatitude, double
SearchLongitude)
{
var model = db.Jobs.ToList();
foreach (var item in model)
{ item.PickupDistanceSort =
ICN.CustomMethods.GetDistance(SearchLatitude, SearchLongitude,
item.PickupLatitude, item.PickupLongitude); }
return View("JobHeadings", model.OrderBy(s => s.PickupDistanceSort));
}
The code below works if you enter a city and state, then click outside of
the text box but NOT directly on the Search submit button. Clicking
outside of the text box triggers the onblur event which fires the
javascript code to run a bing maps geocode on the city and state and
populates the two hidden text boxes with the latitude and longitude. THEN
when you click the submit button the code passes the latitude and
longitude into the CityDistanceSort action on the Job controller which
sorts the cities in the database based on their distance from the latitude
and longitude passed in, then posts that sorted model to the view.
Everything works except that you need to be able to enter the City and
State and then of course just click the Submit button directly. But doing
so doesn't give the JS code time to geocode and causes an error: The
parameters dictionary contains a null entry for parameter 'SearchLatitude'
of non-nullable type 'System.Double...
@using(Html.BeginForm("CityDistanceSort", "Job"))
{
<input type="hidden" name="SearchLatitude" id="SearchLatitude">
<input type="hidden" name="SearchLongitude" id="SearchLongitude">
<input type="text" name="CityStateName" id="CityStateName"
placeholder="CITY, BY DISTANCE" onblur="GeocodeSearchCityState()">
<input type="submit" value="SEARCH" />
}
[HttpPost]
public ActionResult CityDistanceSort(double SearchLatitude, double
SearchLongitude)
{
var model = db.Jobs.ToList();
foreach (var item in model)
{ item.PickupDistanceSort =
ICN.CustomMethods.GetDistance(SearchLatitude, SearchLongitude,
item.PickupLatitude, item.PickupLongitude); }
return View("JobHeadings", model.OrderBy(s => s.PickupDistanceSort));
}
Saturday, 10 August 2013
Must return only a description but returns all the path json
Must return only a description but returns all the path json
Must return the description of each title I tried to create the path for
each one worked however returns all instead of each. Anyone know how to
do?
javascript
$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D'http%3A%2F%2Frss.cnn.com%2Fservices%2Fpodcasting%2Fac360%2Frss.xml'%20AND%20itemPath%3D%22%2F%2Fchannel%22&format=json&diagnostics=true&callback=?",
function (data) {
// Load Titles patch Json
console.log(data.query.results.channel.item);
var titles = data.query.results.channel.item.map(function (item) {
return item.title;
});
var urls = data.query.results.channel.item.map(function (item) {
return item.origLink;
});
var descri = data.query.results.channel.item.map(function (item) {
return item.description;
});
$(".description-podcast p").text(descri);
console.log(titles);
$(".container-list-podcast ul").append('<li>' +
titles.join('</li><li>'));
$(".container-list-podcast ul li").each(function (key, value) {
var text = $(this).text();
$(this).html('<a href="' + urls[key] + '">' + text + '</a>');
});
// Load Navigation Only Key
a = $('.nav_holder li a').keynav(function () {
return window.keyNavigationDisabled;
});
});
jsfiddle
Must return the description of each title I tried to create the path for
each one worked however returns all instead of each. Anyone know how to
do?
javascript
$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D'http%3A%2F%2Frss.cnn.com%2Fservices%2Fpodcasting%2Fac360%2Frss.xml'%20AND%20itemPath%3D%22%2F%2Fchannel%22&format=json&diagnostics=true&callback=?",
function (data) {
// Load Titles patch Json
console.log(data.query.results.channel.item);
var titles = data.query.results.channel.item.map(function (item) {
return item.title;
});
var urls = data.query.results.channel.item.map(function (item) {
return item.origLink;
});
var descri = data.query.results.channel.item.map(function (item) {
return item.description;
});
$(".description-podcast p").text(descri);
console.log(titles);
$(".container-list-podcast ul").append('<li>' +
titles.join('</li><li>'));
$(".container-list-podcast ul li").each(function (key, value) {
var text = $(this).text();
$(this).html('<a href="' + urls[key] + '">' + text + '</a>');
});
// Load Navigation Only Key
a = $('.nav_holder li a').keynav(function () {
return window.keyNavigationDisabled;
});
});
jsfiddle
Subscribe to:
Comments (Atom)