In 2013 What Touch Screen Laptop Would You Buy?
Hardware changes so quickly. Most of the other questions like this are for
2010 or 2011.
What laptop would you buy if you wanted a flashy touch screen laptop
running Ubuntu?
Monday, 30 September 2013
If $g$ has finite order $n$ show that $n$ is the least number such that $g^n$ is the neutral element
If $g$ has finite order $n$ show that $n$ is the least number such that
$g^n$ is the neutral element
pThe order of the element $g$ is the size (cardinality) of the group
$\langle g \rangle$. If $g$ has finite order $n$ show that $n$ is the
least number such that $g^n$ is the neutral element./p
$g^n$ is the neutral element
pThe order of the element $g$ is the size (cardinality) of the group
$\langle g \rangle$. If $g$ has finite order $n$ show that $n$ is the
least number such that $g^n$ is the neutral element./p
How to drop a button over another in iOS
How to drop a button over another in iOS
I have two UIButtons in a ViewController. One of them is dragable using
UIPanGesture recogniser. I want to drop this dragable UIButton over a
fixed UIButton. How can I achieve this?
This is what I tried:
if (CGRectIntersectsRect(self.firstButton.frame, self.oneButton.frame))
{
[self.oneButton addSubview:self.firstButton]; //first button is the
dragable button.
}
However I figured just adding as subview won't work. What is the right way
to achieve this?
I have two UIButtons in a ViewController. One of them is dragable using
UIPanGesture recogniser. I want to drop this dragable UIButton over a
fixed UIButton. How can I achieve this?
This is what I tried:
if (CGRectIntersectsRect(self.firstButton.frame, self.oneButton.frame))
{
[self.oneButton addSubview:self.firstButton]; //first button is the
dragable button.
}
However I figured just adding as subview won't work. What is the right way
to achieve this?
Cannot add New Team Project in VS2010. Error TF249063
Cannot add New Team Project in VS2010. Error TF249063
Good day,
I am trying to create a new team project from VS2010. We do currently have
TFS projects on the server. However, once all the detail has been entered,
I get the follwoing error message:
The following Web service is not available:
http://{servername}/_vti_bin/TeamFoundationIntegrationService.asmx.
The web service does not exist on the server.
The folder 'C:\Program Files\Common Files\Microsoft Shared\Web Server
Extensions' does not exist for stsadm.exe.
Can anyone shed some light on the situation at hand?
Thanks.
Good day,
I am trying to create a new team project from VS2010. We do currently have
TFS projects on the server. However, once all the detail has been entered,
I get the follwoing error message:
The following Web service is not available:
http://{servername}/_vti_bin/TeamFoundationIntegrationService.asmx.
The web service does not exist on the server.
The folder 'C:\Program Files\Common Files\Microsoft Shared\Web Server
Extensions' does not exist for stsadm.exe.
Can anyone shed some light on the situation at hand?
Thanks.
Sunday, 29 September 2013
Boot Ubuntu after windows install?
Boot Ubuntu after windows install?
I know that after a windows installation,the MBR is changed to the windows
loader.How can I boot to Ubuntu 12.04 LTS after a windows installation?
I know that after a windows installation,the MBR is changed to the windows
loader.How can I boot to Ubuntu 12.04 LTS after a windows installation?
Trigger onblur event conditionally
Trigger onblur event conditionally
I need to be able to control when the blur event is actually triggered.
<div class="selectedcomp"></div>
<input type="text" class="textbox" maxlength="50" id="searchfavs" />
<div id="globalcompanyresultscontainer">
<div id="globalcompanyresults">
</div>
</div>
When a user is typing a query in #searchfavs I'm loading the results into
#globalcompanyresults. When a user clicks a loaded result I copy the HTML
of that result into another element:
$('#globalcompanyresults').on('click', 'div.company-card img', function () {
$('#globalcompanyresults').html('');
$('.selectedcomp').html($(this).parent()[0].outerHTML);
});
As soon as the user clicks outside the #searchfavs element or presses the
tab key, also causing #searchfavs to loose focus, I want to clear all
results, simply by calling this:
$("#searchfavs").blur(function () {
$('#globalcompanyresults').html('');
});
However, this function is also called as soon as the user clicks a result
in #globalcompanyresults, the blur event is thrown, causing
#globalcompanyresults to be empty and I cannot access the clicked result
HTML anymore.
onblur, may NOT be triggered if a result in #globalcompanyresults is
clicked, by a click elsewhere or by pressing the tab key it's all good.
I need to be able to control when the blur event is actually triggered.
<div class="selectedcomp"></div>
<input type="text" class="textbox" maxlength="50" id="searchfavs" />
<div id="globalcompanyresultscontainer">
<div id="globalcompanyresults">
</div>
</div>
When a user is typing a query in #searchfavs I'm loading the results into
#globalcompanyresults. When a user clicks a loaded result I copy the HTML
of that result into another element:
$('#globalcompanyresults').on('click', 'div.company-card img', function () {
$('#globalcompanyresults').html('');
$('.selectedcomp').html($(this).parent()[0].outerHTML);
});
As soon as the user clicks outside the #searchfavs element or presses the
tab key, also causing #searchfavs to loose focus, I want to clear all
results, simply by calling this:
$("#searchfavs").blur(function () {
$('#globalcompanyresults').html('');
});
However, this function is also called as soon as the user clicks a result
in #globalcompanyresults, the blur event is thrown, causing
#globalcompanyresults to be empty and I cannot access the clicked result
HTML anymore.
onblur, may NOT be triggered if a result in #globalcompanyresults is
clicked, by a click elsewhere or by pressing the tab key it's all good.
AllowAnonymousAttribute does not work with content
AllowAnonymousAttribute does not work with content
I have an action in a controller marked with the attribute
[AllowAnonymous] that return a ContentResult. When I call that action, MVC
redirects me to the login page. If I call another action that return a
ViewResult (on the same controller), I receive the page and I'm not being
redirected to the login page (expected behavior).
Here is the action that unexpectly redirects me to the login page:
public ActionResult AngularConfig(int pid, int uid)
{
const string scriptPath = "~/Scripts/config.js";
string config = System.IO.File.ReadAllText(Server.MapPath(scriptPath));
Uri baseUri = Request.Url ?? new
Uri(String.Format("http{0}://www.domain.com/",
Request.IsSecureConnection ? "s" : ""));
config = config.Replace("{{API_KEY}}", Config.ApiKey)
.Replace("{{RECEIVER_PATH}}", new Uri(baseUri,
"/AppReceiver.html").ToString())
.Replace("{{PAGE_SIZE}}",
Config.PageSize.ToString(CultureInfo.InvariantCulture));
return Content(config);
}
I also tried to return a FileResult but the behavior is the exactly the
same. Here is another action that returns a ViewResult without redirecting
me to the login page:
public ActionResult Stream()
{
return View();
}
Is anyone else had this problem already?
I have an action in a controller marked with the attribute
[AllowAnonymous] that return a ContentResult. When I call that action, MVC
redirects me to the login page. If I call another action that return a
ViewResult (on the same controller), I receive the page and I'm not being
redirected to the login page (expected behavior).
Here is the action that unexpectly redirects me to the login page:
public ActionResult AngularConfig(int pid, int uid)
{
const string scriptPath = "~/Scripts/config.js";
string config = System.IO.File.ReadAllText(Server.MapPath(scriptPath));
Uri baseUri = Request.Url ?? new
Uri(String.Format("http{0}://www.domain.com/",
Request.IsSecureConnection ? "s" : ""));
config = config.Replace("{{API_KEY}}", Config.ApiKey)
.Replace("{{RECEIVER_PATH}}", new Uri(baseUri,
"/AppReceiver.html").ToString())
.Replace("{{PAGE_SIZE}}",
Config.PageSize.ToString(CultureInfo.InvariantCulture));
return Content(config);
}
I also tried to return a FileResult but the behavior is the exactly the
same. Here is another action that returns a ViewResult without redirecting
me to the login page:
public ActionResult Stream()
{
return View();
}
Is anyone else had this problem already?
How can I create a BufferedImage animation with a direct ColorModel? My attempts simply are not working
How can I create a BufferedImage animation with a direct ColorModel? My
attempts simply are not working
I've been trying for ages to create a BufferedImage animation with a
direct ColorModel using WritableRaster, but I simply can't get the
BufferedImage to update! I've been able to get it to work using an indexed
ColorModel, but I just can't get it to work using a direct ColorModel! Can
someone please point me to where I can see an example of this being
achieved, please.
attempts simply are not working
I've been trying for ages to create a BufferedImage animation with a
direct ColorModel using WritableRaster, but I simply can't get the
BufferedImage to update! I've been able to get it to work using an indexed
ColorModel, but I just can't get it to work using a direct ColorModel! Can
someone please point me to where I can see an example of this being
achieved, please.
Saturday, 28 September 2013
Changing the C code for desired Output
Changing the C code for desired Output
I have came across this interview question. I know it's tricky but can't
think of any approach.
Change the program so that the output of printf is always 20. Only foo()
can be changed. main() function can not be changed.
void foo()
{
// Add Here
}
int main()
{
int i = 20;
foo();
i = 100;
printf("%d", i);
//Some other computation. Doesn't have any printf statements.
return 0;
}
I have came across this interview question. I know it's tricky but can't
think of any approach.
Change the program so that the output of printf is always 20. Only foo()
can be changed. main() function can not be changed.
void foo()
{
// Add Here
}
int main()
{
int i = 20;
foo();
i = 100;
printf("%d", i);
//Some other computation. Doesn't have any printf statements.
return 0;
}
Vector of vectors , Separating different values from array
Vector of vectors , Separating different values from array
I need to separate values from an 2d array. All i need to do is to store
all indexes of fields with certain values.
For example i may have an array which has 3 cells with value 1 and 10
fields with value 2. I tried to create 1 vector which stores all indexes
for value 1 and the other one that stores all indexes for value 2 .
here's a code I've been trying to write , but it doesnt seem to wrok
void searchForGrains(Cell **tab, int _size){
storage.push_back(tab[0][0]);
Point p(0,0); // Point refers to array indexes
storage[0].points.push_back(p);
for(int i=0 ; i<_size ; ++i){
for(int j=0 ; j<_size ; ++j){
int counter = 0;
for(unsigned int k=0 ; k<storage.size() ; k++){
if(tab[i][j].value == storage[k].value){
Point pp(i,j);
storage[k].points.push_back(pp);
}
else
counter++;
}
if(counter == storage.size())
storage.push_back(tab[i][j]);
}
}
}
I need to separate values from an 2d array. All i need to do is to store
all indexes of fields with certain values.
For example i may have an array which has 3 cells with value 1 and 10
fields with value 2. I tried to create 1 vector which stores all indexes
for value 1 and the other one that stores all indexes for value 2 .
here's a code I've been trying to write , but it doesnt seem to wrok
void searchForGrains(Cell **tab, int _size){
storage.push_back(tab[0][0]);
Point p(0,0); // Point refers to array indexes
storage[0].points.push_back(p);
for(int i=0 ; i<_size ; ++i){
for(int j=0 ; j<_size ; ++j){
int counter = 0;
for(unsigned int k=0 ; k<storage.size() ; k++){
if(tab[i][j].value == storage[k].value){
Point pp(i,j);
storage[k].points.push_back(pp);
}
else
counter++;
}
if(counter == storage.size())
storage.push_back(tab[i][j]);
}
}
}
Why Memory Engine is much larger than InnoDB engine store?
Why Memory Engine is much larger than InnoDB engine store?
I have a table stored about 100,000 rows data in InnoDB engine. I just
copy the data to a memory engine table, but I find that the size of the
new one is much large than orignal table. Why?
| Rows | Engine | Size |
| 96702 | Memory|741MB|
|96952|InnoDB|28MB|
WHY?
I have a table stored about 100,000 rows data in InnoDB engine. I just
copy the data to a memory engine table, but I find that the size of the
new one is much large than orignal table. Why?
| Rows | Engine | Size |
| 96702 | Memory|741MB|
|96952|InnoDB|28MB|
WHY?
regex to get strings before and after the colon
regex to get strings before and after the colon
I am having string like following
olah billo:78517700-1f01-11e3-a6b7-3c970e02b4ec, jiglo
piglo:68517700-1f01-11e3-a6b7-3c970e02b4ec, nimho
james:98517700-1f01-11e3-a6b7-3c970e02b4ec, kathy
ruck:38517700-1f01-11e3-a6b7-3c970e02b4ec
I want to have a regex to get the string before and after colon in a Map
with key the string after colon. I want to know what is the most efficient
way.
I am having string like following
olah billo:78517700-1f01-11e3-a6b7-3c970e02b4ec, jiglo
piglo:68517700-1f01-11e3-a6b7-3c970e02b4ec, nimho
james:98517700-1f01-11e3-a6b7-3c970e02b4ec, kathy
ruck:38517700-1f01-11e3-a6b7-3c970e02b4ec
I want to have a regex to get the string before and after colon in a Map
with key the string after colon. I want to know what is the most efficient
way.
Friday, 27 September 2013
SQL SUM not SUM all column but show all data
SQL SUM not SUM all column but show all data
How to SUM all of my column in my table with database oracle ? The SQL
code like this :
SELECT DISTINCT
M.MODEL_NO,
P.FORM_NO,
P.MODEL_NO,
TO_CHAR(TO_DATE(P.DATE_ADDED,'YYYY-MM-DD'),'MONTH'),
Q.FORM_NO,
Q.STATUS_QTY,
SUM(Q.QTY) OVER (PARTITION BY P.FORM_NO ORDER BY P.FORM_NO
RANGE UNBOUNDED PRECEDING) QTY
FROM
SEIAPPS_MODEL M, SEIAPPS_PRODUCTION_STATUS P, SEIAPPS_QTY Q
WHERE
P.FORM_NO = Q.FORM_NO AND P.MODEL_NO = M.MODEL_NO AND M.MODEL_NO = '15'
AND P.DATE_ADDED LIKE '2013-05%' AND Q.STATUS_QTY = 'OK';
When I query this SQL code in TOAD, it will show all data, not SUM for all.
What I wanted is like this :
SUM_ALL
5000 (example value)
Please advice. Thanks
How to SUM all of my column in my table with database oracle ? The SQL
code like this :
SELECT DISTINCT
M.MODEL_NO,
P.FORM_NO,
P.MODEL_NO,
TO_CHAR(TO_DATE(P.DATE_ADDED,'YYYY-MM-DD'),'MONTH'),
Q.FORM_NO,
Q.STATUS_QTY,
SUM(Q.QTY) OVER (PARTITION BY P.FORM_NO ORDER BY P.FORM_NO
RANGE UNBOUNDED PRECEDING) QTY
FROM
SEIAPPS_MODEL M, SEIAPPS_PRODUCTION_STATUS P, SEIAPPS_QTY Q
WHERE
P.FORM_NO = Q.FORM_NO AND P.MODEL_NO = M.MODEL_NO AND M.MODEL_NO = '15'
AND P.DATE_ADDED LIKE '2013-05%' AND Q.STATUS_QTY = 'OK';
When I query this SQL code in TOAD, it will show all data, not SUM for all.
What I wanted is like this :
SUM_ALL
5000 (example value)
Please advice. Thanks
How to import data into postgres
How to import data into postgres
I have data in the below mentioned format:
<a> <b> <c>> NULL NULL
<d> <e> <f<> '1999-10-10', '2000-10-10'
<g<> <h> <i>> '300-12-12 BC', '300-01-01 BC'
<m> <l> <k<,>j> NULL NULL
<g> <k> "o,l" NULL NULL
Here a,b,c,d,e,f,g,h,i,j,k,l,m may contain any character e.g. they may
contain charaters like ',/,$,#,*,&,^,%,;,:,},{,],[, space,>,< etc
I tried to import this data into postgres using commas to separate the
four columns (by creating .csv file). However, this approach is incorrect
as
third column contains the value (<k<,>j>) and "o,'" with a comma.
The patterns which exists in my data is the 1st and 2nd column contain
data within angular brackets (<>). The third column contains data either
within quotes or within angular brackets. The fourth and fifth column
contain either NULL or dates.
Is there some way by which I may import this data into postgres
efficiently as I have about 3 Tera Byte of data. I am a complete novice at
postgres so please help
I have data in the below mentioned format:
<a> <b> <c>> NULL NULL
<d> <e> <f<> '1999-10-10', '2000-10-10'
<g<> <h> <i>> '300-12-12 BC', '300-01-01 BC'
<m> <l> <k<,>j> NULL NULL
<g> <k> "o,l" NULL NULL
Here a,b,c,d,e,f,g,h,i,j,k,l,m may contain any character e.g. they may
contain charaters like ',/,$,#,*,&,^,%,;,:,},{,],[, space,>,< etc
I tried to import this data into postgres using commas to separate the
four columns (by creating .csv file). However, this approach is incorrect
as
third column contains the value (<k<,>j>) and "o,'" with a comma.
The patterns which exists in my data is the 1st and 2nd column contain
data within angular brackets (<>). The third column contains data either
within quotes or within angular brackets. The fourth and fifth column
contain either NULL or dates.
Is there some way by which I may import this data into postgres
efficiently as I have about 3 Tera Byte of data. I am a complete novice at
postgres so please help
ORA-00907: missing right parenthesis on specifying 'ON UPDATE TIMESTAMP'
ORA-00907: missing right parenthesis on specifying 'ON UPDATE TIMESTAMP'
I need to have two columns - created_date and updated_date for every table
in the DB. I am trying the following SQL in Oracle, but its not working:
create table tmptmp (
id number(10),
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE TIMESTAMP
);
The above gives the following error:
Error at Command Line:5 Column:42
Error report:
SQL Error: ORA-00907: missing right parenthesis
00907. 00000 - "missing right parenthesis"
*Cause:
*Action:
Any clue what is wrong here?
I need to have two columns - created_date and updated_date for every table
in the DB. I am trying the following SQL in Oracle, but its not working:
create table tmptmp (
id number(10),
created TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
updated TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE TIMESTAMP
);
The above gives the following error:
Error at Command Line:5 Column:42
Error report:
SQL Error: ORA-00907: missing right parenthesis
00907. 00000 - "missing right parenthesis"
*Cause:
*Action:
Any clue what is wrong here?
Can you run Ant on a buildfile that is located inside a jar?
Can you run Ant on a buildfile that is located inside a jar?
I am wondering if you can run Ant on a buildfile that would be located
inside a JAR. The reason why I am interested in this is because I would
like to include a "deploy" target in my buildfile that could be called
after the jar has been moved to its destination. That "deploy" target
would take care of extracting resources and other libraries required to
run the program.
So, for instance, I would package up properties, images and external jars
inside of my jar when building. The deployment process would then consist
of moving the jar to the location it is meant to run in, and call ant
myjar.jar/build.xml deploy or something like that.
Does that make sense?
I am wondering if you can run Ant on a buildfile that would be located
inside a JAR. The reason why I am interested in this is because I would
like to include a "deploy" target in my buildfile that could be called
after the jar has been moved to its destination. That "deploy" target
would take care of extracting resources and other libraries required to
run the program.
So, for instance, I would package up properties, images and external jars
inside of my jar when building. The deployment process would then consist
of moving the jar to the location it is meant to run in, and call ant
myjar.jar/build.xml deploy or something like that.
Does that make sense?
Placing default components in an iParsys
Placing default components in an iParsys
We have a default set of header and footer components that we want to
display on every page.
In my template files, I have lines like the following to include
components automatically:
<cq:include path="thecomponent" resourceType="/path/to/component" />
However, the options for the components are not inherited down to child
pages, so our users would need to rebuild their headers and footers every
time they make a new page. In my template file, is there a way to place
these components in an iParsys automatically?
This attempt was not successful, but I think it illustrates what I want to
do:
<cq:include path="PageTop"
resourceType="/libs/foundation/components/iparsys">
<cq:include path="thecomponent" resourceType="/path/to/component" />
<cq:include path="theOthercomponent"
resourceType="/path/to/other/component" />
</cq:include>
We have a default set of header and footer components that we want to
display on every page.
In my template files, I have lines like the following to include
components automatically:
<cq:include path="thecomponent" resourceType="/path/to/component" />
However, the options for the components are not inherited down to child
pages, so our users would need to rebuild their headers and footers every
time they make a new page. In my template file, is there a way to place
these components in an iParsys automatically?
This attempt was not successful, but I think it illustrates what I want to
do:
<cq:include path="PageTop"
resourceType="/libs/foundation/components/iparsys">
<cq:include path="thecomponent" resourceType="/path/to/component" />
<cq:include path="theOthercomponent"
resourceType="/path/to/other/component" />
</cq:include>
SSIS - check if row exists before importing from source to destination
SSIS - check if row exists before importing from source to destination
Can someone please advise:
I have got SOURCE (which is OLD SQL Server) and we need to move data to
new DESTINATION (which is NEW SERVER). So moving data between different
instances.
I'm struggling how to write the package which looks up in destination
first and check if row exists then do nothing else INSERT.
Regards
Can someone please advise:
I have got SOURCE (which is OLD SQL Server) and we need to move data to
new DESTINATION (which is NEW SERVER). So moving data between different
instances.
I'm struggling how to write the package which looks up in destination
first and check if row exists then do nothing else INSERT.
Regards
Thursday, 26 September 2013
Which technology is better extjs or dojo?
Which technology is better extjs or dojo?
I want to implement Grid which loads a very huge amount of data,
performing search in grid contents, pagination. The data to grid from
serverside.And I want to add rows to grid, delete rows and update the
inserted rows in database. I want to know which is better technology to
implement grid with the above requirements. Please help me.
I want to implement Grid which loads a very huge amount of data,
performing search in grid contents, pagination. The data to grid from
serverside.And I want to add rows to grid, delete rows and update the
inserted rows in database. I want to know which is better technology to
implement grid with the above requirements. Please help me.
Wednesday, 25 September 2013
Issue with else statement
Issue with else statement
I have the code below to retrieve row from the database, but if I enter id
that doesn't exist in the database in 'assign_id_input', it won't execute
the else statement and display out 'Error'.
$assign_id_input = $_POST['assign_id_input'];
$search_assign_user_id = mysql_query("SELECT * FROM free_ebook WHERE useid
= $assign_id_input;")or die(mysql_error());
while($assign_user_id_array = mysql_fetch_array($search_assign_user_id,
MYSQL_ASSOC)) {
$filtered_assign_user_id_array = array_filter($assign_user_id_array);
if(count($filtered_assign_user_id_array) > 0) {
echo 'No Error';
}
else{
echo 'Error';
}
}
I have the code below to retrieve row from the database, but if I enter id
that doesn't exist in the database in 'assign_id_input', it won't execute
the else statement and display out 'Error'.
$assign_id_input = $_POST['assign_id_input'];
$search_assign_user_id = mysql_query("SELECT * FROM free_ebook WHERE useid
= $assign_id_input;")or die(mysql_error());
while($assign_user_id_array = mysql_fetch_array($search_assign_user_id,
MYSQL_ASSOC)) {
$filtered_assign_user_id_array = array_filter($assign_user_id_array);
if(count($filtered_assign_user_id_array) > 0) {
echo 'No Error';
}
else{
echo 'Error';
}
}
Thursday, 19 September 2013
An web application to Update an one field (say id number) in the pdf each time when the user download the pdf form
An web application to Update an one field (say id number) in the pdf each
time when the user download the pdf form
I wanted to create an web application which allows the users to download
the pdf file with the with the value to the one of the field..and
incrementing this number for each download and i wanted to even to store
that number to the database.
Any idea how to start with?
time when the user download the pdf form
I wanted to create an web application which allows the users to download
the pdf file with the with the value to the one of the field..and
incrementing this number for each download and i wanted to even to store
that number to the database.
Any idea how to start with?
which one have I to choose between "union" and "case"?
which one have I to choose between "union" and "case"?
I have a list of tables (i.e. productsA, productsB, productsN, ...) each
product in these tables may have a comment (stored in the comments table),
if I hed to select top 10 ordered comments wich of these is the best
solution to be adopted (in terms of performances and speed)?
using UNION:
http://www.sqlfiddle.com/#!3/bc382/1
select TOP 10 comment_product, product_name, comment_date FROM (
select comment_product, product_name, comment_date from comments inner
join productsA on product_id = id_product WHERE product_type = 'A'
UNION
select comment_product, product_name, comment_date from comments inner
join productsB on product_id = id_product WHERE product_type = 'B'
UNION
select comment_product, product_name, comment_date from comments inner
join productsC on product_id = id_product WHERE product_type = 'C'
) as temp ORDER BY comment_date DESC
using CASE:
http://www.sqlfiddle.com/#!3/bc382/2
select TOP 10 comment_product, comment_date,
CASE product_type
when 'A' then (select product_name from productsA as sub where
sub.id_product = com.product_id)
when 'B' then (select product_name from productsB as sub where
sub.id_product = com.product_id)
when 'C' then (select product_name from productsC as sub where
sub.id_product = com.product_id)
END
FROM comments as com
ORDER BY comment_date DESC
I have a list of tables (i.e. productsA, productsB, productsN, ...) each
product in these tables may have a comment (stored in the comments table),
if I hed to select top 10 ordered comments wich of these is the best
solution to be adopted (in terms of performances and speed)?
using UNION:
http://www.sqlfiddle.com/#!3/bc382/1
select TOP 10 comment_product, product_name, comment_date FROM (
select comment_product, product_name, comment_date from comments inner
join productsA on product_id = id_product WHERE product_type = 'A'
UNION
select comment_product, product_name, comment_date from comments inner
join productsB on product_id = id_product WHERE product_type = 'B'
UNION
select comment_product, product_name, comment_date from comments inner
join productsC on product_id = id_product WHERE product_type = 'C'
) as temp ORDER BY comment_date DESC
using CASE:
http://www.sqlfiddle.com/#!3/bc382/2
select TOP 10 comment_product, comment_date,
CASE product_type
when 'A' then (select product_name from productsA as sub where
sub.id_product = com.product_id)
when 'B' then (select product_name from productsB as sub where
sub.id_product = com.product_id)
when 'C' then (select product_name from productsC as sub where
sub.id_product = com.product_id)
END
FROM comments as com
ORDER BY comment_date DESC
Bash Script won't generate ssh key correctly
Bash Script won't generate ssh key correctly
I am writing a script that others can use to set up git on a Linux system
and I am trying to generate an ssh key, have them upload it to git, and
then check to see if the key works. I am just beginning this script so it
is still a little messy, but how can I get this part to work?
echo "what is your github email address"
read email
ssh-keygen -C $email
echo "your code is:"
cat ~/.ssh/id_rsa.pub
echo "Press enter when code is pasted to github"
read -s continue
ssh -T git@github.com
I am writing a script that others can use to set up git on a Linux system
and I am trying to generate an ssh key, have them upload it to git, and
then check to see if the key works. I am just beginning this script so it
is still a little messy, but how can I get this part to work?
echo "what is your github email address"
read email
ssh-keygen -C $email
echo "your code is:"
cat ~/.ssh/id_rsa.pub
echo "Press enter when code is pasted to github"
read -s continue
ssh -T git@github.com
CSS Stylesheet linking wrong in Wordpress across entire site
CSS Stylesheet linking wrong in Wordpress across entire site
Ok, I have a feeling I've really done it this time. I've developed a
Wordpress site locally and then transferred it to my remote server. I did
a search and replace on the database using the script.
Now, I go into my site on the remote server and the HTML is good, but the
CSS stylesheet is not linking properly.
Here is how it appears when I view source:
<link rel="stylesheet" type="text/css" media="all"
href="www.fairchildwebsolutions.com/jesusandg/wp-content/themes/Sky/style.css"
/>
Now when I click on the link in source, I am directed to this:
www.fairchildwebsolutions.com/jesusandg/www.fairchildwebsolutions.com/jesusandg/wp-content/themes/Sky/style.css
Obviously, one too many domain names in there, so the file cannot be
found. My question now is, how do I go back and do a search and replace on
this to remove the extra domain without messing things up even worse?
Ok, I have a feeling I've really done it this time. I've developed a
Wordpress site locally and then transferred it to my remote server. I did
a search and replace on the database using the script.
Now, I go into my site on the remote server and the HTML is good, but the
CSS stylesheet is not linking properly.
Here is how it appears when I view source:
<link rel="stylesheet" type="text/css" media="all"
href="www.fairchildwebsolutions.com/jesusandg/wp-content/themes/Sky/style.css"
/>
Now when I click on the link in source, I am directed to this:
www.fairchildwebsolutions.com/jesusandg/www.fairchildwebsolutions.com/jesusandg/wp-content/themes/Sky/style.css
Obviously, one too many domain names in there, so the file cannot be
found. My question now is, how do I go back and do a search and replace on
this to remove the extra domain without messing things up even worse?
boa constructor frame not launching
boa constructor frame not launching
This is my first application in Boa Constructor and my first time using
wxPython.
#Boa:Frame:Frame1
import wx
choiceList = ['DAR', 'Impex', 'Endon', 'Astro', 'Ansell', 'Other']
def create(parent):
return Frame1(parent)
[wxID_FRAME1, wxID_FRAME1BUTTONSELECTDIR, wxID_FRAME1BUTTONSELECTFILE,
wxID_FRAME1CHOICESUPPLIER,
] = [wx.NewId() for _init_ctrls in range(4)]
class Frame1(wx.Frame):
def _init_ctrls(self, prnt):
# generated method, don't edit
wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
pos=wx.Point(517, 20), size=wx.Size(400, 492),
style=wx.DEFAULT_FRAME_STYLE, title='Frame1')
self.SetClientSize(wx.Size(392, 458))
self.choiceSupplier = wx.Choice(choices=choiceList,
id=wxID_FRAME1CHOICESUPPLIER,
name=u'choiceSupplier', parent=self, pos=wx.Point(48, 176),
size=wx.Size(120, 21), style=0)
self.choiceSupplier.Bind(wx.EVT_CHOICE, self.OnChoiceSupplierChoice,
id=wxID_FRAME1CHOICESUPPLIER)
def __init__(self, parent):
self._init_ctrls(parent)
def OnChoiceSupplierChoice(self, event):
supplier = choiceList[self.choiceSupplier.GetSelection()]
print supplier
My code runs fine when I click run application. However when I try to edit
it in designer I get an error:
16:17:06: Traceback (most recent call last):
16:17:06: File
"C:\Python27\Lib\site-packages\boa-constructor\Models\wxPythonControllers.py",
line 78, in OnDesigner self.showDesigner()
16:17:06: File
"C:\Python27\Lib\site-packages\boa-constructor\Models\wxPythonControllers.py",
line 143, in showDesigner designer.refreshCtrl()
16:17:06: File
"C:\Python27\Lib\site-packages\boa-constructor\Views\Designer.py", line
399, in refreshCtrl self.initObjectsAndCompanions(objCol.creators[1:],
objCol, deps, depLnks)
16:17:06: File
"C:\Python27\Lib\site-packages\boa-constructor\Views\InspectableViews.py",
line 127, in initObjectsAndCompanions self.initObjCreator(constr)
16:17:06: File
"C:\Python27\Lib\site-packages\boa-constructor\Views\Designer.py", line
529, in initObjCreator InspectableObjectView.initObjCreator(self,
constrPrs)
16:17:06: File
"C:\Python27\Lib\site-packages\boa-constructor\Views\InspectableViews.py",
line 155, in initObjCreator constrPrs.comp_name, constrPrs.params)
16:17:06: File
"C:\Python27\Lib\site-packages\boa-constructor\Views\Designer.py", line
483, in loadControl compClass=CtrlCompanion,
evalDct=self.model.specialAttrs)
16:17:06: File
"C:\Python27\Lib\site-packages\boa-constructor\Views\Designer.py", line
62, in setupArgs args = InspectableObjectView.setupArgs(self,
ctrlName, params, dontEval, evalDct=evalDct)
16:17:06: File "C:\Python27\Lib\site-packages\boa-constructor\View
\InspectableViews.py", line 63, in setupArgs evalDct)
16:17:06: File
"C:\Python27\Lib\site-packages\boa-constructor\PaletteMapping.py", line
158, in evalCtrl return eval(expr, globals(), localsDct)
16:17:06: File "<string>", line 1, in <module>
16:17:06: NameError: name 'choiceList' is not defined
This is my first application in Boa Constructor and my first time using
wxPython.
#Boa:Frame:Frame1
import wx
choiceList = ['DAR', 'Impex', 'Endon', 'Astro', 'Ansell', 'Other']
def create(parent):
return Frame1(parent)
[wxID_FRAME1, wxID_FRAME1BUTTONSELECTDIR, wxID_FRAME1BUTTONSELECTFILE,
wxID_FRAME1CHOICESUPPLIER,
] = [wx.NewId() for _init_ctrls in range(4)]
class Frame1(wx.Frame):
def _init_ctrls(self, prnt):
# generated method, don't edit
wx.Frame.__init__(self, id=wxID_FRAME1, name='', parent=prnt,
pos=wx.Point(517, 20), size=wx.Size(400, 492),
style=wx.DEFAULT_FRAME_STYLE, title='Frame1')
self.SetClientSize(wx.Size(392, 458))
self.choiceSupplier = wx.Choice(choices=choiceList,
id=wxID_FRAME1CHOICESUPPLIER,
name=u'choiceSupplier', parent=self, pos=wx.Point(48, 176),
size=wx.Size(120, 21), style=0)
self.choiceSupplier.Bind(wx.EVT_CHOICE, self.OnChoiceSupplierChoice,
id=wxID_FRAME1CHOICESUPPLIER)
def __init__(self, parent):
self._init_ctrls(parent)
def OnChoiceSupplierChoice(self, event):
supplier = choiceList[self.choiceSupplier.GetSelection()]
print supplier
My code runs fine when I click run application. However when I try to edit
it in designer I get an error:
16:17:06: Traceback (most recent call last):
16:17:06: File
"C:\Python27\Lib\site-packages\boa-constructor\Models\wxPythonControllers.py",
line 78, in OnDesigner self.showDesigner()
16:17:06: File
"C:\Python27\Lib\site-packages\boa-constructor\Models\wxPythonControllers.py",
line 143, in showDesigner designer.refreshCtrl()
16:17:06: File
"C:\Python27\Lib\site-packages\boa-constructor\Views\Designer.py", line
399, in refreshCtrl self.initObjectsAndCompanions(objCol.creators[1:],
objCol, deps, depLnks)
16:17:06: File
"C:\Python27\Lib\site-packages\boa-constructor\Views\InspectableViews.py",
line 127, in initObjectsAndCompanions self.initObjCreator(constr)
16:17:06: File
"C:\Python27\Lib\site-packages\boa-constructor\Views\Designer.py", line
529, in initObjCreator InspectableObjectView.initObjCreator(self,
constrPrs)
16:17:06: File
"C:\Python27\Lib\site-packages\boa-constructor\Views\InspectableViews.py",
line 155, in initObjCreator constrPrs.comp_name, constrPrs.params)
16:17:06: File
"C:\Python27\Lib\site-packages\boa-constructor\Views\Designer.py", line
483, in loadControl compClass=CtrlCompanion,
evalDct=self.model.specialAttrs)
16:17:06: File
"C:\Python27\Lib\site-packages\boa-constructor\Views\Designer.py", line
62, in setupArgs args = InspectableObjectView.setupArgs(self,
ctrlName, params, dontEval, evalDct=evalDct)
16:17:06: File "C:\Python27\Lib\site-packages\boa-constructor\View
\InspectableViews.py", line 63, in setupArgs evalDct)
16:17:06: File
"C:\Python27\Lib\site-packages\boa-constructor\PaletteMapping.py", line
158, in evalCtrl return eval(expr, globals(), localsDct)
16:17:06: File "<string>", line 1, in <module>
16:17:06: NameError: name 'choiceList' is not defined
How to run javascript function in "background" / without freezing UI
How to run javascript function in "background" / without freezing UI
I've done an html form which has alot of questions (coming from a
database) in many different tabs. User then gives answers in those
questions. Each time a user changes a tab my javascript creates a save.
The problem is that I have to loop through all questions each time the tab
is changed and it freezes the form for about 5 seconds every time.
I've been searching for an answer how I can run my save function in
background. Apparently there is no real way to run something on background
and many recommend using setTimeout(); For example this one How to get a
group of js function running in background
But none of these examples doesn't explain or take into consideration that
even if I use something like setTimeout(saveFunction, 2000); it doesn't
solve my problem. It only postpones it by 2 seconds in this case.
Is there a way to solve this problem? Thank you in advance.
I've done an html form which has alot of questions (coming from a
database) in many different tabs. User then gives answers in those
questions. Each time a user changes a tab my javascript creates a save.
The problem is that I have to loop through all questions each time the tab
is changed and it freezes the form for about 5 seconds every time.
I've been searching for an answer how I can run my save function in
background. Apparently there is no real way to run something on background
and many recommend using setTimeout(); For example this one How to get a
group of js function running in background
But none of these examples doesn't explain or take into consideration that
even if I use something like setTimeout(saveFunction, 2000); it doesn't
solve my problem. It only postpones it by 2 seconds in this case.
Is there a way to solve this problem? Thank you in advance.
AppGyver - phonegap remove loading transition screen
AppGyver - phonegap remove loading transition screen
Hello I'm creating a simple mobile app using Appgyver - steroids. I'm new
with this framework I'm trying to find a way to hide the loading screen
between different pages in both Android and iOS. I have read their
documentation but I can't make it work based on this:
http://docs.appgyver.com/en/edge/steroids_Steroids%20Native%20UI_steroids.layers_layers.push.md.html#steroids.layers.push
I careted and animation with keepLoading: false which didnt work
also after the view push I called:
steroids.view.removeLoading();
as mentioned here:
http://docs.appgyver.com/en/edge/steroids_Steroids%20Native%20UI_steroids.view_view.removeLoading.md.html#steroids.view.removeLoading
Nothing removed the black loading transition screen between pages. Could
someone please tell me what I'm doing wrong?
Hello I'm creating a simple mobile app using Appgyver - steroids. I'm new
with this framework I'm trying to find a way to hide the loading screen
between different pages in both Android and iOS. I have read their
documentation but I can't make it work based on this:
http://docs.appgyver.com/en/edge/steroids_Steroids%20Native%20UI_steroids.layers_layers.push.md.html#steroids.layers.push
I careted and animation with keepLoading: false which didnt work
also after the view push I called:
steroids.view.removeLoading();
as mentioned here:
http://docs.appgyver.com/en/edge/steroids_Steroids%20Native%20UI_steroids.view_view.removeLoading.md.html#steroids.view.removeLoading
Nothing removed the black loading transition screen between pages. Could
someone please tell me what I'm doing wrong?
Wednesday, 18 September 2013
In Common-Lisp, is it possible to expand a macro into several elements?
In Common-Lisp, is it possible to expand a macro into several elements?
I want a macro my-macro which can expand to 1 2 3 rather than (1 2 3), so
that
(list (my-macro) 4 5) -> (1 2 3 4 5)
Is this possible?
I want a macro my-macro which can expand to 1 2 3 rather than (1 2 3), so
that
(list (my-macro) 4 5) -> (1 2 3 4 5)
Is this possible?
Stylesheet to change elment's name
Stylesheet to change elment's name
I have the following XML
<ExternalAssessmentRequest>
<ApplicationData Lender="MegaBank">
<LiabilityList>
<RequestedLoans>
<Applicants Percentage="0.5" RelatedIdentifier="Applicant1"/>
<Applicants Percentage="0.5" RelatedIdentifier="Applicant2"/>
<Features Code="Test"/>
</RequestedLoans>
<ExistingLoans>
<Securities RelatedIdentifier="Test"/>
<Applicants Percentage="0.5" RelatedIdentifier="Applicant1"/>
<Applicants Percentage="0.5" RelatedIdentifier="Applicant2"/>
</ExistingLoans>
<OtherLiabilities >
<Applicants Percentage="0.5" RelatedIdentifier="Applicant1"/>
<Applicants Percentage="0.5" RelatedIdentifier="Applicant2"/>
</OtherLiabilities>
<Expenses Amount="50" Description="Train Ticket"
Identifier="Expense1" NonRecurring="Yes" Type="Transport"
Year="2013">
<Applicants Percentage="0.5" RelatedIdentifier="Applicant1"/>
<Applicants Percentage="0.5" RelatedIdentifier="Applicant2"/>
</Expenses>
</LiabilityList>
<AssetList>
<Assets >
<Applicants Percentage="0.5" RelatedIdentifier="Applicant1"/>
<Applicants Percentage="0.5" RelatedIdentifier="Applicant2"/>
</Assets>
<Funds Amount="1000" Description="Slush Fund"
Identifier="Fund1"/>
</AssetList>
<IncomeList>
<Incomes >
<Applicants Percentage="0.5" RelatedIdentifier="Applicant1"/>
<Applicants Percentage="0.5" RelatedIdentifier="Applicant2"/>
</Incomes>
</IncomeList>
<ApplicantList>
<Households AdditionalAdults="0" Boarding="Yes" Children="0"
Description="1 Test St, Sydney" Postcode="2000">
<Persons CountryOfResidence="Australia"
CustomerDurationInMonths="0" DischargedBankrupts="0"
Identifier="Applicant1" Name="John Smith"
Partner="Applicant2" Partnered="Yes"
PermanentResident="Yes"/>
<Persons CountryOfResidence="Australia"
CustomerDurationInMonths="0" DischargedBankrupts="0"
Identifier="Applicant2" Name="Jane Smith"
Partner="Applicant1" Partnered="Yes"
PermanentResident="Yes"/>
<Guarantors/>
</Households>
<Companies Identifier="Company1" Name="Tardis">
<Directors RelatedIdentifier="Applicant1"/>
</Companies>
</ApplicantList>
<FeeList>
<Fees Amount="100" Capitalised="Yes"
DateOfPayment="1967-08-13" Description="Application Fee"
Identifier="Fee1" PaidAmount="0"/>
</FeeList>
</ApplicationData>
<AdditionalAssessments Lender="MegaBank">
<RequestedLoans Product="Supa Variable" ProductID="Product2"/>
</AdditionalAssessments>
</ExternalAssessmentRequest>
I need a xsl style sheet to change all the element's names that are plural
to singular. For example RequestedLoans = RequestedLoan, Companies =
Company and so on.
Really appreciate your help if anyone can help me. Regards
I have the following XML
<ExternalAssessmentRequest>
<ApplicationData Lender="MegaBank">
<LiabilityList>
<RequestedLoans>
<Applicants Percentage="0.5" RelatedIdentifier="Applicant1"/>
<Applicants Percentage="0.5" RelatedIdentifier="Applicant2"/>
<Features Code="Test"/>
</RequestedLoans>
<ExistingLoans>
<Securities RelatedIdentifier="Test"/>
<Applicants Percentage="0.5" RelatedIdentifier="Applicant1"/>
<Applicants Percentage="0.5" RelatedIdentifier="Applicant2"/>
</ExistingLoans>
<OtherLiabilities >
<Applicants Percentage="0.5" RelatedIdentifier="Applicant1"/>
<Applicants Percentage="0.5" RelatedIdentifier="Applicant2"/>
</OtherLiabilities>
<Expenses Amount="50" Description="Train Ticket"
Identifier="Expense1" NonRecurring="Yes" Type="Transport"
Year="2013">
<Applicants Percentage="0.5" RelatedIdentifier="Applicant1"/>
<Applicants Percentage="0.5" RelatedIdentifier="Applicant2"/>
</Expenses>
</LiabilityList>
<AssetList>
<Assets >
<Applicants Percentage="0.5" RelatedIdentifier="Applicant1"/>
<Applicants Percentage="0.5" RelatedIdentifier="Applicant2"/>
</Assets>
<Funds Amount="1000" Description="Slush Fund"
Identifier="Fund1"/>
</AssetList>
<IncomeList>
<Incomes >
<Applicants Percentage="0.5" RelatedIdentifier="Applicant1"/>
<Applicants Percentage="0.5" RelatedIdentifier="Applicant2"/>
</Incomes>
</IncomeList>
<ApplicantList>
<Households AdditionalAdults="0" Boarding="Yes" Children="0"
Description="1 Test St, Sydney" Postcode="2000">
<Persons CountryOfResidence="Australia"
CustomerDurationInMonths="0" DischargedBankrupts="0"
Identifier="Applicant1" Name="John Smith"
Partner="Applicant2" Partnered="Yes"
PermanentResident="Yes"/>
<Persons CountryOfResidence="Australia"
CustomerDurationInMonths="0" DischargedBankrupts="0"
Identifier="Applicant2" Name="Jane Smith"
Partner="Applicant1" Partnered="Yes"
PermanentResident="Yes"/>
<Guarantors/>
</Households>
<Companies Identifier="Company1" Name="Tardis">
<Directors RelatedIdentifier="Applicant1"/>
</Companies>
</ApplicantList>
<FeeList>
<Fees Amount="100" Capitalised="Yes"
DateOfPayment="1967-08-13" Description="Application Fee"
Identifier="Fee1" PaidAmount="0"/>
</FeeList>
</ApplicationData>
<AdditionalAssessments Lender="MegaBank">
<RequestedLoans Product="Supa Variable" ProductID="Product2"/>
</AdditionalAssessments>
</ExternalAssessmentRequest>
I need a xsl style sheet to change all the element's names that are plural
to singular. For example RequestedLoans = RequestedLoan, Companies =
Company and so on.
Really appreciate your help if anyone can help me. Regards
SQL - Using sum but optionally using default value for row
SQL - Using sum but optionally using default value for row
Given tables
asset
col - id
date_sequence
col - date
daily_history
col - date
col - num_error_seconds
col - asset_id
historical_event
col - end_date
col - asset_id
I'm trying to count up all the daily num_error_seconds for all assets in a
given time range in order to display "Percentage NOT in error" by day. The
catch is if there is a historical_event involving an asset that has an
end_date beyond the sql query range, then daily_history should be ignored
and a default value of 86400 seconds (one day of error_seconds) should be
used for that asset
The query I have that does not use the historical_event is:
select ds.date,
IF(count(dh.time) = 0,
100,
100 - (100*sum(dh.num_error_seconds) / (86400 * count(*)))
) percent
from date_sequence ds
join asset a
left join daily_history dh on dh.date = ds.date and dh.asset_id=a.asset_id
where ds.date >= in_start_time and ds.date <= in_end_time
group by ds.thedate;
To build on this is beyond my SQL knowledge. Because of the aggregate
function, I cannot simply inject 86400 seconds for each asset that is
associated with an event that has an end_date beyond the in_end_time.
Can this be accomplished in one query? Or do I need to stage data with an
initial query?
Given tables
asset
col - id
date_sequence
col - date
daily_history
col - date
col - num_error_seconds
col - asset_id
historical_event
col - end_date
col - asset_id
I'm trying to count up all the daily num_error_seconds for all assets in a
given time range in order to display "Percentage NOT in error" by day. The
catch is if there is a historical_event involving an asset that has an
end_date beyond the sql query range, then daily_history should be ignored
and a default value of 86400 seconds (one day of error_seconds) should be
used for that asset
The query I have that does not use the historical_event is:
select ds.date,
IF(count(dh.time) = 0,
100,
100 - (100*sum(dh.num_error_seconds) / (86400 * count(*)))
) percent
from date_sequence ds
join asset a
left join daily_history dh on dh.date = ds.date and dh.asset_id=a.asset_id
where ds.date >= in_start_time and ds.date <= in_end_time
group by ds.thedate;
To build on this is beyond my SQL knowledge. Because of the aggregate
function, I cannot simply inject 86400 seconds for each asset that is
associated with an event that has an end_date beyond the in_end_time.
Can this be accomplished in one query? Or do I need to stage data with an
initial query?
How to add a delete/remove button per each option item in html select?
How to add a delete/remove button per each option item in html select?
I need create or use a library to create a custom html select to delete
each item in the html select. Something like this:
<select>
<option value="volvo">Volvo</option> <button>delete</button>
<option value="saab">Saab</option> <button>delete</button>
<option value="mercedes">Mercedes</option> <button>delete</button>
<option value="audi">Audi</option> <button>delete</button>
</select>
I have searched how to do this and for any library that might exist to do
this, but I haven't found anything. In IOS exists this but I need
something like that but for html.
I need create or use a library to create a custom html select to delete
each item in the html select. Something like this:
<select>
<option value="volvo">Volvo</option> <button>delete</button>
<option value="saab">Saab</option> <button>delete</button>
<option value="mercedes">Mercedes</option> <button>delete</button>
<option value="audi">Audi</option> <button>delete</button>
</select>
I have searched how to do this and for any library that might exist to do
this, but I haven't found anything. In IOS exists this but I need
something like that but for html.
Can someone implement a binary tree using a python list? [on hold]
Can someone implement a binary tree using a python list? [on hold]
Can I Implement a Binary tree in python using a python list? If possible
how it's done?
Can I Implement a Binary tree in python using a python list? If possible
how it's done?
what does the # and ## means in C preprocessor macro of c++
what does the # and ## means in C preprocessor macro of c++
I read the following code:
#define MACRO(abc, def) {#def ## #abc}
char result[10] = MARCO(abc, def);
I know the ## operator is used to merge the two string to one, but what
about the # in front of def and abc?
I read the following code:
#define MACRO(abc, def) {#def ## #abc}
char result[10] = MARCO(abc, def);
I know the ## operator is used to merge the two string to one, but what
about the # in front of def and abc?
IEnumerable extension method issue
IEnumerable extension method issue
I have this IEnumerable extension method that was downloaded from the
Internet and I am struggling to write a retrospective test that works
Extension Method
public static bool In<T>(this T source, params T[] list) where T :
IEnumerable
{
if (source == null) throw new ArgumentNullException("source");
return list.Contains(source);
}
Test
[TestMethod]
public void In()
{
IEnumerable<int> search = new int[] { 0 };
IEnumerable<int> found = new int[] { 0, 0, 1, 2, 3 };
IEnumerable<int> notFound = new int[] { 1, 5, 6, 7, 8 };
Assert.IsTrue(search.In(found));
Assert.IsFalse(search.In(notFound));
}
Results
All the code compiles but in both assertions the result from the extension
method returns false when I believe the first assertion search.In(found)
should return true.
Question
Am I doing something wrong in the calling code or is there an issue with
the extension?
I have this IEnumerable extension method that was downloaded from the
Internet and I am struggling to write a retrospective test that works
Extension Method
public static bool In<T>(this T source, params T[] list) where T :
IEnumerable
{
if (source == null) throw new ArgumentNullException("source");
return list.Contains(source);
}
Test
[TestMethod]
public void In()
{
IEnumerable<int> search = new int[] { 0 };
IEnumerable<int> found = new int[] { 0, 0, 1, 2, 3 };
IEnumerable<int> notFound = new int[] { 1, 5, 6, 7, 8 };
Assert.IsTrue(search.In(found));
Assert.IsFalse(search.In(notFound));
}
Results
All the code compiles but in both assertions the result from the extension
method returns false when I believe the first assertion search.In(found)
should return true.
Question
Am I doing something wrong in the calling code or is there an issue with
the extension?
Touch events not passing to subviews
Touch events not passing to subviews
i have a scrollview and inside a uiview that contains multiple subviews (
uiimageview). the problem is i can't pass touch gestures to the imageviews
..
-(void)AddImageViewWithFrame:(CGRect)frame andImage:(UIImage*)img
andtag:(int)tag{
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(imageTapped:)];
tempimg=[[UIImageView alloc] initWithFrame:frame];
UIImageView *bifat = [[UIImageView alloc]
initWithImage:[UIImage imageNamed:@"bifat.jpg"]];
tempimg.image=img;
tempimg.tag=tag;
tap.delegate=self;
tempimg.userInteractionEnabled = YES;
view_cuImagini.userInteractionEnabled=YES;
[tempimg addGestureRecognizer:tap];
// [self.view addGestureRecognizer:tap];
[tempimg addSubview:bifat];
[view_cuImagini addSubview:tempimg];
}
-(void)imageTapped:(UITapGestureRecognizer *)rec{
if (rec.state==UIGestureRecognizerStateRecognized) {
NSLog(@"imageTouch with tag %i",rec.view.tag);
}
i want to be able to find the which tempimg was touched does anybody has a
solutions for this?
i have a scrollview and inside a uiview that contains multiple subviews (
uiimageview). the problem is i can't pass touch gestures to the imageviews
..
-(void)AddImageViewWithFrame:(CGRect)frame andImage:(UIImage*)img
andtag:(int)tag{
UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]
initWithTarget:self action:@selector(imageTapped:)];
tempimg=[[UIImageView alloc] initWithFrame:frame];
UIImageView *bifat = [[UIImageView alloc]
initWithImage:[UIImage imageNamed:@"bifat.jpg"]];
tempimg.image=img;
tempimg.tag=tag;
tap.delegate=self;
tempimg.userInteractionEnabled = YES;
view_cuImagini.userInteractionEnabled=YES;
[tempimg addGestureRecognizer:tap];
// [self.view addGestureRecognizer:tap];
[tempimg addSubview:bifat];
[view_cuImagini addSubview:tempimg];
}
-(void)imageTapped:(UITapGestureRecognizer *)rec{
if (rec.state==UIGestureRecognizerStateRecognized) {
NSLog(@"imageTouch with tag %i",rec.view.tag);
}
i want to be able to find the which tempimg was touched does anybody has a
solutions for this?
Tuesday, 17 September 2013
Webpage displaying differently on PC
Webpage displaying differently on PC
I've gone through every possible reason I could think of as to why my
webpage is displaying differently on a pc. My Navigation bar is enlarged
and split into two lines, is the problem.
I'm testing with a mac 1920 x 1080 resolution and a pc 1920 x 1080
resolution.
Page works perfectly on the mac (safari, firefox, chrome)
page's navigation is enlarged on ie, chrome & firefox on the PC
I've checked for any font substitution which could possibly change enlarge
the nav, fonts are displaying correctly on both pc and mac though.
Is it possible it is an OS issue?
I've gone through every possible reason I could think of as to why my
webpage is displaying differently on a pc. My Navigation bar is enlarged
and split into two lines, is the problem.
I'm testing with a mac 1920 x 1080 resolution and a pc 1920 x 1080
resolution.
Page works perfectly on the mac (safari, firefox, chrome)
page's navigation is enlarged on ie, chrome & firefox on the PC
I've checked for any font substitution which could possibly change enlarge
the nav, fonts are displaying correctly on both pc and mac though.
Is it possible it is an OS issue?
mysql search over two or more table?
mysql search over two or more table?
sorry i am a very mysql beginner:
I want to search over two (or three) tables
Table: persons
id | name | age
1 | AA | 20
2 | BB | 30
3 | CC | 40
Table: data
id | person_id | item
1 | 2 | nail
2 | 2 | hammer
3 | 1 | hammer
4 | 2 | hat
person.id is data.person_id
So i have the following questions: - How can i find all people who has a
hammer? - How can i find all people who have no item? - How can i find all
people who 20 and have hammer? (just add to where 'AND p.age = 20' i think
now) - How can i find all persons who has a item?
I know i can search over more tables with JOIN but i don't get it to work
now.
Thanks in advance!
sorry i am a very mysql beginner:
I want to search over two (or three) tables
Table: persons
id | name | age
1 | AA | 20
2 | BB | 30
3 | CC | 40
Table: data
id | person_id | item
1 | 2 | nail
2 | 2 | hammer
3 | 1 | hammer
4 | 2 | hat
person.id is data.person_id
So i have the following questions: - How can i find all people who has a
hammer? - How can i find all people who have no item? - How can i find all
people who 20 and have hammer? (just add to where 'AND p.age = 20' i think
now) - How can i find all persons who has a item?
I know i can search over more tables with JOIN but i don't get it to work
now.
Thanks in advance!
Custome UncachedSpiceService
Custome UncachedSpiceService
I have an issue when I try to use ormlite with robospice.
With ormlite, we must call getHelper() and releaseHelper(). And I think
the best place to call them is UncachedSpiceService.
So I want to call getHelper() in onStart Service and releaseHelper() in
onStop.
Can I do this? And how can do. Please give me some advice.
Thanks.
I have an issue when I try to use ormlite with robospice.
With ormlite, we must call getHelper() and releaseHelper(). And I think
the best place to call them is UncachedSpiceService.
So I want to call getHelper() in onStart Service and releaseHelper() in
onStop.
Can I do this? And how can do. Please give me some advice.
Thanks.
Custom datatable sort
Custom datatable sort
I have a table of data that is order by rank which can be entered through
an input box.
The rank is a single digit number 1 through 9 or it could be blank. I want
the blanks to always appear at the end of the list whenever I sort.
See the JSFiddle example: http://jsfiddle.net/afEHc/
If I use:
"aoColumns": [ { "sSortDataType": "dom-text" }, null ]
It works picks up the new values but the order is incorrect. That is the
blanks need to always appear at the end.
If I use:
"aoColumns": [{"sType": "data-rank"}, null ]
It works correct initially but then breaks when either I sort by another
column first or add a value to the rank column.
Any point or suggestions would be appreciated.
I have a table of data that is order by rank which can be entered through
an input box.
The rank is a single digit number 1 through 9 or it could be blank. I want
the blanks to always appear at the end of the list whenever I sort.
See the JSFiddle example: http://jsfiddle.net/afEHc/
If I use:
"aoColumns": [ { "sSortDataType": "dom-text" }, null ]
It works picks up the new values but the order is incorrect. That is the
blanks need to always appear at the end.
If I use:
"aoColumns": [{"sType": "data-rank"}, null ]
It works correct initially but then breaks when either I sort by another
column first or add a value to the rank column.
Any point or suggestions would be appreciated.
Abbreviation permutation in PHP
Abbreviation permutation in PHP
I'm trying to write a small routine responsible for permuting all possible
abbreviations for a string. This string is a full name, separated by
spaces. Like this:
James Mitchell Rhodes
I want to output:
J. Mitchell Rhodes
James M. Rhodes
J. M. Rhodes
And so on... however, i also have to consider "stopwords":
James the Third Rhodes
I want to output:
J. the Third R.
James The Third R.
Is there a known algorithm for this? I've been trying to fix this problems
for quite some time now.
I'm trying to write a small routine responsible for permuting all possible
abbreviations for a string. This string is a full name, separated by
spaces. Like this:
James Mitchell Rhodes
I want to output:
J. Mitchell Rhodes
James M. Rhodes
J. M. Rhodes
And so on... however, i also have to consider "stopwords":
James the Third Rhodes
I want to output:
J. the Third R.
James The Third R.
Is there a known algorithm for this? I've been trying to fix this problems
for quite some time now.
How to pass parameters to C# Console Application via task scheduler on win 2k3 server?
How to pass parameters to C# Console Application via task scheduler on win
2k3 server?
I have researched around the web and have found no answer to this simple
question. I know on new versions of windows task scheduler that it
actually has an option area for parameters but on win2k3 there is no such
option.
I am assuming that I just need to pass it as part of the path of the .exe.
Something like. :
"c:\myProgram.exe boolParam=false;stringParam='myVal'"
I am almost positive that this can be done in either the stated way above
or something very similar but my syntax is apparently way off and I have
tried several variations with no success.
2k3 server?
I have researched around the web and have found no answer to this simple
question. I know on new versions of windows task scheduler that it
actually has an option area for parameters but on win2k3 there is no such
option.
I am assuming that I just need to pass it as part of the path of the .exe.
Something like. :
"c:\myProgram.exe boolParam=false;stringParam='myVal'"
I am almost positive that this can be done in either the stated way above
or something very similar but my syntax is apparently way off and I have
tried several variations with no success.
@Transactional in @Service ignored
@Transactional in @Service ignored
If I put 'mode="aspectj"' into 'tx:annotation-driven' tag, then
Spring-data handles transactions only in @Repository files, and not in
@Service classes.
Here is my @Service to retrieve users:
@Service
public class RepositoryAuthService implements AuthService{
@Resource
AuthUserRepository userRepository;
@Transactional(propagation = Propagation.REQUIRED)
@Override
public User findByCredentials(String userName, String password){
User user = userRepository.getByCredentials(userName, password);
TransactionAspectSupport.currentTransactionStatus().toString();
...
}
Here is my spring-context:
<tx:annotation-driven mode="aspectj"
transaction-manager="transactionManager" />
<jpa:repositories base-package="my.jpatest.dao.auth" />
<context:component-scan base-package="my.jpatest.dao.auth">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Repository" />
</context:component-scan>
<bean class="my.jpatest.dao.auth.RepositoryAuthService" id="authService" />
Exception:
org.springframework.transaction.NoTransactionException: No transaction
aspect-managed TransactionStatus in scope
at
org.springframework.transaction.interceptor.TransactionAspectSupport.currentTransactionStatus(TransactionAspectSupport.java:111)
at
my.jpatest.dao.auth.RepositoryAuthService.findByCredentials(RepositoryAuthService.java:34)
I tried 'aspectj' with 'proxy-target-class="true"' but did not help.
Without mode="aspectj" everything is fine: the connection remains after
the repository-call as expected.
There is a detailed article about that, but this is quite long:
http://doanduyhai.wordpress.com/2011/11/20/spring-transactional-explained/
Any tips?
Regards: bence
If I put 'mode="aspectj"' into 'tx:annotation-driven' tag, then
Spring-data handles transactions only in @Repository files, and not in
@Service classes.
Here is my @Service to retrieve users:
@Service
public class RepositoryAuthService implements AuthService{
@Resource
AuthUserRepository userRepository;
@Transactional(propagation = Propagation.REQUIRED)
@Override
public User findByCredentials(String userName, String password){
User user = userRepository.getByCredentials(userName, password);
TransactionAspectSupport.currentTransactionStatus().toString();
...
}
Here is my spring-context:
<tx:annotation-driven mode="aspectj"
transaction-manager="transactionManager" />
<jpa:repositories base-package="my.jpatest.dao.auth" />
<context:component-scan base-package="my.jpatest.dao.auth">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Repository" />
</context:component-scan>
<bean class="my.jpatest.dao.auth.RepositoryAuthService" id="authService" />
Exception:
org.springframework.transaction.NoTransactionException: No transaction
aspect-managed TransactionStatus in scope
at
org.springframework.transaction.interceptor.TransactionAspectSupport.currentTransactionStatus(TransactionAspectSupport.java:111)
at
my.jpatest.dao.auth.RepositoryAuthService.findByCredentials(RepositoryAuthService.java:34)
I tried 'aspectj' with 'proxy-target-class="true"' but did not help.
Without mode="aspectj" everything is fine: the connection remains after
the repository-call as expected.
There is a detailed article about that, but this is quite long:
http://doanduyhai.wordpress.com/2011/11/20/spring-transactional-explained/
Any tips?
Regards: bence
Sunday, 15 September 2013
SVN( CONDITION BASED ) BATCH FILE
SVN( CONDITION BASED ) BATCH FILE
I am trying to write an .bat file which will take an SVN update ( Command
: svn update C:/svn/ ) for me,but some times it is not working as expected
its give error like ( svn: E155004: Working copy 'C:\svn' locked ).
So am trying to write an condition based code that will check if svn
update is successful or not if not successful by above mentioned error so
my .bat file should run svn clean up first and again take update. If you
any idea about this so help me out.
I am trying to write an .bat file which will take an SVN update ( Command
: svn update C:/svn/ ) for me,but some times it is not working as expected
its give error like ( svn: E155004: Working copy 'C:\svn' locked ).
So am trying to write an condition based code that will check if svn
update is successful or not if not successful by above mentioned error so
my .bat file should run svn clean up first and again take update. If you
any idea about this so help me out.
OpenCV, ROS and Computer Vision
OpenCV, ROS and Computer Vision
I started learning OpenCV and ROS one month ago and I would like some tips
in Computer Vision.
What library do I use in ROS for Computer Vision with OpenCV? I'm using
the Gonzalez book of Image processing. Need I use Image Processing book?
About Math what will I need?
Thanks :)
I started learning OpenCV and ROS one month ago and I would like some tips
in Computer Vision.
What library do I use in ROS for Computer Vision with OpenCV? I'm using
the Gonzalez book of Image processing. Need I use Image Processing book?
About Math what will I need?
Thanks :)
node js ENOENT error
node js ENOENT error
running this code giving me this error, trying to fig out since an hour
but failed
var http = require('http');
var url = require('url');
var fs = require('fs');
var port = 3010;
http.createServer(function(req, res){
var query = url.parse(req.url,true).query;
console.log(query);
var file = query.f + query.t;
//var file = "eurusd_m1.json";
console.log(file);
var eurusd;
fs.readFile('data/' + file + '_m1.json', function(err,data){
if (err){
console.log(err);
}
eurusd = JSON.parse(data);
console.log(eurusd);
});
res.writeHead(200,{'content-type':'text/plain'});
res.end("helllo owrld");
}).listen(port);
console.log("server running at port 3010..");
it's giving me below result:
server running at port 3010..
{ f: 'eur', t: 'usd' }
eurusd
{}
NaN
{ [Error: ENOENT, open
'C:\Users\Administrator\Documents\zeromq\data\NaN_m1.json']
errno: 34,
code: 'ENOENT',
path: 'C:\\Users\\Administrator\\Documents\\zeromq\\data\\NaN_m1.json' }
undefined:1
undefined
^
SyntaxError: Unexpected token u
at Object.parse (native)
at C:\Users\Administrator\Documents\zeromq\dataserver.js:17:17
at fs.js:207:20
at Object.oncomplete (fs.js:107:15)
running this code giving me this error, trying to fig out since an hour
but failed
var http = require('http');
var url = require('url');
var fs = require('fs');
var port = 3010;
http.createServer(function(req, res){
var query = url.parse(req.url,true).query;
console.log(query);
var file = query.f + query.t;
//var file = "eurusd_m1.json";
console.log(file);
var eurusd;
fs.readFile('data/' + file + '_m1.json', function(err,data){
if (err){
console.log(err);
}
eurusd = JSON.parse(data);
console.log(eurusd);
});
res.writeHead(200,{'content-type':'text/plain'});
res.end("helllo owrld");
}).listen(port);
console.log("server running at port 3010..");
it's giving me below result:
server running at port 3010..
{ f: 'eur', t: 'usd' }
eurusd
{}
NaN
{ [Error: ENOENT, open
'C:\Users\Administrator\Documents\zeromq\data\NaN_m1.json']
errno: 34,
code: 'ENOENT',
path: 'C:\\Users\\Administrator\\Documents\\zeromq\\data\\NaN_m1.json' }
undefined:1
undefined
^
SyntaxError: Unexpected token u
at Object.parse (native)
at C:\Users\Administrator\Documents\zeromq\dataserver.js:17:17
at fs.js:207:20
at Object.oncomplete (fs.js:107:15)
How do i change the color of actionbar's up arrow
How do i change the color of actionbar's up arrow
How do I change the actionbar's up arrow. I am using the action bar in
android not ABS or actionbarcompat . Is there a way to change the color
/image of the action bar's up arrow.
How do I change the actionbar's up arrow. I am using the action bar in
android not ABS or actionbarcompat . Is there a way to change the color
/image of the action bar's up arrow.
Length of Python dictionary created doesn't match length from input file
Length of Python dictionary created doesn't match length from input file
Hi python programmers out there!
I'm currently to create a dictionary from the following input file:
1776344_at 1779734_at 0.755332745 1.009570769 -0.497209846 1776344_at
1771911_at 0.931592828 0.830039019 2.28101445 1776344_at 1777458_at
0.746306282 0.753624146 3.709120716 ... ...
There are a total of 12552 lines in this file. What I wanted to do is to
create a dictionary where the first 2 columns are the keys and the rest
are the values. This I've successfully done and it looks something like
this:
1770449_s_at;1777263_at:0.825723773;1.188969175;-2.858979578
1772892_at;1772051_at:-0.743866602;-1.303847456;26.41464414
1777227_at;1779218_s_at:0.819554413;0.677758609;4.51390617
But here's THE THING: I ran my python script on ms-dos cmd, and the
generated output not only does not have the same sequence as that in the
input file (i.e. 1st line is the 34th line), the whole file only have 739
lines.
Can someone enlighten me what's going on? Is it something to do with
memory? Cos the last I check I still have 305GB of disk space.
The script I wrote is as follow:
import sys import os
input_file = sys.argv[1] infile = open(input_file, 'r')
model_dict = {} for line in infile: key =
';'.join(line.split('\t')[0:2]).rstrip(os.linesep) value =
';'.join(line.split('\t')[2:]).rstrip(os.linesep) print 'keys
are:',key,'\n','values are:',value model_dict[key] = value print
model_dict outfile = open('model_dict', 'w') for key,value in
model_dict.items(): print key,value outfile.write('%s:%s\n' % (key,value))
outfile.close()
Thank you guys in advance!
Hi python programmers out there!
I'm currently to create a dictionary from the following input file:
1776344_at 1779734_at 0.755332745 1.009570769 -0.497209846 1776344_at
1771911_at 0.931592828 0.830039019 2.28101445 1776344_at 1777458_at
0.746306282 0.753624146 3.709120716 ... ...
There are a total of 12552 lines in this file. What I wanted to do is to
create a dictionary where the first 2 columns are the keys and the rest
are the values. This I've successfully done and it looks something like
this:
1770449_s_at;1777263_at:0.825723773;1.188969175;-2.858979578
1772892_at;1772051_at:-0.743866602;-1.303847456;26.41464414
1777227_at;1779218_s_at:0.819554413;0.677758609;4.51390617
But here's THE THING: I ran my python script on ms-dos cmd, and the
generated output not only does not have the same sequence as that in the
input file (i.e. 1st line is the 34th line), the whole file only have 739
lines.
Can someone enlighten me what's going on? Is it something to do with
memory? Cos the last I check I still have 305GB of disk space.
The script I wrote is as follow:
import sys import os
input_file = sys.argv[1] infile = open(input_file, 'r')
model_dict = {} for line in infile: key =
';'.join(line.split('\t')[0:2]).rstrip(os.linesep) value =
';'.join(line.split('\t')[2:]).rstrip(os.linesep) print 'keys
are:',key,'\n','values are:',value model_dict[key] = value print
model_dict outfile = open('model_dict', 'w') for key,value in
model_dict.items(): print key,value outfile.write('%s:%s\n' % (key,value))
outfile.close()
Thank you guys in advance!
How responsible are negative positioning on CSS
How responsible are negative positioning on CSS
I'm getting started on CSS and I have the following question:
Is it "responsible" to use a negative positioning on CSS? Can this cause
any conflict on browsers such as IE7,8? What do you recommend?
#example-bottom {
position: relative;
top: -3px;
min-height: 29px;
margin-bottom: 10px;
}
I'm getting started on CSS and I have the following question:
Is it "responsible" to use a negative positioning on CSS? Can this cause
any conflict on browsers such as IE7,8? What do you recommend?
#example-bottom {
position: relative;
top: -3px;
min-height: 29px;
margin-bottom: 10px;
}
About process and the Java VM
About process and the Java VM
It seems one VM instance can only run one process (real OS or VMware can
run multiple process in it).
is it right?
It seems one VM instance can only run one process (real OS or VMware can
run multiple process in it).
is it right?
Saturday, 14 September 2013
HTTP response content type
HTTP response content type
I am implementing a file download feature via a servlet and tried using
Files.probeContentType without success, it doesn't seem to pick up the
right MIME type, so I use a default of application/octet-stream when that
happens. In my testing, that setting seems to work ok with all the various
file types like tar, gif, gz, mp4, xml, json, work as in the files are
downloaded correctly and can be opened with their respective apps.
First question, if anyone can tell me what I am doing wrong with
probeContentType or a better way to determine the mime type, that'll be
most appreciated, here are the few lines of code in Scala
val is = new FileInputStream(file)
val mt = Files.probeContentType(file.toPath)
val mimetype = if (mt == null) "application/octet-stream" else mt
Regardless, is it ok to always set the HTTP response content-type to
application/octet-stream? I have only tested with Chrome and Firefox.
I am implementing a file download feature via a servlet and tried using
Files.probeContentType without success, it doesn't seem to pick up the
right MIME type, so I use a default of application/octet-stream when that
happens. In my testing, that setting seems to work ok with all the various
file types like tar, gif, gz, mp4, xml, json, work as in the files are
downloaded correctly and can be opened with their respective apps.
First question, if anyone can tell me what I am doing wrong with
probeContentType or a better way to determine the mime type, that'll be
most appreciated, here are the few lines of code in Scala
val is = new FileInputStream(file)
val mt = Files.probeContentType(file.toPath)
val mimetype = if (mt == null) "application/octet-stream" else mt
Regardless, is it ok to always set the HTTP response content-type to
application/octet-stream? I have only tested with Chrome and Firefox.
Searching API for a specific Json key, value
Searching API for a specific Json key, value
I'm using the wunderground api to get weather conditions from a specific
city. They have various ways to query the data here --->
http://www.wunderground.com/weather/api/d/docs?d=data/index. The response
is in JSON.
Is there a possible way to GET the locations from a specific key, value
using the api; like getting all the cities that have a current temperature
of 75 degrees, without getting the data for various locations, then
checking if the temperature is a certain number?
I'm using the wunderground api to get weather conditions from a specific
city. They have various ways to query the data here --->
http://www.wunderground.com/weather/api/d/docs?d=data/index. The response
is in JSON.
Is there a possible way to GET the locations from a specific key, value
using the api; like getting all the cities that have a current temperature
of 75 degrees, without getting the data for various locations, then
checking if the temperature is a certain number?
Create a rule to automatically convert a column to lowercase or uppercase on insert
Create a rule to automatically convert a column to lowercase or uppercase
on insert
Using postgres, how would you create a rule to force lowercase or
uppercase on a given column when a new record is inserted. For example, so
that an insert like this:
INSERT INTO foobar (foo, bar) VALUES ('EXAMPLE', 2)
Gets converted to by a rule prior to inserting:
INSERT INTO foobar (foo, bar) VALUES ('example', 2)
This is what I came up with after looking at the documentation but was not
able to get it to work:
CREATE RULE "foo_to_lower" AS ON INSERT TO foobar
DO INSTEAD
INSERT INTO foobar VALUES (
lower(NEW.foo)
)
WHERE (ascii(foo) BETWEEN 65 AND 90);
Note, in the WHERE statement I'm trying to detect uppercase characters as
ascii characters between 65 and 90 are all uppercase.
on insert
Using postgres, how would you create a rule to force lowercase or
uppercase on a given column when a new record is inserted. For example, so
that an insert like this:
INSERT INTO foobar (foo, bar) VALUES ('EXAMPLE', 2)
Gets converted to by a rule prior to inserting:
INSERT INTO foobar (foo, bar) VALUES ('example', 2)
This is what I came up with after looking at the documentation but was not
able to get it to work:
CREATE RULE "foo_to_lower" AS ON INSERT TO foobar
DO INSTEAD
INSERT INTO foobar VALUES (
lower(NEW.foo)
)
WHERE (ascii(foo) BETWEEN 65 AND 90);
Note, in the WHERE statement I'm trying to detect uppercase characters as
ascii characters between 65 and 90 are all uppercase.
Access to fields of prefetch_related on reverse relation
Access to fields of prefetch_related on reverse relation
I have this models
class Animal(models.model):
name = models.Charfield()
class Dog(Animal):
field = models.IntegerField()
class Owner(models.model):
animal = models.ForeignKey(Animal)
name = models.CharField()
Now supose that i want all Dogs and his owner names.
dogs = Dog.objects.all().prefetch_related('ownwer_set')
How do i access owner.name from dogs?
I have this models
class Animal(models.model):
name = models.Charfield()
class Dog(Animal):
field = models.IntegerField()
class Owner(models.model):
animal = models.ForeignKey(Animal)
name = models.CharField()
Now supose that i want all Dogs and his owner names.
dogs = Dog.objects.all().prefetch_related('ownwer_set')
How do i access owner.name from dogs?
Return a random number inside a loop in JS but never the same
Return a random number inside a loop in JS but never the same
This question has been asked a couple of times, but never exactly how I
need it. I'm trying to do something like this: I have a fixed number of
spans and I want to give every one of them a font size between 10px and
46px. Some can have the same value! Decimals are allowed (but I'm guessing
useless because browsers handle "sub-pixels" differently (I am told)).
Apart from that, I want a random value between 0 and 100 for left and top
properties, but these values can never be the same!
I got this far: (borrowed from here on SO), but sometimes values overlap.
function randomFromInterval(from,to) {
return Math.floor(Math.random()*(to-from+1)+from);
}
$("#question-mark-wrapper > span:not('.the-one')").each(function() {
$(this).css({
"font-size": randomFromInterval(10,36) + "px",
"left": randomFromInterval(0,100) + "%",
"top": randomFromInterval(0,100) + "%",
});
});
This question has been asked a couple of times, but never exactly how I
need it. I'm trying to do something like this: I have a fixed number of
spans and I want to give every one of them a font size between 10px and
46px. Some can have the same value! Decimals are allowed (but I'm guessing
useless because browsers handle "sub-pixels" differently (I am told)).
Apart from that, I want a random value between 0 and 100 for left and top
properties, but these values can never be the same!
I got this far: (borrowed from here on SO), but sometimes values overlap.
function randomFromInterval(from,to) {
return Math.floor(Math.random()*(to-from+1)+from);
}
$("#question-mark-wrapper > span:not('.the-one')").each(function() {
$(this).css({
"font-size": randomFromInterval(10,36) + "px",
"left": randomFromInterval(0,100) + "%",
"top": randomFromInterval(0,100) + "%",
});
});
PHP Convert mysql to mysqli
PHP Convert mysql to mysqli
The following script works fine:
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and
password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword");
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
Why, when I replace only the mysql_connect and mysql_select_db statements
(keeping everything else including all passwords the same) with the
following, do i get the "Wrong Username or Password" echo?
mysqli_connect($host,$username,$password,$db_name) or die("cannot connect");
The following script works fine:
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and
password='$mypassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword");
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
Why, when I replace only the mysql_connect and mysql_select_db statements
(keeping everything else including all passwords the same) with the
following, do i get the "Wrong Username or Password" echo?
mysqli_connect($host,$username,$password,$db_name) or die("cannot connect");
Filtering search results in android app
Filtering search results in android app
Currently when I search for a particular tag, the results are sorted
according to the activity on them. There is no option to see like newest
questions with a tag android-app. Please add this feature.
Currently when I search for a particular tag, the results are sorted
according to the activity on them. There is no option to see like newest
questions with a tag android-app. Please add this feature.
how to put the res file in android jar
how to put the res file in android jar
I am develop the android project, and I want to provide the SDK to other
used, and I have some picture or file in the res folder, and use the
resource by the R class. but now, I can't package the res in to the SDK
jar.
thanks for you help.
json
I am develop the android project, and I want to provide the SDK to other
used, and I have some picture or file in the res folder, and use the
resource by the R class. but now, I can't package the res in to the SDK
jar.
thanks for you help.
json
Friday, 13 September 2013
How to append !important to an inline css?
How to append !important to an inline css?
It's really hard for me to figure this out. But can anyone give me a
sample script where I can just add !important to an already existing
inline css?
It's really hard for me to figure this out. But can anyone give me a
sample script where I can just add !important to an already existing
inline css?
Regex: select name and surname
Regex: select name and surname
I want to select just the names of persons in the 3 examples and exclude
this part :(Nom : Mr or Nom : Mme ) :
Nom : Mr Name Surname Nom : Mr Name1 Name2 Surname Nom : Mme Name Surname
Nom : Mme Name1 Name2 Surname
I'm using Regex with a generator : http://gskinner.com/RegExr/ I tried
(?<=Nom :)(.*)
but it gives nothing as it includes Mr or Mme that I want to exclude any
help please?
Best regards Amorino
I want to select just the names of persons in the 3 examples and exclude
this part :(Nom : Mr or Nom : Mme ) :
Nom : Mr Name Surname Nom : Mr Name1 Name2 Surname Nom : Mme Name Surname
Nom : Mme Name1 Name2 Surname
I'm using Regex with a generator : http://gskinner.com/RegExr/ I tried
(?<=Nom :)(.*)
but it gives nothing as it includes Mr or Mme that I want to exclude any
help please?
Best regards Amorino
How do I test if any of my json's properties has a particular subproperty, without a loop?
How do I test if any of my json's properties has a particular subproperty,
without a loop?
Consider an example:
food : {
cheese: { taste: "delicious", smell: "smelly" },
bacon: { taste: "godly", smell: "godly" }
}
I would like a loop-less test to see if any of "food"'s properties (cheese
and/or bacon ) have a "taste" that is "godly".
In this case, it would be yes. Testing for "disgusting" should result in
false as there is none to have taste : "disgusting"
My question really revolves around a loopless solution, as a hundred
property json within several layers of loops is bad :(
without a loop?
Consider an example:
food : {
cheese: { taste: "delicious", smell: "smelly" },
bacon: { taste: "godly", smell: "godly" }
}
I would like a loop-less test to see if any of "food"'s properties (cheese
and/or bacon ) have a "taste" that is "godly".
In this case, it would be yes. Testing for "disgusting" should result in
false as there is none to have taste : "disgusting"
My question really revolves around a loopless solution, as a hundred
property json within several layers of loops is bad :(
Rails validating with two models
Rails validating with two models
Ok, bit confused on how to solve this issue.
I have one form and two models. Here is my form:
<% if @booking.errors.any? %>
<% @booking.errors.full_messages.each do |msg| %>
<p class="error"><%= msg %></p>
<% end %>
<% end %>
<% if @guest.errors.any? %>
<% @guest.errors.full_messages.each do |msg| %>
<p class="error"><%= msg %></p>
<% end %>
<% end %>
<%= form_for :booking, url: bookings_path do |f| %>
<%= label_tag :email, "Guest's Email Address" %>
<%= text_field_tag :email %>
<%= f.label :nights, "Nights" %>
<%= f.text_field :nights %>
<%= f.label :nights, "People" %>
<%= f.text_field :people %>
<%= f.label :nights, "Arrival Date" %>
<%= f.text_field :arrival %>
<% end %>
As you can see, the email field isn't part of the form builder. The email
address will be used to create a new Guest record if the email doesn't
already exist. Once I have the ID of the guest then the booking record can
be made also.
Here is the code for create action in my BookingController - where the
form is submitted to...
...
def create
accommodation = current_user.accommodation
guest = Guest.find_or_create_by(:email => params[:email])
@booking = accommodation.bookings.new(post_params.merge(:guest_id =>
guest.id))
if @booking.save
flash[:success] = 'The booking has been added successfully.'
redirect_to :controller => 'bookings', :action => 'index'
else
render 'new'
end
end
...
I do realise this question isn't new but I can't find a good solution
anywhere to my problem - I want to be able to set the form up properly (if
necessary) and validate all fields using the two models. Then I need to
display the error messages. At the moment, my email is ignored and I'm not
sure what to do next.
Any help much appreciated.
Ok, bit confused on how to solve this issue.
I have one form and two models. Here is my form:
<% if @booking.errors.any? %>
<% @booking.errors.full_messages.each do |msg| %>
<p class="error"><%= msg %></p>
<% end %>
<% end %>
<% if @guest.errors.any? %>
<% @guest.errors.full_messages.each do |msg| %>
<p class="error"><%= msg %></p>
<% end %>
<% end %>
<%= form_for :booking, url: bookings_path do |f| %>
<%= label_tag :email, "Guest's Email Address" %>
<%= text_field_tag :email %>
<%= f.label :nights, "Nights" %>
<%= f.text_field :nights %>
<%= f.label :nights, "People" %>
<%= f.text_field :people %>
<%= f.label :nights, "Arrival Date" %>
<%= f.text_field :arrival %>
<% end %>
As you can see, the email field isn't part of the form builder. The email
address will be used to create a new Guest record if the email doesn't
already exist. Once I have the ID of the guest then the booking record can
be made also.
Here is the code for create action in my BookingController - where the
form is submitted to...
...
def create
accommodation = current_user.accommodation
guest = Guest.find_or_create_by(:email => params[:email])
@booking = accommodation.bookings.new(post_params.merge(:guest_id =>
guest.id))
if @booking.save
flash[:success] = 'The booking has been added successfully.'
redirect_to :controller => 'bookings', :action => 'index'
else
render 'new'
end
end
...
I do realise this question isn't new but I can't find a good solution
anywhere to my problem - I want to be able to set the form up properly (if
necessary) and validate all fields using the two models. Then I need to
display the error messages. At the moment, my email is ignored and I'm not
sure what to do next.
Any help much appreciated.
Parser error on redirect?
Parser error on redirect?
I get a parser error when running my code and have checked references but
everything seems in place.The error occurs when on a redirect from a page
The error occurs on line 1.
<%@ Page Title="CreateUser" Language="C#" MasterPageFile="~/Main.Master"
AutoEventWireup="true" CodeBehind="CreateUser.aspx.cs"
Inherits="ICSWebPortal.Portal.Pages.User.CreateUser" PageName="Create
User" PageDescription="Details of user" %>
<%@ MasterType VirtualPath="~/Main.Master" %>
This is my redirect function on another page
function CreateNewUser()
{
window.location = "<% = GetHost() %>/User/Create/"
}
I get a parser error when running my code and have checked references but
everything seems in place.The error occurs when on a redirect from a page
The error occurs on line 1.
<%@ Page Title="CreateUser" Language="C#" MasterPageFile="~/Main.Master"
AutoEventWireup="true" CodeBehind="CreateUser.aspx.cs"
Inherits="ICSWebPortal.Portal.Pages.User.CreateUser" PageName="Create
User" PageDescription="Details of user" %>
<%@ MasterType VirtualPath="~/Main.Master" %>
This is my redirect function on another page
function CreateNewUser()
{
window.location = "<% = GetHost() %>/User/Create/"
}
My OS puts hard spaces after #'s
My OS puts hard spaces after #'s
I'm having a small issue when writing Markdown documents because for some
reason OS X adds hard spaces after the character #. If I type this:
## Title
I would expect to get this:
<h2>Title</h2>
But because my system puts a hard space after the last #, I get this:
<h2> Title</h2>
I'm saying my system because I've had the issue with two different text
editors. I have no idea where I could fix this. Currently I'm working with
Vim and I'd welcome an editor-based fix as well!
I'm having a small issue when writing Markdown documents because for some
reason OS X adds hard spaces after the character #. If I type this:
## Title
I would expect to get this:
<h2>Title</h2>
But because my system puts a hard space after the last #, I get this:
<h2> Title</h2>
I'm saying my system because I've had the issue with two different text
editors. I have no idea where I could fix this. Currently I'm working with
Vim and I'd welcome an editor-based fix as well!
Thursday, 12 September 2013
Is it possible to style the contents of a DockPanel to fill the last *visible* child?
Is it possible to style the contents of a DockPanel to fill the last
*visible* child?
Consider this XAML snippet...
<DockPanel x:Name="TestDockPanel">
<Button x:Name="RightButton" Content="Right" DockPanel.Dock="Right" />
<Button x:Name="FillButton" Content="Fill" />
</DockPanel>
As written, the DockPanel will layout 'RightButton' to the right, then
fill the rest of the area with 'FillButton' like this...
We're trying to find a way to style it so that when 'FillButton' has its
visibility changed to 'Collapsed', 'RightButton' should now fill the area,
like this...
The only way we know how to do this is to physically remove 'FillButton'
from the children of 'TestDockPanel' but that requires code-behind, which
we're trying to avoid.
Update
Below in an answer, I've posed a solution based on a subclass. However,
I'm leaving this open since I'd like something that can be used with any
DockPanel (or other subclass) and preferrably applied via a style or an
attached behavior. Also, to be clear, a requirement of the solution is
that it must be based on a DockPanel, not a grid or other panel.
*visible* child?
Consider this XAML snippet...
<DockPanel x:Name="TestDockPanel">
<Button x:Name="RightButton" Content="Right" DockPanel.Dock="Right" />
<Button x:Name="FillButton" Content="Fill" />
</DockPanel>
As written, the DockPanel will layout 'RightButton' to the right, then
fill the rest of the area with 'FillButton' like this...
We're trying to find a way to style it so that when 'FillButton' has its
visibility changed to 'Collapsed', 'RightButton' should now fill the area,
like this...
The only way we know how to do this is to physically remove 'FillButton'
from the children of 'TestDockPanel' but that requires code-behind, which
we're trying to avoid.
Update
Below in an answer, I've posed a solution based on a subclass. However,
I'm leaving this open since I'd like something that can be used with any
DockPanel (or other subclass) and preferrably applied via a style or an
attached behavior. Also, to be clear, a requirement of the solution is
that it must be based on a DockPanel, not a grid or other panel.
I'm try to wrote in assembly
I'm try to wrote in assembly
I try to write through the cell values ​​coup addresses 100h
to 110h negative values​​. (If the value is negative - it
remains negative). Do not use the Compare CMP. so i try to check the MSB
sign with text command and it isn't working I wrote this
code segment
assume ds:code,cs:code
start: mov ax,code
mov cx,10
mov si,100h
check:
mov al,[si]
test al,10000000h//here i have problem!
je isntnegative
inc si
dec cx
cmp cx,0
jz finish
jmp check
isntnegative:
neg al
inc si
dec cx
cmp cx,0
jz finish
jmp check
finish:
int 21h
nop
code ends
end start
I know it's long and effective but it's the best I can do at the moment.
I try to write through the cell values ​​coup addresses 100h
to 110h negative values​​. (If the value is negative - it
remains negative). Do not use the Compare CMP. so i try to check the MSB
sign with text command and it isn't working I wrote this
code segment
assume ds:code,cs:code
start: mov ax,code
mov cx,10
mov si,100h
check:
mov al,[si]
test al,10000000h//here i have problem!
je isntnegative
inc si
dec cx
cmp cx,0
jz finish
jmp check
isntnegative:
neg al
inc si
dec cx
cmp cx,0
jz finish
jmp check
finish:
int 21h
nop
code ends
end start
I know it's long and effective but it's the best I can do at the moment.
Dynamic Search Boxes in Jquery Mobile
Dynamic Search Boxes in Jquery Mobile
Am not sure on how to do this but I will describe it and hopefully you all
can come up with a good solution. I want to have a box (not sure if its an
input of search box) that when someone types in the box it pulls values
from my database and shows the closest match based on characters being
typed in. If the word that is typed by the user is not there then when the
form is submitted then the word is added to a database.
Additionally I want to have an add button next to the box, so that if the
user wants to add more than one word they can. This means that when the
add is clicked a duplicate of the first box appears which does the same
thing. The values will be stored in an array.
Any idea how I can go about doing this?
Am not sure on how to do this but I will describe it and hopefully you all
can come up with a good solution. I want to have a box (not sure if its an
input of search box) that when someone types in the box it pulls values
from my database and shows the closest match based on characters being
typed in. If the word that is typed by the user is not there then when the
form is submitted then the word is added to a database.
Additionally I want to have an add button next to the box, so that if the
user wants to add more than one word they can. This means that when the
add is clicked a duplicate of the first box appears which does the same
thing. The values will be stored in an array.
Any idea how I can go about doing this?
Find the number of pairs whose sum is divisible by k?
Find the number of pairs whose sum is divisible by k?
Given a value of k. Such that k<=100000 We have to print the number of
pairs such that sum of elements of each pair is divisible by k. under the
following condition first element should be smaller than second, and both
element should be less than 10^9
Given a value of k. Such that k<=100000 We have to print the number of
pairs such that sum of elements of each pair is divisible by k. under the
following condition first element should be smaller than second, and both
element should be less than 10^9
Mysql function TO_SECONDS doesn't exist
Mysql function TO_SECONDS doesn't exist
I've been passing through this problem for one day, and it's hard to
understand why MySql doesn't work easily.
I'm trying to execute the statement below, but it isn't recognized at all.
SELECT TO_SECONDS('2013-09-12 11:15:00');
I get the following error:
ERROR 1305 (42000): FUNCTION db.to_seconds does not exist
I've checked MySQL's documentation and this function is available since
version 5.5. So, I updated my previous version and now I'm working with
6.0 but still not working.
mysql> select version();
+---------------------------+
| version() |
+---------------------------+
| 6.0.4-alpha-community-log |
+---------------------------+
1 row in set (0.03 sec)
Server version: 6.0.4-alpha-community-log MySQL Community Server (GPL)
Anyone knows what is going on?
I've been passing through this problem for one day, and it's hard to
understand why MySql doesn't work easily.
I'm trying to execute the statement below, but it isn't recognized at all.
SELECT TO_SECONDS('2013-09-12 11:15:00');
I get the following error:
ERROR 1305 (42000): FUNCTION db.to_seconds does not exist
I've checked MySQL's documentation and this function is available since
version 5.5. So, I updated my previous version and now I'm working with
6.0 but still not working.
mysql> select version();
+---------------------------+
| version() |
+---------------------------+
| 6.0.4-alpha-community-log |
+---------------------------+
1 row in set (0.03 sec)
Server version: 6.0.4-alpha-community-log MySQL Community Server (GPL)
Anyone knows what is going on?
what's the difference between thread sheduling actor and thread context switch
what's the difference between thread sheduling actor and thread context
switch
it is said in scala that using the actors can scale much better compared
with traditional threading. I can understand that bit like keep thread
blocking is obiviously not good. but what is the difference of thread
scheduling new tasks and thread context switches? isn't this kind of
scheduling new tasks will incur performance penalties as well ?
similar scenario in .NET as well, the async does similar things, I don't
understand the difference here of the thread switching off from the state
machine switching on to the unfinished tasks with context switches happen
on threads, after all what's the difference ?
switch
it is said in scala that using the actors can scale much better compared
with traditional threading. I can understand that bit like keep thread
blocking is obiviously not good. but what is the difference of thread
scheduling new tasks and thread context switches? isn't this kind of
scheduling new tasks will incur performance penalties as well ?
similar scenario in .NET as well, the async does similar things, I don't
understand the difference here of the thread switching off from the state
machine switching on to the unfinished tasks with context switches happen
on threads, after all what's the difference ?
Wednesday, 11 September 2013
with absolutely positioned not adjusting the parent height
with absolutely positioned not adjusting the parent height
I've done a fair bit of reading on this, and haven't seen an answer that I
can get to work. Is it possible to make the parent div height adjust to
the height of the absolutely positioned list-item ?
For now, I've compensated by adding large amount of margin.. real large..
but that is not the correct solution here.
The html looks like this: Simple..
<div class="home-section products">
<div id="gallery-container">
<ul>
<li class="one"><img src="showcase-five.jpg"></li>
<li class="two"><img src="showcase-four.jpg"></li>
<li class="three"><img src="showcase-one.jpg"></li>
<li class="four"><img src="showcase-three.jpg"></li>
<li class="five"><img src="showcase-two.jpg"></li>
</ul>
</div>
</div>
I need the li height to make the .home-section adapt to its height.
If posting a link to the development site is allowed, I'd be happy to
share it and allow you to inspect the code in question.
Thanks
I've done a fair bit of reading on this, and haven't seen an answer that I
can get to work. Is it possible to make the parent div height adjust to
the height of the absolutely positioned list-item ?
For now, I've compensated by adding large amount of margin.. real large..
but that is not the correct solution here.
The html looks like this: Simple..
<div class="home-section products">
<div id="gallery-container">
<ul>
<li class="one"><img src="showcase-five.jpg"></li>
<li class="two"><img src="showcase-four.jpg"></li>
<li class="three"><img src="showcase-one.jpg"></li>
<li class="four"><img src="showcase-three.jpg"></li>
<li class="five"><img src="showcase-two.jpg"></li>
</ul>
</div>
</div>
I need the li height to make the .home-section adapt to its height.
If posting a link to the development site is allowed, I'd be happy to
share it and allow you to inspect the code in question.
Thanks
Return type for this function
Return type for this function
my function prototype is this.
int * f4(int parm);
my function looks like this
int * f4(int parm)
{
return &parm + 1;
}
Is my return type correct for this? because it isn't doing anything when I
call the function.
this is my call
int *pointer1;
pointer1 = f4(319);
cout << pointer1 << endl;
it returns the address of the pointer, but I need it to return the value,
but I can't seem to get it to work.
using
cout << *pointer << endl;
just displays 0
my function prototype is this.
int * f4(int parm);
my function looks like this
int * f4(int parm)
{
return &parm + 1;
}
Is my return type correct for this? because it isn't doing anything when I
call the function.
this is my call
int *pointer1;
pointer1 = f4(319);
cout << pointer1 << endl;
it returns the address of the pointer, but I need it to return the value,
but I can't seem to get it to work.
using
cout << *pointer << endl;
just displays 0
How to download file using TIDFtp in DelphiXE2
How to download file using TIDFtp in DelphiXE2
I'm having a problem downloading a file using the TidFTP component in
Delphi XE2. I am able to get a connection to the FTP site, get a list of
files and perform the get command. However, when I try to download a file
using the get command the file always downloads larger than the source
file. Then the subsequent file is corrupt.
Additionally, if I try to download multiple files, the first file
downloads (larger than the source) and the remaining files are skipped. No
error is thrown from the get command, it just quits. I tried to hook into
some of the events on the TidFTP control like AfterGet and OnStatus but
everything appears normal.
I tried using a 3rd party FTP client to access the file and download it
just to make sure it was not a problem with our FTP server and that
download worked as expected. So I'm thinking it might be related to the
TidFTP control or perhaps I'm doing something incorrectly.
Here is the routine I'm using to download the file:
var
ftp: TIdFTP;
strDirectory: string;
begin
ftp := TIdFTP.Create(nil);
try
ftp.Host := 'ftp.myftpserver.com'
ftp.Passive := false;
ftp.Username := 'TestUser';
ftp.Password := 'TestPassword';
ftp.ConnectTimeout := 1000;
ftp.Connect();
ftp.BeginWork(wmRead);
ftp.ChangeDir('/TestArea/');
strDirectory := 'c:\test\';
if not DirectoryExists(strDirectory) then
CreateDir(strDirectory);
ftp.Get('Test.zip', strDirectory + '\' + 'Test.zip', true, false);
ftp.Disconnect();
except
on e: exception do
showMessage(e.message);
end;
end;
I'm having a problem downloading a file using the TidFTP component in
Delphi XE2. I am able to get a connection to the FTP site, get a list of
files and perform the get command. However, when I try to download a file
using the get command the file always downloads larger than the source
file. Then the subsequent file is corrupt.
Additionally, if I try to download multiple files, the first file
downloads (larger than the source) and the remaining files are skipped. No
error is thrown from the get command, it just quits. I tried to hook into
some of the events on the TidFTP control like AfterGet and OnStatus but
everything appears normal.
I tried using a 3rd party FTP client to access the file and download it
just to make sure it was not a problem with our FTP server and that
download worked as expected. So I'm thinking it might be related to the
TidFTP control or perhaps I'm doing something incorrectly.
Here is the routine I'm using to download the file:
var
ftp: TIdFTP;
strDirectory: string;
begin
ftp := TIdFTP.Create(nil);
try
ftp.Host := 'ftp.myftpserver.com'
ftp.Passive := false;
ftp.Username := 'TestUser';
ftp.Password := 'TestPassword';
ftp.ConnectTimeout := 1000;
ftp.Connect();
ftp.BeginWork(wmRead);
ftp.ChangeDir('/TestArea/');
strDirectory := 'c:\test\';
if not DirectoryExists(strDirectory) then
CreateDir(strDirectory);
ftp.Get('Test.zip', strDirectory + '\' + 'Test.zip', true, false);
ftp.Disconnect();
except
on e: exception do
showMessage(e.message);
end;
end;
PHP -How to display data from text file in table?
PHP -How to display data from text file in table?
I have text file like:
3|1003|Deig|12"
Deig|bakki|1208.00|2.00|96.00|0.00|0.00|0.00|0.00|98.00|90.95|7.05|8516.40
3|1011|Deig|12"
Ponn|bakki|1450.00|2.00|49.00|0.00|0.00|0.00|0.00|51.00|44.62|6.38|9243.75
3|1004|Deig|15"
Deig|bakki|1450.00|25.00|170.00|0.00|0.00|0.00|0.00|195.00|175.75|19.25|27912.50
How can I display the data in the table(it is possible??) each "|"
separates the cells and this text file can have 20+ rows.
I have text file like:
3|1003|Deig|12"
Deig|bakki|1208.00|2.00|96.00|0.00|0.00|0.00|0.00|98.00|90.95|7.05|8516.40
3|1011|Deig|12"
Ponn|bakki|1450.00|2.00|49.00|0.00|0.00|0.00|0.00|51.00|44.62|6.38|9243.75
3|1004|Deig|15"
Deig|bakki|1450.00|25.00|170.00|0.00|0.00|0.00|0.00|195.00|175.75|19.25|27912.50
How can I display the data in the table(it is possible??) each "|"
separates the cells and this text file can have 20+ rows.
VideoPlayer using mediacodec
VideoPlayer using mediacodec
i am looking for a mediaplayer which can play video/audio using new jelly
beans mediacodec api, i was able to play audio and video simultaneously
but audio and video are out of sync.Please help me solve a/v sync problem
sample repos i have used:
https://github.com/showlabor/AndroidPitchPlayer
https://github.com/vecio/MediaCodecDemo
i am looking for a mediaplayer which can play video/audio using new jelly
beans mediacodec api, i was able to play audio and video simultaneously
but audio and video are out of sync.Please help me solve a/v sync problem
sample repos i have used:
https://github.com/showlabor/AndroidPitchPlayer
https://github.com/vecio/MediaCodecDemo
How to select top value using two table
How to select top value using two table
i Have two table
table1:itemTbale
table2:itemDetails
itemTable contain
id | itemName
itemDetails
id | itemID | price | details
table may contain data like this
id | itemName
1 Vechile
2 Fruits
id | itemID | price | details
1 1 80$ bla bla
2 1 150$ bla bla bla
3 1 200$ bla bla
4 2 5$ ..
5 2 8$ ..bla
6 2 7$ bla..
Now i have to select top item details for each itemID
LIKE
id | itemID | price | details |itemName
1 1 80$ bla bla Vechile
4 2 5$ .. Fruits.
I am being little confuse with query.Help me Thank you in advance.
i Have two table
table1:itemTbale
table2:itemDetails
itemTable contain
id | itemName
itemDetails
id | itemID | price | details
table may contain data like this
id | itemName
1 Vechile
2 Fruits
id | itemID | price | details
1 1 80$ bla bla
2 1 150$ bla bla bla
3 1 200$ bla bla
4 2 5$ ..
5 2 8$ ..bla
6 2 7$ bla..
Now i have to select top item details for each itemID
LIKE
id | itemID | price | details |itemName
1 1 80$ bla bla Vechile
4 2 5$ .. Fruits.
I am being little confuse with query.Help me Thank you in advance.
Tuesday, 10 September 2013
Where do I apply changes in htaccess file to direct to subdirectory?
Where do I apply changes in htaccess file to direct to subdirectory?
I have seen some suggestions for changing the htaccess file to pull up a
subdirectory at the root URL, however, when I add code according to those
suggestions, nothing changes - the old root stil pulls up. So I assume I'm
plugging in the additional code in the wrong place. Can someone tell me
where I should plugin code so that the root URL pulls up site.com/joomla?
Here is the original file:
##
# @package Joomla
# @copyright Copyright (C) 2005 - 2013 Open Source Matters. All rights
reserved.
# @license GNU General Public License version 2 or later; see
LICENSE.txt
##
##
# READ THIS COMPLETELY IF YOU CHOOSE TO USE THIS FILE!
#
# The line just below this section: 'Options +FollowSymLinks' may cause
problems
# with some server configurations. It is required for use of mod_rewrite,
but may already
# be set by your server administrator in a way that dissallows changing it in
# your .htaccess file. If using it causes your server to error out,
comment it out (add # to
# beginning of line), reload your site in your browser and test your sef
url's. If they work,
# it has been set by your server administrator and you do not need it set
here.
##
## Can be commented out if causes errors, see notes above.
Options +FollowSymLinks
## Mod_rewrite in use.
RewriteEngine On
## Begin - Rewrite rules to block out some common exploits.
# If you experience problems on your site block out the operations listed
below
# This attempts to block the most common type of exploit `attempts` to
Joomla!
#
# Block out any script trying to base64_encode data within the URL.
RewriteCond %{QUERY_STRING} base64_encode[^(]*\([^)]*\) [OR]
# Block out any script that includes a <script> tag in URL.
RewriteCond %{QUERY_STRING} (<|%3C)([^s]*s)+cript.*(>|%3E) [NC,OR]
# Block out any script trying to set a PHP GLOBALS variable via URL.
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
# Block out any script trying to modify a _REQUEST variable via URL.
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
# Return 403 Forbidden header and show the content of the root homepage
RewriteRule .* index.php [F]
#
## End - Rewrite rules to block out some common exploits.
## Begin - Custom redirects
#
# If you need to redirect some pages, or set a canonical non-www to
# www redirect (or vice versa), place that code here. Ensure those
# redirects use the correct RewriteRule syntax and the [R=301,L] flags.
#
## End - Custom redirects
##
# Uncomment following line if your webserver's URL
# is not directly related to physical file paths.
# Update Your Joomla! Directory (just / for root).
##
# RewriteBase /
## Begin - Joomla! core SEF Section.
#
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
#
# If the requested path and file is not /index.php and the request
# has not already been internally rewritten to the index.php script
RewriteCond %{REQUEST_URI} !^/index\.php
# and the request is for something within the component folder,
# or for the site root, or for an extensionless URL, or the
# requested URL ends with one of the listed extensions
RewriteCond %{REQUEST_URI}
/component/|(/[^.]*|\.(php|html?|feed|pdf|vcf|raw))$ [NC]
# and the requested path and file doesn't directly match a physical file
RewriteCond %{REQUEST_FILENAME} !-f
# and the requested path and file doesn't directly match a physical folder
RewriteCond %{REQUEST_FILENAME} !-d
# internally rewrite the request to the index.php script
RewriteRule .* index.php [L]
#
## End - Joomla! core SEF Section.
I have seen some suggestions for changing the htaccess file to pull up a
subdirectory at the root URL, however, when I add code according to those
suggestions, nothing changes - the old root stil pulls up. So I assume I'm
plugging in the additional code in the wrong place. Can someone tell me
where I should plugin code so that the root URL pulls up site.com/joomla?
Here is the original file:
##
# @package Joomla
# @copyright Copyright (C) 2005 - 2013 Open Source Matters. All rights
reserved.
# @license GNU General Public License version 2 or later; see
LICENSE.txt
##
##
# READ THIS COMPLETELY IF YOU CHOOSE TO USE THIS FILE!
#
# The line just below this section: 'Options +FollowSymLinks' may cause
problems
# with some server configurations. It is required for use of mod_rewrite,
but may already
# be set by your server administrator in a way that dissallows changing it in
# your .htaccess file. If using it causes your server to error out,
comment it out (add # to
# beginning of line), reload your site in your browser and test your sef
url's. If they work,
# it has been set by your server administrator and you do not need it set
here.
##
## Can be commented out if causes errors, see notes above.
Options +FollowSymLinks
## Mod_rewrite in use.
RewriteEngine On
## Begin - Rewrite rules to block out some common exploits.
# If you experience problems on your site block out the operations listed
below
# This attempts to block the most common type of exploit `attempts` to
Joomla!
#
# Block out any script trying to base64_encode data within the URL.
RewriteCond %{QUERY_STRING} base64_encode[^(]*\([^)]*\) [OR]
# Block out any script that includes a <script> tag in URL.
RewriteCond %{QUERY_STRING} (<|%3C)([^s]*s)+cript.*(>|%3E) [NC,OR]
# Block out any script trying to set a PHP GLOBALS variable via URL.
RewriteCond %{QUERY_STRING} GLOBALS(=|\[|\%[0-9A-Z]{0,2}) [OR]
# Block out any script trying to modify a _REQUEST variable via URL.
RewriteCond %{QUERY_STRING} _REQUEST(=|\[|\%[0-9A-Z]{0,2})
# Return 403 Forbidden header and show the content of the root homepage
RewriteRule .* index.php [F]
#
## End - Rewrite rules to block out some common exploits.
## Begin - Custom redirects
#
# If you need to redirect some pages, or set a canonical non-www to
# www redirect (or vice versa), place that code here. Ensure those
# redirects use the correct RewriteRule syntax and the [R=301,L] flags.
#
## End - Custom redirects
##
# Uncomment following line if your webserver's URL
# is not directly related to physical file paths.
# Update Your Joomla! Directory (just / for root).
##
# RewriteBase /
## Begin - Joomla! core SEF Section.
#
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
#
# If the requested path and file is not /index.php and the request
# has not already been internally rewritten to the index.php script
RewriteCond %{REQUEST_URI} !^/index\.php
# and the request is for something within the component folder,
# or for the site root, or for an extensionless URL, or the
# requested URL ends with one of the listed extensions
RewriteCond %{REQUEST_URI}
/component/|(/[^.]*|\.(php|html?|feed|pdf|vcf|raw))$ [NC]
# and the requested path and file doesn't directly match a physical file
RewriteCond %{REQUEST_FILENAME} !-f
# and the requested path and file doesn't directly match a physical folder
RewriteCond %{REQUEST_FILENAME} !-d
# internally rewrite the request to the index.php script
RewriteRule .* index.php [L]
#
## End - Joomla! core SEF Section.
Web Server apache mysql
Web Server apache mysql
How are the web servers load balanced.
What modules are used by Apache2.4.
What is the configuration file for PHP.
Any specific configuraton for PHP (not out of the box). Any specific
configuration for CentOS.
Any specific configuration for MySQL.
Are the MySQL instances on the web server? What is the topology.
How are the web servers load balanced.
What modules are used by Apache2.4.
What is the configuration file for PHP.
Any specific configuraton for PHP (not out of the box). Any specific
configuration for CentOS.
Any specific configuration for MySQL.
Are the MySQL instances on the web server? What is the topology.
How fix size's limitation of MultipleLookupField?
How fix size's limitation of MultipleLookupField?
I have a boring problem with MultipleLookupField component of SharePoint
WebControls.
This component allow add items in parallel list, but saves just at maximum
10 items. And saves all items at a string field that has size just 255
characters.
You can see the reported problem right here.
So, I need some solution that is possible add how many items the user put
at list parallel list.
Has any way to increase or remove this limit?
If someone had a similar problem I really appreciate any orientation.
Thanks.
I have a boring problem with MultipleLookupField component of SharePoint
WebControls.
This component allow add items in parallel list, but saves just at maximum
10 items. And saves all items at a string field that has size just 255
characters.
You can see the reported problem right here.
So, I need some solution that is possible add how many items the user put
at list parallel list.
Has any way to increase or remove this limit?
If someone had a similar problem I really appreciate any orientation.
Thanks.
Resizing UIScrollView to fit its content not working
Resizing UIScrollView to fit its content… not working
I have an app that uses a UIScrollView to display content created by
Interface Builder. I add a UITextView to it programmatically because its
content is changeable and I want it to resize. This is done! The problem
comes when resizing the UIScrollView to fit the new UITextView size. I
just can't get it done.. I tried various methods including:
CGRect contentRect = CGRectZero; for (UIView *view in
self.scrollView.subviews) contentRect = CGRectUnion(contentRect,
view.frame); self.scrollView.contentSize = contentRect.size;
I think the problem is because it is built by Interface Builder but the
UIScrollView contains other elements as well so I can't create it
programmatically. I was hoping someone could help me on this.
UPDATE 1: I have both the UIView and the UIScrollView's heights set to
1024 from the Interface Builder.
UPDATE 2 (FIX): I was able to fix this problem by issuing a timer at the
end of the viewDidLoad method like so:
[NSTimer scheduledTimerWithTimeInterval:0.00001 target:self
selector:@selector(resizeScrollView) userInfo:nil repeats:NO]
and then resizing it in the resizeScrollView method here:
-(void)resizeScrollView { CGFloat scrollViewHeight = 0.0f; for (UIView*
view in scrollView.subviews) { scrollViewHeight += view.frame.size.height;
} [scrollView setContentSize:(CGSizeMake(320, scrollViewHeight-50))]; }
Thanks for all the help!
NOTE: This solution was inspired by Maniac One's answer. Thanks!
I have an app that uses a UIScrollView to display content created by
Interface Builder. I add a UITextView to it programmatically because its
content is changeable and I want it to resize. This is done! The problem
comes when resizing the UIScrollView to fit the new UITextView size. I
just can't get it done.. I tried various methods including:
CGRect contentRect = CGRectZero; for (UIView *view in
self.scrollView.subviews) contentRect = CGRectUnion(contentRect,
view.frame); self.scrollView.contentSize = contentRect.size;
I think the problem is because it is built by Interface Builder but the
UIScrollView contains other elements as well so I can't create it
programmatically. I was hoping someone could help me on this.
UPDATE 1: I have both the UIView and the UIScrollView's heights set to
1024 from the Interface Builder.
UPDATE 2 (FIX): I was able to fix this problem by issuing a timer at the
end of the viewDidLoad method like so:
[NSTimer scheduledTimerWithTimeInterval:0.00001 target:self
selector:@selector(resizeScrollView) userInfo:nil repeats:NO]
and then resizing it in the resizeScrollView method here:
-(void)resizeScrollView { CGFloat scrollViewHeight = 0.0f; for (UIView*
view in scrollView.subviews) { scrollViewHeight += view.frame.size.height;
} [scrollView setContentSize:(CGSizeMake(320, scrollViewHeight-50))]; }
Thanks for all the help!
NOTE: This solution was inspired by Maniac One's answer. Thanks!
C# Windows Service won't start
C# Windows Service won't start
When I try to start my c# service it says:"starting" for a second and it
turns back to being "stopped" What can be the problem? I had the same code
before, and it worked but made some changes in the code now and it stopped
working. Here is what I added to my code:
App Config:
<add key="cut-copy" value="copy"/>
Normal code:
private void fileSystemWatcher1_Created(object sender,
System.IO.FileSystemEventArgs e)
{
String cut_copy = ConfigurationManager.AppSettings[@"cut-copy"];
if (cut_copy == "copy")
{
cut = false;
}
else
{
cut = true;
}
if (WaitForFileAvailable(e.FullPath, TimeSpan.FromSeconds(10)))
{
var file = Path.Combine(source, e.Name);
var copy_file = Path.Combine(target, e.Name);
var destination = Path.Combine(target,
Path.ChangeExtension(source, Path.GetExtension(source)));
if (File.Exists(file))// Check to see if the file exists.
{ //If it does delete the file in
the target and copy the one from the source to the
target.
File.Delete(copy_file);
File.Copy(e.FullPath, Path.Combine(target, e.Name));
}
else// If it doesn't, just copy the file.
{
if (cut == true)
{
if (File.Exists(file))// Check to see if the
file exists.
{ //If it does delete the
file in the target and copy the one from the
source to the target.
File.Delete(copy_file);
File.Move(Path.Combine(e.FullPath,
e.Name), target);
}
}
else
{
if (File.Exists(file))// Check to see if the
file exists.
{ //If it does delete the
file in the target and copy the one from the
source to the target.
File.Delete(copy_file);
File.Copy(e.FullPath, Path.Combine(target,
e.Name));
}
}
//under this is more code that didn't change
}
What am I doing wrong?
When I try to start my c# service it says:"starting" for a second and it
turns back to being "stopped" What can be the problem? I had the same code
before, and it worked but made some changes in the code now and it stopped
working. Here is what I added to my code:
App Config:
<add key="cut-copy" value="copy"/>
Normal code:
private void fileSystemWatcher1_Created(object sender,
System.IO.FileSystemEventArgs e)
{
String cut_copy = ConfigurationManager.AppSettings[@"cut-copy"];
if (cut_copy == "copy")
{
cut = false;
}
else
{
cut = true;
}
if (WaitForFileAvailable(e.FullPath, TimeSpan.FromSeconds(10)))
{
var file = Path.Combine(source, e.Name);
var copy_file = Path.Combine(target, e.Name);
var destination = Path.Combine(target,
Path.ChangeExtension(source, Path.GetExtension(source)));
if (File.Exists(file))// Check to see if the file exists.
{ //If it does delete the file in
the target and copy the one from the source to the
target.
File.Delete(copy_file);
File.Copy(e.FullPath, Path.Combine(target, e.Name));
}
else// If it doesn't, just copy the file.
{
if (cut == true)
{
if (File.Exists(file))// Check to see if the
file exists.
{ //If it does delete the
file in the target and copy the one from the
source to the target.
File.Delete(copy_file);
File.Move(Path.Combine(e.FullPath,
e.Name), target);
}
}
else
{
if (File.Exists(file))// Check to see if the
file exists.
{ //If it does delete the
file in the target and copy the one from the
source to the target.
File.Delete(copy_file);
File.Copy(e.FullPath, Path.Combine(target,
e.Name));
}
}
//under this is more code that didn't change
}
What am I doing wrong?
Is there any way so that no one can get source code of application from exe file?
Is there any way so that no one can get source code of application from
exe file?
I want to create a exe file for my java project but the problem is that
anyone can get my application code from exe. Is there any way so that no
one can get source code of application from exe file ?
exe file?
I want to create a exe file for my java project but the problem is that
anyone can get my application code from exe. Is there any way so that no
one can get source code of application from exe file ?
Monday, 9 September 2013
Line chart as a HTML5 control
Line chart as a HTML5 control
I want to develop a line chart as a HTML5 control. The chart should
contain all the values in X and Y axis with bold lines. Someone please
help.
I want to develop a line chart as a HTML5 control. The chart should
contain all the values in X and Y axis with bold lines. Someone please
help.
Return only the longest matches in re.finditer when identifying an Open Reading Frame
Return only the longest matches in re.finditer when identifying an Open
Reading Frame
I am trying to write code that will identify open reading frames in a DNA
sequence. An ORF is defined as a portion of a sequence that starts with
ATG and ends with a stop codon TAG, TAA, or TGA. I have used a look ahead
expression to find overlapping sequences. However, I want only the longest
strings to be printed. For example, if we have:
ATGAAAATGAAATAAGTCGTCGGG
Then only: ATGAAATGAAATAA should be returned. ATGAAATAA should not be
returned.
def find_orfs(sequence, aa):
orfs = []
orfre = '(?=(ATG(?:[ATGC]{3}){%d,}?(?:TAG|TAA|TGA)))' % (aa)
for match in re.finditer(orfre, sequence):
orfs.append(
{'start':match.start(1) + 1, 'stop':match.end(1),\
'stop codon':sequence[match.end(1)-3:match.end(1)],\
'nucleotide length':match.end(1) - match.start(1),\
'amino acid length':(match.end(1) - match.start(1) - 3)/3,\
'reading frame':match.start() % 3})
print match.group(1)
return orfs
Reading Frame
I am trying to write code that will identify open reading frames in a DNA
sequence. An ORF is defined as a portion of a sequence that starts with
ATG and ends with a stop codon TAG, TAA, or TGA. I have used a look ahead
expression to find overlapping sequences. However, I want only the longest
strings to be printed. For example, if we have:
ATGAAAATGAAATAAGTCGTCGGG
Then only: ATGAAATGAAATAA should be returned. ATGAAATAA should not be
returned.
def find_orfs(sequence, aa):
orfs = []
orfre = '(?=(ATG(?:[ATGC]{3}){%d,}?(?:TAG|TAA|TGA)))' % (aa)
for match in re.finditer(orfre, sequence):
orfs.append(
{'start':match.start(1) + 1, 'stop':match.end(1),\
'stop codon':sequence[match.end(1)-3:match.end(1)],\
'nucleotide length':match.end(1) - match.start(1),\
'amino acid length':(match.end(1) - match.start(1) - 3)/3,\
'reading frame':match.start() % 3})
print match.group(1)
return orfs
Load the current page via Ajax in php
Load the current page via Ajax in php
I have a problem on my ajax script and I need to load the page without
refreshing the page. Base on this code.
index.php
<div class="header-page" class="clearfix" role="banner">
<div class="container">
<img src="images/logo.png" />
</div>
</div>
<!-- end of HEADER -->
<form>
<div id="contents">
<div class="main-container">
<div class="container">
<table id="tableID">
<tr class="data-head">
<td>Name</td>
<td>Phase</td>
<td>Money 1</td>
<td>Money 2</td>
<td>Money 3</td>
</tr>
<?php
while ($row = mysql_fetch_row($result, MYSQL_BOTH)) {
$id = $row[0];
$companyname = $row[1];
$client = $row[2];
$package = $row[3];
$payment1 = $row[4];
$payment2 = $row[5];
$payment3 = $row[6];
echo '<tr id="'.$id.'">';
echo '<td><b>'.$client.'</b></td>';
echo '<td>';
echo '<select class="phase"
onchange="trackPhases(this.value)">';
if($phase_status=='Design'){
echo '<option value="'.$phase_status.''.$id.'"
selected>'.$phase_status.'</option>';
echo '<option
value="Build-Out'.$id.'">Build-Out</option>';
echo '<option
value="Launch'.$id.'">Launch</option>';
}
if($phase_status=='Build-Out'){
echo '<option
value="Design'.$id.'">Design</option>';
echo '<option value="'.$phase_status.''.$id.'"
selected>'.$phase_status.'</option>';
echo '<option
value="Launch'.$id.'">Launch</option>';
}
if($phase_status=='Launch'){
echo '<option
value="Design'.$id.'">Design</option>';
echo '<option
value="Build-Out'.$id.'">Build-Out</option>';
echo '<option value="'.$phase_status.''.$id.'"
selected>'.$phase_status.'</option>';
}
echo '</select>';
echo '</td>';
echo '</tr>';
}
?>
</table>
</div>
</div>
</div>
</form>
<div id="txtHint"></div>
And this is my Ajax script. I created a dropdown control(just a sample) on
the html table code. When I select a value on the dropdown -- select
class="phase" onchange="trackPhases(this.value), it should automatically
load the page via Ajax not a refresh.
<script type="text/javascript">
function trackPhases(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
//xmlhttp.open("GET","index.php?q="+str,true);
//xmlhttp.send();
}
My index.php is fine though. But there is something wrong with my Ajax
script. Please help me.
EDIT:
<?php
mysql_connect("localhost", "xx", "password");
mysql_select_db('database');
$query = "SELECT * FROM project";
$result = mysql_query($query);
?>
EDIT
EDIT update.php
<?php
mysql_connect("localhost", "xx", "password");
mysql_select_db('database');
$query = "SELECT * FROM project";
$result = mysql_query($query);
$q = $_GET['q'];
$id = ereg_replace("[^0-9]", "",$q);
$phase_status = preg_replace('/[0-9]+/', '', $q);
$sql = 'UPDATE project_entry SET phase_status="'.$phase_status.'" WHERE
id = '.$id;
$retval = mysql_query($sql);
if(! $retval ){
die('Could not update data: ' . mysql_error());
}
?>
I have a problem on my ajax script and I need to load the page without
refreshing the page. Base on this code.
index.php
<div class="header-page" class="clearfix" role="banner">
<div class="container">
<img src="images/logo.png" />
</div>
</div>
<!-- end of HEADER -->
<form>
<div id="contents">
<div class="main-container">
<div class="container">
<table id="tableID">
<tr class="data-head">
<td>Name</td>
<td>Phase</td>
<td>Money 1</td>
<td>Money 2</td>
<td>Money 3</td>
</tr>
<?php
while ($row = mysql_fetch_row($result, MYSQL_BOTH)) {
$id = $row[0];
$companyname = $row[1];
$client = $row[2];
$package = $row[3];
$payment1 = $row[4];
$payment2 = $row[5];
$payment3 = $row[6];
echo '<tr id="'.$id.'">';
echo '<td><b>'.$client.'</b></td>';
echo '<td>';
echo '<select class="phase"
onchange="trackPhases(this.value)">';
if($phase_status=='Design'){
echo '<option value="'.$phase_status.''.$id.'"
selected>'.$phase_status.'</option>';
echo '<option
value="Build-Out'.$id.'">Build-Out</option>';
echo '<option
value="Launch'.$id.'">Launch</option>';
}
if($phase_status=='Build-Out'){
echo '<option
value="Design'.$id.'">Design</option>';
echo '<option value="'.$phase_status.''.$id.'"
selected>'.$phase_status.'</option>';
echo '<option
value="Launch'.$id.'">Launch</option>';
}
if($phase_status=='Launch'){
echo '<option
value="Design'.$id.'">Design</option>';
echo '<option
value="Build-Out'.$id.'">Build-Out</option>';
echo '<option value="'.$phase_status.''.$id.'"
selected>'.$phase_status.'</option>';
}
echo '</select>';
echo '</td>';
echo '</tr>';
}
?>
</table>
</div>
</div>
</div>
</form>
<div id="txtHint"></div>
And this is my Ajax script. I created a dropdown control(just a sample) on
the html table code. When I select a value on the dropdown -- select
class="phase" onchange="trackPhases(this.value), it should automatically
load the page via Ajax not a refresh.
<script type="text/javascript">
function trackPhases(str)
{
if (str=="")
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
//xmlhttp.open("GET","index.php?q="+str,true);
//xmlhttp.send();
}
My index.php is fine though. But there is something wrong with my Ajax
script. Please help me.
EDIT:
<?php
mysql_connect("localhost", "xx", "password");
mysql_select_db('database');
$query = "SELECT * FROM project";
$result = mysql_query($query);
?>
EDIT
EDIT update.php
<?php
mysql_connect("localhost", "xx", "password");
mysql_select_db('database');
$query = "SELECT * FROM project";
$result = mysql_query($query);
$q = $_GET['q'];
$id = ereg_replace("[^0-9]", "",$q);
$phase_status = preg_replace('/[0-9]+/', '', $q);
$sql = 'UPDATE project_entry SET phase_status="'.$phase_status.'" WHERE
id = '.$id;
$retval = mysql_query($sql);
if(! $retval ){
die('Could not update data: ' . mysql_error());
}
?>
$(this).sortable("serialize"); yields (an empty string)
$(this).sortable("serialize"); yields (an empty string)
I'm trying to save the state of the widgets upon adjusting them both
vertically or horizontally. When I use sortable("serialize") it yields
empty string. Where I'm going wrong?
My application opens a dialog box from where the widgets are selected. The
selected widgets are posted via ajax and the widgets appear properly but
upon adjusting them and using sortable("serialize") yields empty string.
Here is my code
$(function() {
$( ".column" ).sortable({
connectWith: ".column",
handle: ".portlet-header",
update : function(event, ui) {
var postData = $(this).sortable("serialize");
console.log(postData);
}
});
});
views.py
widgets_list = request.POST.getlist('widgets_list[]')
widget_header = ""
height = ""
content = ""
HTMLstr = ""
for widget in widgets_list:
if widget == "widget_liveGraph":
widget_header = "Live Graph"
content = ""
height = "270px"
elif widget == "widget_weather":
widget_header = "Weather"
content = "<script type='text/javascript'
src='http://voap.weather.com/weather/oap/INXX0012?template=GENXH&par=3000000007&unit=1&key=twciweatherwidget'></script>"
height = "auto"
elif widget == "widget_productivityEnergyUse":
widget_header = "Productivity Energy Use"
content = "<br><br> Per sq. feet :- <b>10
</b><br><br>" + \
"Per Occupants :- <b>1000</b>"
height = "auto"
elif widget == "widget_power":
widget_header = "Power"
content = "<br><br> <b>102</b> kW<br><br>"
height = "auto"
HTMLstr += "<div class='portlet ui-widget
ui-widget-content ui-helper-clearfix ui-corner-all'>"+ \
"<div class='portlet-header ui-widget-header
ui-corner-all'><span class='ui-icon
ui-icon-minusthick'>"+\
"</span>" + widget_header + "</div>" + \
"<div class='portlet-content' id="+ widget+"
style='height:"+ height + "; margin: 0 auto;'>" +
content + \
"</div></div>"
return HttpResponse(HTMLstr)
PS: I've also used the correct naming conventions in case of assigning
id's to the div elements , ie id = widget_productivityEnergyUse,
widget_power and so on.
Where I'm going wrong?
I'm trying to save the state of the widgets upon adjusting them both
vertically or horizontally. When I use sortable("serialize") it yields
empty string. Where I'm going wrong?
My application opens a dialog box from where the widgets are selected. The
selected widgets are posted via ajax and the widgets appear properly but
upon adjusting them and using sortable("serialize") yields empty string.
Here is my code
$(function() {
$( ".column" ).sortable({
connectWith: ".column",
handle: ".portlet-header",
update : function(event, ui) {
var postData = $(this).sortable("serialize");
console.log(postData);
}
});
});
views.py
widgets_list = request.POST.getlist('widgets_list[]')
widget_header = ""
height = ""
content = ""
HTMLstr = ""
for widget in widgets_list:
if widget == "widget_liveGraph":
widget_header = "Live Graph"
content = ""
height = "270px"
elif widget == "widget_weather":
widget_header = "Weather"
content = "<script type='text/javascript'
src='http://voap.weather.com/weather/oap/INXX0012?template=GENXH&par=3000000007&unit=1&key=twciweatherwidget'></script>"
height = "auto"
elif widget == "widget_productivityEnergyUse":
widget_header = "Productivity Energy Use"
content = "<br><br> Per sq. feet :- <b>10
</b><br><br>" + \
"Per Occupants :- <b>1000</b>"
height = "auto"
elif widget == "widget_power":
widget_header = "Power"
content = "<br><br> <b>102</b> kW<br><br>"
height = "auto"
HTMLstr += "<div class='portlet ui-widget
ui-widget-content ui-helper-clearfix ui-corner-all'>"+ \
"<div class='portlet-header ui-widget-header
ui-corner-all'><span class='ui-icon
ui-icon-minusthick'>"+\
"</span>" + widget_header + "</div>" + \
"<div class='portlet-content' id="+ widget+"
style='height:"+ height + "; margin: 0 auto;'>" +
content + \
"</div></div>"
return HttpResponse(HTMLstr)
PS: I've also used the correct naming conventions in case of assigning
id's to the div elements , ie id = widget_productivityEnergyUse,
widget_power and so on.
Where I'm going wrong?
What is the best way to add server variables (PHP) in to the Backbone.model using require.js?
What is the best way to add server variables (PHP) in to the
Backbone.model using require.js?
I'm not sure what is the elegant way to pass server variables in to my Model.
For example, i have an id of user that has to be implemented on my Model.
But seems like Backbone with require are not able to do that.
My two options are:
Get a json file with Ajax.
Add the variable on my index.php as a global.
Someone know if exists a other way. Native on the clases?
Backbone.model using require.js?
I'm not sure what is the elegant way to pass server variables in to my Model.
For example, i have an id of user that has to be implemented on my Model.
But seems like Backbone with require are not able to do that.
My two options are:
Get a json file with Ajax.
Add the variable on my index.php as a global.
Someone know if exists a other way. Native on the clases?
javascript array/object.push not working
javascript array/object.push not working
input:
var variants = [];
$("div.product[data-variant]").each(function() {
variants = [{name:chocolate, url:http://urltochocolate.de;
});
output:
$.each(optionList, function (i, el) {
combo.append('<option value="'+ el.url +'">' + el.name + "</option>");
});
the above version works, but if i want to save all variants not only the
last by adding a variants.push it won't work. i know push is an array
function but how does it work for JS objects? or does a push work but then
i use the wrong output function?
any help appreciated, it can't be so difficult, just not seeing the
solution :(
input:
var variants = [];
$("div.product[data-variant]").each(function() {
variants = [{name:chocolate, url:http://urltochocolate.de;
});
output:
$.each(optionList, function (i, el) {
combo.append('<option value="'+ el.url +'">' + el.name + "</option>");
});
the above version works, but if i want to save all variants not only the
last by adding a variants.push it won't work. i know push is an array
function but how does it work for JS objects? or does a push work but then
i use the wrong output function?
any help appreciated, it can't be so difficult, just not seeing the
solution :(
Google play: "Item not found" error on installing application to android 2.x device
Google play: "Item not found" error on installing application to android
2.x device
My application uses module SDK Android 4.2.2 Platform, but in
AndroidManifest.xml I have
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16" />
I am using google-play-services-lib in my application and Google Maps API V2.
I am using tester's account to login to Google Play and try to install my
apk (status - alpha) to android 2.3 device and get "Item not found error"
when clicking to "Upload from Google Play" button, but this app installs
well to android 4.x devices. On the other hand, I can install it on all
devices (android 2.x devices included) from USB or using
http://testflightapp.com.
My device included to supported devices list on Google Play, API level 8+.
Can anyone suggest any possible causes for this error? Many thanks.
2.x device
My application uses module SDK Android 4.2.2 Platform, but in
AndroidManifest.xml I have
<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="16" />
I am using google-play-services-lib in my application and Google Maps API V2.
I am using tester's account to login to Google Play and try to install my
apk (status - alpha) to android 2.3 device and get "Item not found error"
when clicking to "Upload from Google Play" button, but this app installs
well to android 4.x devices. On the other hand, I can install it on all
devices (android 2.x devices included) from USB or using
http://testflightapp.com.
My device included to supported devices list on Google Play, API level 8+.
Can anyone suggest any possible causes for this error? Many thanks.
Sunday, 8 September 2013
Speech Recognizer Sound
Speech Recognizer Sound
I am using the Speech Recognizer Intent to take User Input and translate
it into text. However I want the Intent to continuously take user input
and translate it into text to see if the user and said a certain word. My
Code is able to do that, but every time my app begins listening for input,
the phone makes a short beep sound that it is ready for input.
I was wondering if there is any way to delete the sound from playing every
time the recognizer is ready to listen again.
Here is my code:
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity implements OnClickListener
{
//private TextView mText;
private SpeechRecognizer sr;
private static final String TAG = "MyStt3Activity";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ToggleButton speakButton = (ToggleButton)
findViewById(R.id.CarMode);
//mText = (TextView) findViewById(R.id.textView1);
speakButton.setOnClickListener(this);
sr = SpeechRecognizer.createSpeechRecognizer(this);
sr.setRecognitionListener(new listener());
}
class listener implements RecognitionListener
{
public void onReadyForSpeech(Bundle params)
{
Log.d(TAG, "onReadyForSpeech");
}
public void onBeginningOfSpeech()
{
Log.d(TAG, "onBeginningOfSpeech");
}
public void onRmsChanged(float rmsdB)
{
Log.d(TAG, "onRmsChanged");
}
public void onBufferReceived(byte[] buffer)
{
Log.d(TAG, "onBufferReceived");
}
public void onEndOfSpeech()
{
Log.d(TAG, "onEndofSpeech");
}
public void onError(int error)
{
Log.d(TAG, "error " + error);
Toast.makeText(getApplicationContext(), "What was
that?", Toast.LENGTH_SHORT).show();
sr.cancel();
speechIntent();
}
public void onResults(Bundle results)
{
//String str = new String();
Log.d(TAG, "onResults " + results);
ArrayList<String> data =
results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
Toast.makeText(getApplicationContext(),
data.get(0), Toast.LENGTH_SHORT).show();
sr.cancel();
speechIntent();
//mText.setText("results:
"+String.valueOf(data.size()));
}
public void onPartialResults(Bundle partialResults)
{
Log.d(TAG, "onPartialResults");
}
public void onEvent(int eventType, Bundle params)
{
Log.d(TAG, "onEvent " + eventType);
}
}
public void onClick(View v) {
if (v.getId() == R.id.CarMode)
{
speechIntent();
}
}
public void speechIntent()
{
Intent intent = new
Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"com.example.freestyleandroid");
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5);
sr.startListening(intent);
Log.i("111111","11111111");
}
}
I am using the Speech Recognizer Intent to take User Input and translate
it into text. However I want the Intent to continuously take user input
and translate it into text to see if the user and said a certain word. My
Code is able to do that, but every time my app begins listening for input,
the phone makes a short beep sound that it is ready for input.
I was wondering if there is any way to delete the sound from playing every
time the recognizer is ready to listen again.
Here is my code:
import java.util.ArrayList;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognitionListener;
import android.speech.RecognizerIntent;
import android.speech.SpeechRecognizer;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.widget.ToggleButton;
public class MainActivity extends Activity implements OnClickListener
{
//private TextView mText;
private SpeechRecognizer sr;
private static final String TAG = "MyStt3Activity";
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ToggleButton speakButton = (ToggleButton)
findViewById(R.id.CarMode);
//mText = (TextView) findViewById(R.id.textView1);
speakButton.setOnClickListener(this);
sr = SpeechRecognizer.createSpeechRecognizer(this);
sr.setRecognitionListener(new listener());
}
class listener implements RecognitionListener
{
public void onReadyForSpeech(Bundle params)
{
Log.d(TAG, "onReadyForSpeech");
}
public void onBeginningOfSpeech()
{
Log.d(TAG, "onBeginningOfSpeech");
}
public void onRmsChanged(float rmsdB)
{
Log.d(TAG, "onRmsChanged");
}
public void onBufferReceived(byte[] buffer)
{
Log.d(TAG, "onBufferReceived");
}
public void onEndOfSpeech()
{
Log.d(TAG, "onEndofSpeech");
}
public void onError(int error)
{
Log.d(TAG, "error " + error);
Toast.makeText(getApplicationContext(), "What was
that?", Toast.LENGTH_SHORT).show();
sr.cancel();
speechIntent();
}
public void onResults(Bundle results)
{
//String str = new String();
Log.d(TAG, "onResults " + results);
ArrayList<String> data =
results.getStringArrayList(SpeechRecognizer.RESULTS_RECOGNITION);
Toast.makeText(getApplicationContext(),
data.get(0), Toast.LENGTH_SHORT).show();
sr.cancel();
speechIntent();
//mText.setText("results:
"+String.valueOf(data.size()));
}
public void onPartialResults(Bundle partialResults)
{
Log.d(TAG, "onPartialResults");
}
public void onEvent(int eventType, Bundle params)
{
Log.d(TAG, "onEvent " + eventType);
}
}
public void onClick(View v) {
if (v.getId() == R.id.CarMode)
{
speechIntent();
}
}
public void speechIntent()
{
Intent intent = new
Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,"com.example.freestyleandroid");
intent.putExtra(RecognizerIntent.EXTRA_MAX_RESULTS,5);
sr.startListening(intent);
Log.i("111111","11111111");
}
}
Issue with creating an jQuery plugin without selector
Issue with creating an jQuery plugin without selector
I'm working on a jQuery plugin which does not require a selector so I'm
just adding it to the global jQuery namespace.
I'm having issues with sharing internal instance variables between my
plugin's public methods. For example, I would like to be able to access
$.MyPlugin.settings from the .init method.
Here's the plugin code:
(function($) {
$.MyPlugin = function(options) {
var defaults = {
username: '',
password: ''
}
var plugin = this;
plugin.settings = {};
plugin.init = function() {
plugin.settings = $.extend({}, defaults, options);
}
plugin.init();
}
$.MyPlugin.init = function(callback) {
console.log(this.settings); // undefined
callback();
}
}(jQuery));
In main.js, I have:
$(document).ready(function() {
$.MyPlugin({
username: 'myuser',
password: 'mypass'
});
$.MyPlugin.init(function() {
console.log('hi');
});
This returns:
undefined
hi
I'm working on a jQuery plugin which does not require a selector so I'm
just adding it to the global jQuery namespace.
I'm having issues with sharing internal instance variables between my
plugin's public methods. For example, I would like to be able to access
$.MyPlugin.settings from the .init method.
Here's the plugin code:
(function($) {
$.MyPlugin = function(options) {
var defaults = {
username: '',
password: ''
}
var plugin = this;
plugin.settings = {};
plugin.init = function() {
plugin.settings = $.extend({}, defaults, options);
}
plugin.init();
}
$.MyPlugin.init = function(callback) {
console.log(this.settings); // undefined
callback();
}
}(jQuery));
In main.js, I have:
$(document).ready(function() {
$.MyPlugin({
username: 'myuser',
password: 'mypass'
});
$.MyPlugin.init(function() {
console.log('hi');
});
This returns:
undefined
hi
How is monitor acquired in case of static function?
How is monitor acquired in case of static function?
According to JLS Section §8.4.3.6:
A synchronized method acquires a monitor (§17.1) before it executes.
For a class (static) method, the monitor associated with the Class object
for the method's class is used.
In this synchronized method move class level lock is acquired. So which
Class object is exactly used for obtaining this lock. Is it
Interface.class or ClassImplementingInterface.class? If it is the later is
there any scenario where we can have interface monitors? or rather does
interface have a monitor?
I have read each object is associated with a monitor and in case of static
locks monitor is obtained on corresponding Class object. As we can do
Interface.Class which means interface has corresponding Class object can
we get a lock on that monitor without explicitly saying
synchronized(Interface.class).
According to JLS Section §8.4.3.6:
A synchronized method acquires a monitor (§17.1) before it executes.
For a class (static) method, the monitor associated with the Class object
for the method's class is used.
In this synchronized method move class level lock is acquired. So which
Class object is exactly used for obtaining this lock. Is it
Interface.class or ClassImplementingInterface.class? If it is the later is
there any scenario where we can have interface monitors? or rather does
interface have a monitor?
I have read each object is associated with a monitor and in case of static
locks monitor is obtained on corresponding Class object. As we can do
Interface.Class which means interface has corresponding Class object can
we get a lock on that monitor without explicitly saying
synchronized(Interface.class).
In C#, how can I pick between two items?
In C#, how can I pick between two items?
This may have been asked before, but if it has I can't find it. I'm
writing a small game where sums are randomly generated for the user to
answer, and correct + incorrect answers are counted. It works thus far,
but I wish to implement a system where the game randomly picks between +,
-, / and * symbols between the two randomly picked numbers and then,
depending on which was picked, changes the way the correct answer is
calculated. For a better idea, here is my current relevant code:
public void makeNewSum()
{
var randomNum = new Random();
num1 = randomNum.Next(0, 10);
num2 = randomNum.Next(0, 10);
answer = num1 + num2;
label1.Text = num1.ToString() + " + " + num2.ToString() + " = ";
txtAnswer.Text = "";
txtAnswer.Focus();
The item 'label1' is where the sum that must be answered is displayed,
though you can probably tell. What I'm trying to figure out is how I can
tell it to choose between " + ", " - ", " / " and " * " where it currently
always says " + ", and then change the variable 'answer' to reflect the
symbol chosen. I was planning to use if statements to reflect the choice
of symbol, but I'm lost for how to have it choose between them in the
first place. Help is greatly appreciated!
This may have been asked before, but if it has I can't find it. I'm
writing a small game where sums are randomly generated for the user to
answer, and correct + incorrect answers are counted. It works thus far,
but I wish to implement a system where the game randomly picks between +,
-, / and * symbols between the two randomly picked numbers and then,
depending on which was picked, changes the way the correct answer is
calculated. For a better idea, here is my current relevant code:
public void makeNewSum()
{
var randomNum = new Random();
num1 = randomNum.Next(0, 10);
num2 = randomNum.Next(0, 10);
answer = num1 + num2;
label1.Text = num1.ToString() + " + " + num2.ToString() + " = ";
txtAnswer.Text = "";
txtAnswer.Focus();
The item 'label1' is where the sum that must be answered is displayed,
though you can probably tell. What I'm trying to figure out is how I can
tell it to choose between " + ", " - ", " / " and " * " where it currently
always says " + ", and then change the variable 'answer' to reflect the
symbol chosen. I was planning to use if statements to reflect the choice
of symbol, but I'm lost for how to have it choose between them in the
first place. Help is greatly appreciated!
Subscribe to:
Posts (Atom)