freeze on [xxx.xxx] INFO: rcu_sched self-detected stall on CPU
I'm running Ubuntu 13.04 64bit (kernel: 3.11.1) on VMWare Player 6 as
guest (Host machine Windows 8.1), and 5 minutes later after I start the
virtual machine I receive the following system messages, the system freeze
and I must restart the guest machine!
[xxx.xxx] INFO: rcu_sched self-detected stall on CPU
Monday, 30 September 2013
Combinatorial proof of nth power identity
Combinatorial proof of nth power identity
Prove $1+{n \choose 1}2+{n \choose 2}4+...+{n \choose n-1}2^{n-1}+{n
\choose n}2^n=3^n$ using combinatorial arguments. I have no idea how to
begin solving this, a nudge in the right direction would be appreciated.
Prove $1+{n \choose 1}2+{n \choose 2}4+...+{n \choose n-1}2^{n-1}+{n
\choose n}2^n=3^n$ using combinatorial arguments. I have no idea how to
begin solving this, a nudge in the right direction would be appreciated.
Javascript menu bar
Javascript menu bar
I need a menu bar like http://wallbase.cc for education purpose. I already
tried it myself and failed Sad Does anyone have a script like that for me
to look in?
I need a menu bar like http://wallbase.cc for education purpose. I already
tried it myself and failed Sad Does anyone have a script like that for me
to look in?
IntelliJ IDEA Community Edition supports features of Ultimate?
IntelliJ IDEA Community Edition supports features of Ultimate?
I know that Community ediition doesn't support certain features of
Ultimate but I want to know that there is NO way to make these features to
run in anyway. For example, the Enterprise development (e.g. Tomcat,
Glassfish, Oracle, etc.) or Web development (e.g. Spring, HTML5, etc. ).
So, if I have to run these kind of development somehow can I succeed in
doing these things only with the Community edition or I am locked and not
able to do such things. Say, I don't have the luxury to go to Ultimate for
some reason.
I know that Community ediition doesn't support certain features of
Ultimate but I want to know that there is NO way to make these features to
run in anyway. For example, the Enterprise development (e.g. Tomcat,
Glassfish, Oracle, etc.) or Web development (e.g. Spring, HTML5, etc. ).
So, if I have to run these kind of development somehow can I succeed in
doing these things only with the Community edition or I am locked and not
able to do such things. Say, I don't have the luxury to go to Ultimate for
some reason.
Sunday, 29 September 2013
How to you export a predictive model from R to Excel?
How to you export a predictive model from R to Excel?
I'm curious how to export a predictive model from R into Excel so that it
can be distributed to others to use. A linear model would be easy(take the
coefficients), but something more complex like a neural net or boost
regression would be more difficult. I've read about the PMML package and
how it exports the model into XML, but I'm not sure how this would be
implemented into Excel.
Thanks
I'm curious how to export a predictive model from R into Excel so that it
can be distributed to others to use. A linear model would be easy(take the
coefficients), but something more complex like a neural net or boost
regression would be more difficult. I've read about the PMML package and
how it exports the model into XML, but I'm not sure how this would be
implemented into Excel.
Thanks
php replace string or explode() function
php replace string or explode() function
I have a link in format like
http://example.com/a/b.swf
I want to to convert it to
http://cache.example.com/a/b.swf
How can I do it?
I tried it with PHP's explode() function but when I explode some part of
string, then I add it to itself it does not work.
I have a link in format like
http://example.com/a/b.swf
I want to to convert it to
http://cache.example.com/a/b.swf
How can I do it?
I tried it with PHP's explode() function but when I explode some part of
string, then I add it to itself it does not work.
NETBEANS PL/SQL - INSERT RECORD ONLY IF RECORD DOES NOT EXIST
NETBEANS PL/SQL - INSERT RECORD ONLY IF RECORD DOES NOT EXIST
I got no good answers to my question, found out how to do it. This is how
you would insert a record to a table only if the record does not already
exist:
Create or Replace function on your schema (this is checking 2 parameters,
you can set it to check as many as you wish) PL/SQL is very specific ,
copying and pasting as I have written should compile successfully. It took
many tries to get the syntax just right. This function checks the Table to
be written to, and the corresponding column names to be checked if they
already exist together.
create or replace function Found(var1 type, var2 type)return number is
numberOfSelectedRows number := 0;
begin select count(*) into numberOfSelectedRows from TABLE where
COLUMN_NAME = var1 and COLUMN_NAME = var2;
return numberOfSelectedRows;
end Found;
========================================================================================
2. Write the java to execute the pl/sql function: this is done with
NetBeans. When the button is clicked, it takes FORM data- loaded from
other tables, and determines whether or not the record already exists in
the table to be inserted into.
try {
DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
con = DriverManager.getConnection(""+LOGIN.url+"");
String str1 = jTextField_VariableName.getText();
String str2 = jTextField_VariableName.getText();
String q = "insert into TABLE (var1 type, var2 type) VALUES
('"+str1+"', '"+str2+"')" ;
cs = con.prepareCall("{?=call Found(?, ?)}"); // cs =
CallableStatement - defined in class CallableStatement cs = null;
cs.setString(2, str1);
cs.setString(3, str2);
cs.registerOutParameter(1, Types.INTEGER);
cs.execute();
if(cs.getInt(1)>= 1)
{
JOptionPane.showMessageDialog(null, " this record already
exists");
}
else
{
try{
DriverManager.registerDriver (new
oracle.jdbc.OracleDriver());
con = DriverManager.getConnection(""+LOGIN.url+"");
pst = con.prepareStatement(q);
pst.execute();
}catch(SQLException ex)
{Logger.getLogger(REGISTER_STUDENT.class.getName()).log(Level.SEVERE,
null, ex);}
}
} catch (SQLException ex)
{Logger.getLogger(REGISTER_STUDENT.class.getName()).log(Level.SEVERE,
null, ex);}
I got no good answers to my question, found out how to do it. This is how
you would insert a record to a table only if the record does not already
exist:
Create or Replace function on your schema (this is checking 2 parameters,
you can set it to check as many as you wish) PL/SQL is very specific ,
copying and pasting as I have written should compile successfully. It took
many tries to get the syntax just right. This function checks the Table to
be written to, and the corresponding column names to be checked if they
already exist together.
create or replace function Found(var1 type, var2 type)return number is
numberOfSelectedRows number := 0;
begin select count(*) into numberOfSelectedRows from TABLE where
COLUMN_NAME = var1 and COLUMN_NAME = var2;
return numberOfSelectedRows;
end Found;
========================================================================================
2. Write the java to execute the pl/sql function: this is done with
NetBeans. When the button is clicked, it takes FORM data- loaded from
other tables, and determines whether or not the record already exists in
the table to be inserted into.
try {
DriverManager.registerDriver (new oracle.jdbc.OracleDriver());
con = DriverManager.getConnection(""+LOGIN.url+"");
String str1 = jTextField_VariableName.getText();
String str2 = jTextField_VariableName.getText();
String q = "insert into TABLE (var1 type, var2 type) VALUES
('"+str1+"', '"+str2+"')" ;
cs = con.prepareCall("{?=call Found(?, ?)}"); // cs =
CallableStatement - defined in class CallableStatement cs = null;
cs.setString(2, str1);
cs.setString(3, str2);
cs.registerOutParameter(1, Types.INTEGER);
cs.execute();
if(cs.getInt(1)>= 1)
{
JOptionPane.showMessageDialog(null, " this record already
exists");
}
else
{
try{
DriverManager.registerDriver (new
oracle.jdbc.OracleDriver());
con = DriverManager.getConnection(""+LOGIN.url+"");
pst = con.prepareStatement(q);
pst.execute();
}catch(SQLException ex)
{Logger.getLogger(REGISTER_STUDENT.class.getName()).log(Level.SEVERE,
null, ex);}
}
} catch (SQLException ex)
{Logger.getLogger(REGISTER_STUDENT.class.getName()).log(Level.SEVERE,
null, ex);}
declare a variable Column based on a cover sheet
declare a variable Column based on a cover sheet
Dim iRow As Long
Dim CopyRange As String
iRow = (ActiveCell.Row)
Let CopyRange = "M" & iRow & ":" & "T" & iRow
Range(CopyRange).ClearContents
i have this code and i need to declare the second part of CopyRange ("T" &
iRow) as a variable based on my cover sheet.
Columns M to X respresent the 12 months, so whenever i change the cover
sheet to Septemper for example an Input sheet changes the value to 9, so
when i use the choose methods it chooses current month which is column U
in this case.
what i need to do is to clear all content but current month when i change
the cover, column M (jan) to column T (Aug), in this case.
i've been thinking of something like this:
Sheets("Inputs").Range("H3") = C
Let CopyRange = "M" & iRow
let iCopyRange = C-1 & iRow
Cells (CopyRange, iCopyRange).ClearContents
its kinda weird !!
Dim iRow As Long
Dim CopyRange As String
iRow = (ActiveCell.Row)
Let CopyRange = "M" & iRow & ":" & "T" & iRow
Range(CopyRange).ClearContents
i have this code and i need to declare the second part of CopyRange ("T" &
iRow) as a variable based on my cover sheet.
Columns M to X respresent the 12 months, so whenever i change the cover
sheet to Septemper for example an Input sheet changes the value to 9, so
when i use the choose methods it chooses current month which is column U
in this case.
what i need to do is to clear all content but current month when i change
the cover, column M (jan) to column T (Aug), in this case.
i've been thinking of something like this:
Sheets("Inputs").Range("H3") = C
Let CopyRange = "M" & iRow
let iCopyRange = C-1 & iRow
Cells (CopyRange, iCopyRange).ClearContents
its kinda weird !!
Saturday, 28 September 2013
handler throws NullPointerException after initialtion
handler throws NullPointerException after initialtion
Here is the key code:
public class ChooseFileDialog extends DMBaseConfirmDialog {
public static final int ALL_FILES_READY = 1;
public static final int LIST_FILES = ALL_FILES_READY + 1;
private FileListView listView = null;
private EditText searchContact = null;
private List<FileDescripter> fileDescripters = null;
private DMHandler handler = null;
public ChooseFileDialog(Context context, int theme) {
super(context, theme);
}
private void init(Context context) {
handler = new DMHandler(context) {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case ALL_FILES_READY:
System.out.println("listView ready?" + listView);
// listView.getAdapter().addItems(fileDescripters);
break;
case LIST_FILES:
// String path = (String) msg.obj;
// listView.getAdapter().clearItems();
// listFiles(new File(path));
break;
default:
break;
}
super.handleMessage(msg);
}
};
System.out.println("list files");
listFiles(new File("/"));
}
private void listFiles(final File path) {
System.out.println("handler1:" + handler);
new Thread() {
@Override
public void run() {
fileDescripters = new ArrayList<FileDescripter>();
File[] files = path.listFiles();
File parent;
if ((parent = path.getParentFile()) != null) {
fileDescripters.add(new FileDescripter(parent));
}
if (files != null)
for (File file : files) {
fileDescripters.add(new FileDescripter(file));
}
System.out.println("handler run:" + handler);
handler.sendEmptyMessage(ALL_FILES_READY);
}
}.start();
}
@Override
protected void updateView(View root, Context context) {
listView = (FileListView) root.findViewById(R.id.file_list_view);
System.out.println("listview 1:" + listView);
searchContact = (EditText) root.findViewById(R.id.search_file);
searchContact.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
List<FileDescripter> searchsContacts =
searchContacts(searchContact
.getText().toString().trim());
listView.getAdapter().clearItems();
listView.getAdapter().addItems(searchsContacts);
}
});
init(context);
}
super(context, theme); will call updateView(View root, Context context)
after initiating the views, init(context) will be called to initiate handler
then listFiles will be called
strangely, from the log :
09-29 10:00:27.900: I/System.out(4554): handler1:Handler
09-29 10:00:27.965: I/System.out(4554): handler run:null
how the handler could be null after initiation.
Here is the key code:
public class ChooseFileDialog extends DMBaseConfirmDialog {
public static final int ALL_FILES_READY = 1;
public static final int LIST_FILES = ALL_FILES_READY + 1;
private FileListView listView = null;
private EditText searchContact = null;
private List<FileDescripter> fileDescripters = null;
private DMHandler handler = null;
public ChooseFileDialog(Context context, int theme) {
super(context, theme);
}
private void init(Context context) {
handler = new DMHandler(context) {
@Override
public void handleMessage(Message msg) {
switch (msg.what) {
case ALL_FILES_READY:
System.out.println("listView ready?" + listView);
// listView.getAdapter().addItems(fileDescripters);
break;
case LIST_FILES:
// String path = (String) msg.obj;
// listView.getAdapter().clearItems();
// listFiles(new File(path));
break;
default:
break;
}
super.handleMessage(msg);
}
};
System.out.println("list files");
listFiles(new File("/"));
}
private void listFiles(final File path) {
System.out.println("handler1:" + handler);
new Thread() {
@Override
public void run() {
fileDescripters = new ArrayList<FileDescripter>();
File[] files = path.listFiles();
File parent;
if ((parent = path.getParentFile()) != null) {
fileDescripters.add(new FileDescripter(parent));
}
if (files != null)
for (File file : files) {
fileDescripters.add(new FileDescripter(file));
}
System.out.println("handler run:" + handler);
handler.sendEmptyMessage(ALL_FILES_READY);
}
}.start();
}
@Override
protected void updateView(View root, Context context) {
listView = (FileListView) root.findViewById(R.id.file_list_view);
System.out.println("listview 1:" + listView);
searchContact = (EditText) root.findViewById(R.id.search_file);
searchContact.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
@Override
public void afterTextChanged(Editable s) {
List<FileDescripter> searchsContacts =
searchContacts(searchContact
.getText().toString().trim());
listView.getAdapter().clearItems();
listView.getAdapter().addItems(searchsContacts);
}
});
init(context);
}
super(context, theme); will call updateView(View root, Context context)
after initiating the views, init(context) will be called to initiate handler
then listFiles will be called
strangely, from the log :
09-29 10:00:27.900: I/System.out(4554): handler1:Handler
09-29 10:00:27.965: I/System.out(4554): handler run:null
how the handler could be null after initiation.
How to get indexes for values in array
How to get indexes for values in array
I need to write a function that takes as argument 2d array. Each element
of array has an Integer value. As input i have a 2D array for example:
[1][1][2][2]
[2][1][2][2]
[3][3][3][3]
[22][.......
and as output I need to store indexes for each value :
value = 1 : [0,0] ; [0,1] ; [ 1,1]
value = 2 : [1,0] ; ....
value = 3 : [2,0] ; .......
value = 22 : [.........
Size of array may be various, same as number of values. Is it somehow
possible to save that data to vector, or any other data type so later i
could read those values and their indexes?
Sorry if something is unclear, Its my 1st post here:) Cheers
I need to write a function that takes as argument 2d array. Each element
of array has an Integer value. As input i have a 2D array for example:
[1][1][2][2]
[2][1][2][2]
[3][3][3][3]
[22][.......
and as output I need to store indexes for each value :
value = 1 : [0,0] ; [0,1] ; [ 1,1]
value = 2 : [1,0] ; ....
value = 3 : [2,0] ; .......
value = 22 : [.........
Size of array may be various, same as number of values. Is it somehow
possible to save that data to vector, or any other data type so later i
could read those values and their indexes?
Sorry if something is unclear, Its my 1st post here:) Cheers
Check if anything exist between two points
Check if anything exist between two points
Is there any way to check if there's anything between two points? For
example, there's two points A and C
If A B C, the method will return true but if A C B , they are not on a
same line so it will return false.
Is there any way to check if there's anything between two points? For
example, there's two points A and C
If A B C, the method will return true but if A C B , they are not on a
same line so it will return false.
MySql: read database table entry which is next to timestamp
MySql: read database table entry which is next to timestamp
I have a mysql database storing the energy produced by an inverter. The
values are stored summed up every x min in column "kWh_Dag". Now I would
like to read, what energy has been produced that day up to a specific time
of the day. The values are stored with the timestamp written "Datum_Dag".
I tried
SELECT `kWh_Dag` from `tgeg_dag` WHERE `Datum_dag` IN (SELECT
MAX(`Datum_Dag`) FROM `tgeg_dag` WHERE `Datum_Dag` < "2013-09-27
00:00:00")
but the database does not return anything. The "inline" SQL statement does
return the right timestamp belonging to the table entry which is the one I
want.
Is this the smartest way to access the wanted database entry?
Thanks
I have a mysql database storing the energy produced by an inverter. The
values are stored summed up every x min in column "kWh_Dag". Now I would
like to read, what energy has been produced that day up to a specific time
of the day. The values are stored with the timestamp written "Datum_Dag".
I tried
SELECT `kWh_Dag` from `tgeg_dag` WHERE `Datum_dag` IN (SELECT
MAX(`Datum_Dag`) FROM `tgeg_dag` WHERE `Datum_Dag` < "2013-09-27
00:00:00")
but the database does not return anything. The "inline" SQL statement does
return the right timestamp belonging to the table entry which is the one I
want.
Is this the smartest way to access the wanted database entry?
Thanks
Friday, 27 September 2013
Need to get one numeric result from Datagridview through textbox. Urgent help needed project due Monday
Need to get one numeric result from Datagridview through textbox. Urgent
help needed project due Monday
I managed to get all the filters in datagridview to work through textbox
except one filter and i really need help before monday its for my project.
For all the other filters i use " like " in my statement but there is a
field for a dispatch/complaint number and when i enter the number i want
just one filtered row and not all with wildcard in that column For
instance when i type " 1 " in my textbox i want result as just one row
with that dispatch number and not other rows containing numbers like " 10,
21 , 100," , just a single row with the dispatch number " 1 " here is the
code
//the actual filter
((DataTable)recordsdatagridview.DataSource).DefaultView.RowFilter = filter
+ " * '{0}'" + txtstatusvalue.Text.Trim().Replace("'", "''");
//to set the filter for the required column through dropdown combobox i-e:
dispno/compno
if (combosearchby.Text == "Complaint Number")
{
filter = "CONVERT(compno,'System.String')";
txtstatusvalue.Enabled = true;
}
i found the " * '{0}'" from here as well tweaked it a bit and got it to
work earlier but i have no idea what happened to the code and its not
working. sorry for a poorly typed post its my first time posting.. i need
help urgently and can provide any further details if necessary
help needed project due Monday
I managed to get all the filters in datagridview to work through textbox
except one filter and i really need help before monday its for my project.
For all the other filters i use " like " in my statement but there is a
field for a dispatch/complaint number and when i enter the number i want
just one filtered row and not all with wildcard in that column For
instance when i type " 1 " in my textbox i want result as just one row
with that dispatch number and not other rows containing numbers like " 10,
21 , 100," , just a single row with the dispatch number " 1 " here is the
code
//the actual filter
((DataTable)recordsdatagridview.DataSource).DefaultView.RowFilter = filter
+ " * '{0}'" + txtstatusvalue.Text.Trim().Replace("'", "''");
//to set the filter for the required column through dropdown combobox i-e:
dispno/compno
if (combosearchby.Text == "Complaint Number")
{
filter = "CONVERT(compno,'System.String')";
txtstatusvalue.Enabled = true;
}
i found the " * '{0}'" from here as well tweaked it a bit and got it to
work earlier but i have no idea what happened to the code and its not
working. sorry for a poorly typed post its my first time posting.. i need
help urgently and can provide any further details if necessary
Trying to create nested loops dynamically in Ruby
Trying to create nested loops dynamically in Ruby
I currently have the following method:
def generate_lineups(max_salary)
player_combos_by_position = calc_position_combinations
lineups = []
player_combos_by_position[:qb].each do |qb_set|
unless salary_of(qb_set) > max_salary
player_combos_by_position[:rb].each do |rb_set|
unless salary_of(qb_set, rb_set) > max_salary
lineups << create_team_from_sets(qb_set, rb_set)
end
end
end
end
return lineups
end
player_combos_by_position is a hash that contains groupings of players
keyed by position:
{ qb: [[player1, player2], [player6, player7]], rb: [[player3, player4,
player5], [player8, player9, player10]] }
salary_of() takes the sets of players and calculates their total salary.
create_team_from_sets() takes sets of players and returns a new Team of
the players
Ideally I want to remove the hardcoded nested loops as I do not know which
positions will be available. I think recursion is the answer, but I'm
having a hard time wrapping my head around the solution. Any ideas would
be greatly appreciated.
I currently have the following method:
def generate_lineups(max_salary)
player_combos_by_position = calc_position_combinations
lineups = []
player_combos_by_position[:qb].each do |qb_set|
unless salary_of(qb_set) > max_salary
player_combos_by_position[:rb].each do |rb_set|
unless salary_of(qb_set, rb_set) > max_salary
lineups << create_team_from_sets(qb_set, rb_set)
end
end
end
end
return lineups
end
player_combos_by_position is a hash that contains groupings of players
keyed by position:
{ qb: [[player1, player2], [player6, player7]], rb: [[player3, player4,
player5], [player8, player9, player10]] }
salary_of() takes the sets of players and calculates their total salary.
create_team_from_sets() takes sets of players and returns a new Team of
the players
Ideally I want to remove the hardcoded nested loops as I do not know which
positions will be available. I think recursion is the answer, but I'm
having a hard time wrapping my head around the solution. Any ideas would
be greatly appreciated.
Global "Module" in C# similar to VB.NET's Module
Global "Module" in C# similar to VB.NET's Module
I've been searching around here and elsewhere for an answer to this, but I
haven't found an exact answer.
I'm fairly new to C#. In VB.NET, you can define a Module, like a class,
which has some limitations and also some benefits. One of its great
benefits is that you can access all of its members globally if you've
imported the namespace (i.e. "using" in c#). For example:
Private Sub Test()
MsgBox(Now)
End Sub
In the method above, MsgBox is a method in the
Microsoft.VisualBasic.Interaction module and Now is a property in the
Microsoft.VisualBasic.DateAndTime module. I don't have to qualify the call
to either of them in order to use them, although I could:
Private Sub Test()
Microsoft.VisualBasic.Interaction.MsgBox(Microsoft.VisualBasic.DateAndTime.Now)
End Sub
I use this feature all the time in my own projects by building my own
modules with utility methods and properties. It's very, very useful. Is
there an equivalent in C#?
I've been searching around here and elsewhere for an answer to this, but I
haven't found an exact answer.
I'm fairly new to C#. In VB.NET, you can define a Module, like a class,
which has some limitations and also some benefits. One of its great
benefits is that you can access all of its members globally if you've
imported the namespace (i.e. "using" in c#). For example:
Private Sub Test()
MsgBox(Now)
End Sub
In the method above, MsgBox is a method in the
Microsoft.VisualBasic.Interaction module and Now is a property in the
Microsoft.VisualBasic.DateAndTime module. I don't have to qualify the call
to either of them in order to use them, although I could:
Private Sub Test()
Microsoft.VisualBasic.Interaction.MsgBox(Microsoft.VisualBasic.DateAndTime.Now)
End Sub
I use this feature all the time in my own projects by building my own
modules with utility methods and properties. It's very, very useful. Is
there an equivalent in C#?
Adding EditText fields on view when typing on a EditText
Adding EditText fields on view when typing on a EditText
I want to create EditTextFields dynamically on depending the condition.
Condition is that if I start typing on first EditTextField it will create
one more EditTextField in the bottom and will create the third
EditTextField when i start typing on second one. Similarly i want to
delete the bottom text if there is no text in the upper EditTextField.
Thanks.
I want to create EditTextFields dynamically on depending the condition.
Condition is that if I start typing on first EditTextField it will create
one more EditTextField in the bottom and will create the third
EditTextField when i start typing on second one. Similarly i want to
delete the bottom text if there is no text in the upper EditTextField.
Thanks.
Thursday, 26 September 2013
Cannot retrieve all row in table php, only half is retrieved
Cannot retrieve all row in table php, only half is retrieved
I have a table named 'laptop' and a column inside the table named
'Lap_War_Expiry'. The code run well as what I have edit in previous
posting, How to retrieve more than one data in email? . However, the code
only run for 45 data only. It supposed to be 100 data and sent the email
to user. (I know it sounds too many of email, but before I try to combine
the data in one email, I need to make sure all the data is retrieved
first)
I try to change the php.ini config below but still cannot retrieve all the
needed email. Is there anywhere that I should change other than this ? Or
is it my configuration is not right ?
max_execution_time = 0 ; Maximum execution time of each script, in
seconds
max_input_time = 0 ; Maximum amount of time each script may spend parsing
request data
;max_input_nesting_level = -1 ; Maximum input variable nesting level
memory_limit = 128M ; Maximum amount of memory a script may consume
(128MB)
This is my coding for sending the email :
<?php
require 'class.phpmailer.php';
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Mailer = 'smtp';
$mail->SMTPAuth = true;
$mail->Host = 'smtp.gmail.com'; // "ssl://smtp.gmail.com" didn't worked
$mail->Port = 465;
$mail->SMTPSecure = 'ssl';
// ======== get database data ==================
$link = mysql_connect("localhost","root","");
$database="master_inventory";
mysql_select_db ($database,$link) OR die ("Could not open $database" );
$query2 = 'SELECT Lap_PC_Name, Lap_War_Expiry FROM laptop';
name.
$result1 = mysql_query($query2);
//$query2='SELECT GetDate(), Lap_War_Expiry, DATEDIFF(GetDate(),
Lap_War_Expiry) AS
diff FROM laptop where DATEDIFF(GetDate(), Lap_War_Expiry) < 1';
//$result1 = mysql_query($query2);
while($row = mysql_fetch_array($result1)) {
$Lap_PC_Name = $row['Lap_PC_Name'];
$Lap_War_Expiry = $row['Lap_War_Expiry'];
$date=$row['Lap_War_Expiry'];
// $date is get from table
$date = date ('d-m-Y')||('d/m/Y') + (7 * 24 * 60 * 60);
$newdate = strtotime ( '+45 days' , strtotime ( $row['Lap_War_Expiry']) ) ;
$newdate = date ( 'd/m/Y' , $newdate );
if ($newdate <45) {
$mail->Username = "myemail@gmail.com";
$mail->Password = "password";
$mail->IsHTML(true); // if you are going to send HTML formatted emails
$mail->SingleTo = true;
$mail->From = "assetmanagementsystemauosp@gmail.com";
$mail->FromName = "Asset Management System";
$mail->addAddress("email@gmail.com","Asset Management System");
$mail->Subject = "Notification on warranty expiry";
$mail->Body = "Dear IT Infra,<br/><br />The licensed for the following PC
will expired
in less than one month.<br /><br /> PC Name : ".$Lap_PC_Name. "<br />Date
of expired :"
.$Lap_War_Expiry;
if(!$mail->Send())
echo "Message was not sent <br />PHPMailer Error: " . $mail->ErrorInfo;
else
echo "Message has been sent";
}
else {
echo "No PC expired less than 45 days for today. ";
}
}
?>
I have a table named 'laptop' and a column inside the table named
'Lap_War_Expiry'. The code run well as what I have edit in previous
posting, How to retrieve more than one data in email? . However, the code
only run for 45 data only. It supposed to be 100 data and sent the email
to user. (I know it sounds too many of email, but before I try to combine
the data in one email, I need to make sure all the data is retrieved
first)
I try to change the php.ini config below but still cannot retrieve all the
needed email. Is there anywhere that I should change other than this ? Or
is it my configuration is not right ?
max_execution_time = 0 ; Maximum execution time of each script, in
seconds
max_input_time = 0 ; Maximum amount of time each script may spend parsing
request data
;max_input_nesting_level = -1 ; Maximum input variable nesting level
memory_limit = 128M ; Maximum amount of memory a script may consume
(128MB)
This is my coding for sending the email :
<?php
require 'class.phpmailer.php';
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Mailer = 'smtp';
$mail->SMTPAuth = true;
$mail->Host = 'smtp.gmail.com'; // "ssl://smtp.gmail.com" didn't worked
$mail->Port = 465;
$mail->SMTPSecure = 'ssl';
// ======== get database data ==================
$link = mysql_connect("localhost","root","");
$database="master_inventory";
mysql_select_db ($database,$link) OR die ("Could not open $database" );
$query2 = 'SELECT Lap_PC_Name, Lap_War_Expiry FROM laptop';
name.
$result1 = mysql_query($query2);
//$query2='SELECT GetDate(), Lap_War_Expiry, DATEDIFF(GetDate(),
Lap_War_Expiry) AS
diff FROM laptop where DATEDIFF(GetDate(), Lap_War_Expiry) < 1';
//$result1 = mysql_query($query2);
while($row = mysql_fetch_array($result1)) {
$Lap_PC_Name = $row['Lap_PC_Name'];
$Lap_War_Expiry = $row['Lap_War_Expiry'];
$date=$row['Lap_War_Expiry'];
// $date is get from table
$date = date ('d-m-Y')||('d/m/Y') + (7 * 24 * 60 * 60);
$newdate = strtotime ( '+45 days' , strtotime ( $row['Lap_War_Expiry']) ) ;
$newdate = date ( 'd/m/Y' , $newdate );
if ($newdate <45) {
$mail->Username = "myemail@gmail.com";
$mail->Password = "password";
$mail->IsHTML(true); // if you are going to send HTML formatted emails
$mail->SingleTo = true;
$mail->From = "assetmanagementsystemauosp@gmail.com";
$mail->FromName = "Asset Management System";
$mail->addAddress("email@gmail.com","Asset Management System");
$mail->Subject = "Notification on warranty expiry";
$mail->Body = "Dear IT Infra,<br/><br />The licensed for the following PC
will expired
in less than one month.<br /><br /> PC Name : ".$Lap_PC_Name. "<br />Date
of expired :"
.$Lap_War_Expiry;
if(!$mail->Send())
echo "Message was not sent <br />PHPMailer Error: " . $mail->ErrorInfo;
else
echo "Message has been sent";
}
else {
echo "No PC expired less than 45 days for today. ";
}
}
?>
Wednesday, 25 September 2013
How to change ios7 UISwitch border color?
How to change ios7 UISwitch border color?
I just add a UISwitch in UITableViewCell of my App, but when it's status
turn to off, it look like just a round there.
I try to change the background color to gary, I saw the border color is
white, how to change it to gary like the UISwitch in ios7 setting?
my app:
ios7 setting:
I just add a UISwitch in UITableViewCell of my App, but when it's status
turn to off, it look like just a round there.
I try to change the background color to gary, I saw the border color is
white, how to change it to gary like the UISwitch in ios7 setting?
my app:
ios7 setting:
Thursday, 19 September 2013
Updating value of array
Updating value of array
how do I update the value in itemprices if iteminfo equals to certain
subject?
User(
[name] => xxxx
[phone] => xxxxx
[email]xxxxx
[itemprices] => Array ( [0] => 1.00 [1] => 1.00 )
[iteminfo] => Array ( [0] => Chemistry [1] => Biology )
)
how do I update the value in itemprices if iteminfo equals to certain
subject?
User(
[name] => xxxx
[phone] => xxxxx
[email]xxxxx
[itemprices] => Array ( [0] => 1.00 [1] => 1.00 )
[iteminfo] => Array ( [0] => Chemistry [1] => Biology )
)
Javascript: How do I perform a action with the click of a button?
Javascript: How do I perform a action with the click of a button?
What is the proper syntax for clicking a button and having Javascript run
whatever statement you have? I did a google search but there is either
multiple ways or people aren't explaining the parameters or functions very
well.
Here is my code. All I want to do is when I click "attack" on my "button",
the monster will lose 10 hp.
document.getElementById("attack").click(); = dragon.hp = dragon.hp - 10;
What is the proper syntax for clicking a button and having Javascript run
whatever statement you have? I did a google search but there is either
multiple ways or people aren't explaining the parameters or functions very
well.
Here is my code. All I want to do is when I click "attack" on my "button",
the monster will lose 10 hp.
document.getElementById("attack").click(); = dragon.hp = dragon.hp - 10;
Excel Macro, read a worksheet, select range of data, copy selection
Excel Macro, read a worksheet, select range of data, copy selection
I need to write a macro that reads a worksheet of GeoTechnical data,
selects the data based off a value in a particular row, select that row
and continue reading until the end of worksheet. Once all rows are
selected, I then need to copy those rows into a new worksheet. I haven't
done VBA in about 10 years, so just trying to get back into things.
For example, I want the macro to read the worksheet, when column "I"
contains the word "Run" on a particular row, I want to then select from
that row, A:AM. Continue reading through the worksheet until the end of
it. The end of the document is tricky as there are up to 10-15 blank rows
sometimes in between groups of data in the worksheet. If there is more
then 25 blank rows, then the document would be at the end. Once everything
is selected, I then need to copy the selection for pasting into a new
worksheet. Here is the code I have thus far, but I'm unable to get a
selection:
Option Explicit Sub GeoTechDB() Dim x As String Dim BlankCount As Integer
' Select first line of data. Range("I2").Select ' Set search variable
value and counter. x = "Run" BlankCount = 0 ' Set Do loop to read cell
value, increment or reset counter and stop loop at end 'document when
there ' is more then 25 blank cells in column "I", copy final selection Do
Until BlankCount > 25 ' Check active cell for search value "Run". If
ActiveCell.Value = x Then 'select the range of data when "Run" is found
ActiveCell.Range("A:AM").Select 'set counter to 0 BlankCount = 0 'Step
down 1 row from present location ActiveCell.Offset(1, 0).Select Else 'Step
down 1 row from present location ActiveCell.Offset(1, 0).Select 'if cell
is empty then increment the counter BlankCount = BlankCount + 1 End If
Loop End Sub
I need to write a macro that reads a worksheet of GeoTechnical data,
selects the data based off a value in a particular row, select that row
and continue reading until the end of worksheet. Once all rows are
selected, I then need to copy those rows into a new worksheet. I haven't
done VBA in about 10 years, so just trying to get back into things.
For example, I want the macro to read the worksheet, when column "I"
contains the word "Run" on a particular row, I want to then select from
that row, A:AM. Continue reading through the worksheet until the end of
it. The end of the document is tricky as there are up to 10-15 blank rows
sometimes in between groups of data in the worksheet. If there is more
then 25 blank rows, then the document would be at the end. Once everything
is selected, I then need to copy the selection for pasting into a new
worksheet. Here is the code I have thus far, but I'm unable to get a
selection:
Option Explicit Sub GeoTechDB() Dim x As String Dim BlankCount As Integer
' Select first line of data. Range("I2").Select ' Set search variable
value and counter. x = "Run" BlankCount = 0 ' Set Do loop to read cell
value, increment or reset counter and stop loop at end 'document when
there ' is more then 25 blank cells in column "I", copy final selection Do
Until BlankCount > 25 ' Check active cell for search value "Run". If
ActiveCell.Value = x Then 'select the range of data when "Run" is found
ActiveCell.Range("A:AM").Select 'set counter to 0 BlankCount = 0 'Step
down 1 row from present location ActiveCell.Offset(1, 0).Select Else 'Step
down 1 row from present location ActiveCell.Offset(1, 0).Select 'if cell
is empty then increment the counter BlankCount = BlankCount + 1 End If
Loop End Sub
insert product quantity of cart insto the attributes in prestashop 1.5.4.1
insert product quantity of cart insto the attributes in prestashop 1.5.4.1
I want to insert the number of products you want to buy the customer
within subject design attributes but when inserting it does not work, only
grabs 1 product, as I have to do to make functions thanks![enter image
description here][1]
http://www.entrepaginas.es/images/sabor.jpg this is the format
this is the code product.tpl do not allow in the post
http://www.entrepaginas.es/images/codigo.html
I want to insert the number of products you want to buy the customer
within subject design attributes but when inserting it does not work, only
grabs 1 product, as I have to do to make functions thanks![enter image
description here][1]
http://www.entrepaginas.es/images/sabor.jpg this is the format
this is the code product.tpl do not allow in the post
http://www.entrepaginas.es/images/codigo.html
window.onunload event not firing
window.onunload event not firing
I have a silverlight application in which I need to fire signout event if
user navigates away. I have tried a sample function as
window.onunload = function test() { alert("test"); }
The problem is when I navigate away from the webpage the event fires, but
I need this event to fire when user closed browser or tab.
I have a silverlight application in which I need to fire signout event if
user navigates away. I have tried a sample function as
window.onunload = function test() { alert("test"); }
The problem is when I navigate away from the webpage the event fires, but
I need this event to fire when user closed browser or tab.
Handling retain with ARC enabled?
Handling retain with ARC enabled?
I want to extend an NSMutableArray with queue like selectors one such is
- (id)dequeue {
id obj = nil;
if ([self count] > 0) {
id obj = [self objectAtIndex:0];
if (obj != nil) {
[self removeObjectAtIndex:0];
}
}
return obj;
}
Problem is that I have ARC enabled and the data that obj points at is
released at removeObjectAtIndex: so dequeue always returns null.
What's an elegant way to work around this or is my approach completely wrong?
I want to extend an NSMutableArray with queue like selectors one such is
- (id)dequeue {
id obj = nil;
if ([self count] > 0) {
id obj = [self objectAtIndex:0];
if (obj != nil) {
[self removeObjectAtIndex:0];
}
}
return obj;
}
Problem is that I have ARC enabled and the data that obj points at is
released at removeObjectAtIndex: so dequeue always returns null.
What's an elegant way to work around this or is my approach completely wrong?
Implementing a web service to trigger OCR actions
Implementing a web service to trigger OCR actions
I am trying to implement a web service which triggers OCR actions of the
server side.
Client code:
...
sy = belgeArsivle(testServisIstegi, ab);
...
private static ServisYaniti belgeArsivle(com.ocr.ws.ServiceRequest
serviceRequest,com.ocr.ws.Document document) {
com.ocr.ws.ServiceRequest service = new
com.ocr.ws.OCRArsivWSService();
com.ocr.ws.OCRArsivWS port = service.getOCRArsivWSPort();
return port.docArchive(serviceRequest, document);
}
When I run the code on the server side there is no problem. But whenever I
call the web service method from the client I got this error code:
Exception: javax.xml.ws.soap.SOAPFaultException: Unable to load library
'libtesseract302': The specified module could not be found.
The working server-side code is:
public static void main(String[] args) {
// TODO code application logic here
File imageFile = new File("...OCR\\testTurWithBarcodeScanned.png");
Tesseract instance = Tesseract.getInstance();
try {
String lang = "tur";
instance.setLanguage(lang);
String result = instance.doOCR(imageFile);
System.out.println(result);
// write in a file
try {
File file = new File("...MyOutputWithBarcode.txt");
BufferedWriter out = new BufferedWriter(new
FileWriter(file));
out.write(result);
out.close();
} catch (IOException ex) {
}
} catch (TesseractException ep) {
System.err.println(ep.getMessage());
}
}
I know that this error code is about Tesseract libraries. I put the
corresponding .dll files (liblept168 and libtesseract302) under the client
project's folder, added corresponding libraries (jna, jai_imageio,
ghost4j_0.3.1), did neccessary changes in classpath but still getting this
error.
I run a test code on the server side, it works fine. But the client side
code is not working. Do I need to make some extra adjustment on the client
side to run this web service?
I am trying to implement a web service which triggers OCR actions of the
server side.
Client code:
...
sy = belgeArsivle(testServisIstegi, ab);
...
private static ServisYaniti belgeArsivle(com.ocr.ws.ServiceRequest
serviceRequest,com.ocr.ws.Document document) {
com.ocr.ws.ServiceRequest service = new
com.ocr.ws.OCRArsivWSService();
com.ocr.ws.OCRArsivWS port = service.getOCRArsivWSPort();
return port.docArchive(serviceRequest, document);
}
When I run the code on the server side there is no problem. But whenever I
call the web service method from the client I got this error code:
Exception: javax.xml.ws.soap.SOAPFaultException: Unable to load library
'libtesseract302': The specified module could not be found.
The working server-side code is:
public static void main(String[] args) {
// TODO code application logic here
File imageFile = new File("...OCR\\testTurWithBarcodeScanned.png");
Tesseract instance = Tesseract.getInstance();
try {
String lang = "tur";
instance.setLanguage(lang);
String result = instance.doOCR(imageFile);
System.out.println(result);
// write in a file
try {
File file = new File("...MyOutputWithBarcode.txt");
BufferedWriter out = new BufferedWriter(new
FileWriter(file));
out.write(result);
out.close();
} catch (IOException ex) {
}
} catch (TesseractException ep) {
System.err.println(ep.getMessage());
}
}
I know that this error code is about Tesseract libraries. I put the
corresponding .dll files (liblept168 and libtesseract302) under the client
project's folder, added corresponding libraries (jna, jai_imageio,
ghost4j_0.3.1), did neccessary changes in classpath but still getting this
error.
I run a test code on the server side, it works fine. But the client side
code is not working. Do I need to make some extra adjustment on the client
side to run this web service?
Wednesday, 18 September 2013
Reading a text file and inserting information into a new object
Reading a text file and inserting information into a new object
So I have a text file with information in the following format, with the
name, email, and phone number.
Bill Molan, Bill.Molan@gmail.com, 612-789-7538
Greg Hanson, Greg.Hanson@gmail.com, 651-368-4558
Zoe Hall, Zoe.Hall@gmail.com, 952-778-4322
Henry Sinn, Henry.Sinn@gmail.com, 651-788-9634
Brittany Hudson, Brittany.Hudson@gmail.com, 612-756-4486
When my program starts, I want to read this file and make each row into a
new Person(), which I will eventually add to a list. I am wanting to read
each line, and then use the comma to separate each string to put into the
constructor of Person(), which is a basic class:
public PersonEntry(string n, string e, string p)
{
Name = n;
Email = e;
Phone = p;
}
I have done some looking and I think that using a streamreader is going to
work for reading the text file, but I'm not really sure where to go from
here.
So I have a text file with information in the following format, with the
name, email, and phone number.
Bill Molan, Bill.Molan@gmail.com, 612-789-7538
Greg Hanson, Greg.Hanson@gmail.com, 651-368-4558
Zoe Hall, Zoe.Hall@gmail.com, 952-778-4322
Henry Sinn, Henry.Sinn@gmail.com, 651-788-9634
Brittany Hudson, Brittany.Hudson@gmail.com, 612-756-4486
When my program starts, I want to read this file and make each row into a
new Person(), which I will eventually add to a list. I am wanting to read
each line, and then use the comma to separate each string to put into the
constructor of Person(), which is a basic class:
public PersonEntry(string n, string e, string p)
{
Name = n;
Email = e;
Phone = p;
}
I have done some looking and I think that using a streamreader is going to
work for reading the text file, but I'm not really sure where to go from
here.
reading my json response from a post request i sent
reading my json response from a post request i sent
I made a post request class that I could re-use to make POST requests to
an external api and return the objects they send me (JSON):
class PostRequest
{
private Action<DataUpdateState> Callback;
public PostRequest(string urlPath, string data,
Action<DataUpdateState> callback)
{
Callback = callback;
// form the URI
UriBuilder fullUri = new UriBuilder(urlPath);
fullUri.Query = data;
// initialize a new WebRequest
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create(fullUri.Uri);
request.Method = "POST";
// set up the state object for the async request
DataUpdateState dataState = new DataUpdateState();
dataState.AsyncRequest = request;
// start the asynchronous request
request.BeginGetResponse(new AsyncCallback(HandleResponse),
dataState);
}
private void HandleResponse(IAsyncResult asyncResult)
{
// get the state information
DataUpdateState dataState =
(DataUpdateState)asyncResult.AsyncState;
HttpWebRequest dataRequest =
(HttpWebRequest)dataState.AsyncRequest;
// end the async request
dataState.AsyncResponse =
(HttpWebResponse)dataRequest.EndGetResponse(asyncResult);
if (dataState.AsyncResponse.StatusCode.ToString() == "OK")
{
Callback(dataState); // THIS IS THE LINE YOU SHOULD LOOK
AT :)
}
}
}
public class DataUpdateState
{
public HttpWebRequest AsyncRequest { get; set; }
public HttpWebResponse AsyncResponse { get; set; }
}
}
the Callback method gets the datastate object and pushes it to this function:
public void LoadDashboard( DataUpdateState dataResponse )
{
Stream response = dataResponse.AsyncResponse.GetResponseStream();
//Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
//StreamReader readStream = new StreamReader(response, encode);
//readStream.Close();
Deployment.Current.Dispatcher.BeginInvoke(() => {
App.RootFrame.Navigate(new Uri("/Interface.xaml",
UriKind.RelativeOrAbsolute));
});
}
I'm now unsure of how to get the body of that reply that has been sent to
me from the API. It is returning a json format, I need to be able to map
it to a nice C# class and use it to display stuff on the phone.
I can't find an example that doesn't use JSON.NET (which doesn't have an
assembly for windows phone 8)
I made a post request class that I could re-use to make POST requests to
an external api and return the objects they send me (JSON):
class PostRequest
{
private Action<DataUpdateState> Callback;
public PostRequest(string urlPath, string data,
Action<DataUpdateState> callback)
{
Callback = callback;
// form the URI
UriBuilder fullUri = new UriBuilder(urlPath);
fullUri.Query = data;
// initialize a new WebRequest
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create(fullUri.Uri);
request.Method = "POST";
// set up the state object for the async request
DataUpdateState dataState = new DataUpdateState();
dataState.AsyncRequest = request;
// start the asynchronous request
request.BeginGetResponse(new AsyncCallback(HandleResponse),
dataState);
}
private void HandleResponse(IAsyncResult asyncResult)
{
// get the state information
DataUpdateState dataState =
(DataUpdateState)asyncResult.AsyncState;
HttpWebRequest dataRequest =
(HttpWebRequest)dataState.AsyncRequest;
// end the async request
dataState.AsyncResponse =
(HttpWebResponse)dataRequest.EndGetResponse(asyncResult);
if (dataState.AsyncResponse.StatusCode.ToString() == "OK")
{
Callback(dataState); // THIS IS THE LINE YOU SHOULD LOOK
AT :)
}
}
}
public class DataUpdateState
{
public HttpWebRequest AsyncRequest { get; set; }
public HttpWebResponse AsyncResponse { get; set; }
}
}
the Callback method gets the datastate object and pushes it to this function:
public void LoadDashboard( DataUpdateState dataResponse )
{
Stream response = dataResponse.AsyncResponse.GetResponseStream();
//Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
//StreamReader readStream = new StreamReader(response, encode);
//readStream.Close();
Deployment.Current.Dispatcher.BeginInvoke(() => {
App.RootFrame.Navigate(new Uri("/Interface.xaml",
UriKind.RelativeOrAbsolute));
});
}
I'm now unsure of how to get the body of that reply that has been sent to
me from the API. It is returning a json format, I need to be able to map
it to a nice C# class and use it to display stuff on the phone.
I can't find an example that doesn't use JSON.NET (which doesn't have an
assembly for windows phone 8)
Auto Update all Static Pages
Auto Update all Static Pages
I have a static website that has around 30+ pages in HTML and I need to
auto-update the menu on all of my pages without editing each page
separately (that would take a loooong time). The code for the menu is
exactly the same on all of these pages so maybe I could use a script or
something? I already know that dynamic websites are better and it's easier
to fix issues like this but that's not the case with my website.
I have a static website that has around 30+ pages in HTML and I need to
auto-update the menu on all of my pages without editing each page
separately (that would take a loooong time). The code for the menu is
exactly the same on all of these pages so maybe I could use a script or
something? I already know that dynamic websites are better and it's easier
to fix issues like this but that's not the case with my website.
Change JavaScript string encoding
Change JavaScript string encoding
At the moment I have a large JavaScript string I'm attempting to write to
a file, but in a different encoding (ISO-8859-1). I was hoping to use
something like downloadify. Downloadify only accepts normal JavaScript
strings or base64 encoded strings.
Because of this, I've decided to compress my string using JSZip which
generates a nicely base64 encoded string that can be passed to
downloadify, and downloaded to my desktop. Huzzah! The issue is that the
string I compressed, of course, is still the wrong encoding.
Luckily JSZip can take a Uint8Array as data, instead of a string. So is
there any way to convert a JavaScript string into a ISO-8859-1 encoded
string and store it in a Uint8Array?
Alternatively, if I'm approaching this all wrong, is there a better
solution all together? Is there a fancy JavaScript string class that can
use different internal encodings?
At the moment I have a large JavaScript string I'm attempting to write to
a file, but in a different encoding (ISO-8859-1). I was hoping to use
something like downloadify. Downloadify only accepts normal JavaScript
strings or base64 encoded strings.
Because of this, I've decided to compress my string using JSZip which
generates a nicely base64 encoded string that can be passed to
downloadify, and downloaded to my desktop. Huzzah! The issue is that the
string I compressed, of course, is still the wrong encoding.
Luckily JSZip can take a Uint8Array as data, instead of a string. So is
there any way to convert a JavaScript string into a ISO-8859-1 encoded
string and store it in a Uint8Array?
Alternatively, if I'm approaching this all wrong, is there a better
solution all together? Is there a fancy JavaScript string class that can
use different internal encodings?
Start address must be aligned
Start address must be aligned
I am new to Embedding programing and debugging an issue realted to write
to an fpga register. fpga registers are mapped to cpld device . Fpga
resgiter write failed at very start of the code
//Start address must be aligned
if(ad & 0x3)
{
syslog(LOG_ERR, "%s, fpga reg address is not aligned\n", c__);
return FAILURE;
}
Now write is failing saying that fpga reg address is not aligned
The value of ad we are passing here is 1 .
We don't have FPGA resiter specs with us but one of .def files gives cpld
resgiter list
* 0x20 */
REG(fc)
REGR(pp)
REG(pq)
REGR(inq)
I believe pp ,pq and inq is one of the fpga register(mapped to cpld) we
are writing to and 0x20 is address of fc resgister
So are we passing wrong address(ad) for writing to fpga resgiter??
What I can make out of
Start address must be aligned.
I am new to Embedding programing and debugging an issue realted to write
to an fpga register. fpga registers are mapped to cpld device . Fpga
resgiter write failed at very start of the code
//Start address must be aligned
if(ad & 0x3)
{
syslog(LOG_ERR, "%s, fpga reg address is not aligned\n", c__);
return FAILURE;
}
Now write is failing saying that fpga reg address is not aligned
The value of ad we are passing here is 1 .
We don't have FPGA resiter specs with us but one of .def files gives cpld
resgiter list
* 0x20 */
REG(fc)
REGR(pp)
REG(pq)
REGR(inq)
I believe pp ,pq and inq is one of the fpga register(mapped to cpld) we
are writing to and 0x20 is address of fc resgister
So are we passing wrong address(ad) for writing to fpga resgiter??
What I can make out of
Start address must be aligned.
CSV file import using Ruby on Rails
CSV file import using Ruby on Rails
Is it possible to import CSV files using gem roo or using similar gem?
Also I need to bind first row of that csv file to every other rows as
hash.
Is it possible to import CSV files using gem roo or using similar gem?
Also I need to bind first row of that csv file to every other rows as
hash.
Prestashop Product customizer
Prestashop Product customizer
I have an application which is a T-Shirt customizer which works very good
on it's own. But I need to integrate it into prestashop. So after a user
uses the application to customize a t-shirt he has to click Add to cart
and the product will be added to cart with a custom price and description.
What I need is for this output to be injected into the PrestaShop cart as
a custom product with all the custom information and also the generated
custom product image to display next to the details in the cart.
So I have the customizer done, I have allready made a custom module and
page for Prestashop but I don't know how to integrate it with the cart. My
prestashop knowledge is limited.
How can I do this?
I have an application which is a T-Shirt customizer which works very good
on it's own. But I need to integrate it into prestashop. So after a user
uses the application to customize a t-shirt he has to click Add to cart
and the product will be added to cart with a custom price and description.
What I need is for this output to be injected into the PrestaShop cart as
a custom product with all the custom information and also the generated
custom product image to display next to the details in the cart.
So I have the customizer done, I have allready made a custom module and
page for Prestashop but I don't know how to integrate it with the cart. My
prestashop knowledge is limited.
How can I do this?
Tuesday, 17 September 2013
How to strip newlines from each line during a file read?
How to strip newlines from each line during a file read?
I'm reading lines from a file that contains one[*] word/line, such as:
dog
cat
person
tree
Each of these words also contains a newline \n character. I want to read
them into a list and throw away the newlines. The way I've devised is to
read with readlines() and then process the list to strip() the newlines:
with open('words.txt') as f:
words = f.readlines()
for index, word in enumerate(words):
words[index] = word.strip()
This works fine, but I can't help thinking there's a more efficient way to
do this, to strip the newlines during the read process. But I can't find a
way. Is there something more efficient (while also considering
readability, etc.)
[*] UPDATE: I should have mentioned that some lines may contain more than
one word, and in those cases however many words are on a line should go
into a single list item. Both answers so far handle this (as does my own
code), but I wanted to mention it.
I'm reading lines from a file that contains one[*] word/line, such as:
dog
cat
person
tree
Each of these words also contains a newline \n character. I want to read
them into a list and throw away the newlines. The way I've devised is to
read with readlines() and then process the list to strip() the newlines:
with open('words.txt') as f:
words = f.readlines()
for index, word in enumerate(words):
words[index] = word.strip()
This works fine, but I can't help thinking there's a more efficient way to
do this, to strip the newlines during the read process. But I can't find a
way. Is there something more efficient (while also considering
readability, etc.)
[*] UPDATE: I should have mentioned that some lines may contain more than
one word, and in those cases however many words are on a line should go
into a single list item. Both answers so far handle this (as does my own
code), but I wanted to mention it.
Replace dates in an array of date with values in a mysql query
Replace dates in an array of date with values in a mysql query
I have used the below link to create an array of date.
http://boonedocks.net/mike/archives/137-Creating-a-Date-Range-Array-with-PHP.html
However, I wanted to replace dates in that array by comparing the date(in
the array) and the date(in query result).
If they are equal then I will replace that date in the array with the
result in the mysql query.
array:
array(
9/1/2013,
9/2/2013,
9/3/2013,
9/4/2013,
9/5/2013
)
query result:
| date | values |
| 9/2/2013 | 5 |
| 9/3/2013 | 6 |
| 9/5/2013 | 7 |
the result must be like this:
PHP date ----> 9/1/2013 0
Database ----> 9/2/2013 5
Database ----> 9/3/2013 6
PHP date ----> 9/4/2013 0
Database ----> 9/5/2013 7
How do i do that in PHP? I've been experimenting with while loops inside
foreach, but does not work.
I have used the below link to create an array of date.
http://boonedocks.net/mike/archives/137-Creating-a-Date-Range-Array-with-PHP.html
However, I wanted to replace dates in that array by comparing the date(in
the array) and the date(in query result).
If they are equal then I will replace that date in the array with the
result in the mysql query.
array:
array(
9/1/2013,
9/2/2013,
9/3/2013,
9/4/2013,
9/5/2013
)
query result:
| date | values |
| 9/2/2013 | 5 |
| 9/3/2013 | 6 |
| 9/5/2013 | 7 |
the result must be like this:
PHP date ----> 9/1/2013 0
Database ----> 9/2/2013 5
Database ----> 9/3/2013 6
PHP date ----> 9/4/2013 0
Database ----> 9/5/2013 7
How do i do that in PHP? I've been experimenting with while loops inside
foreach, but does not work.
jQuery : other links inside div element link
jQuery : other links inside div element link
How do I set the div link except my custom links inside the div element?
What I want is that if I click the icon in the div box, it connects the
link connected with the icons, and if I click the rest area of the div
element, it goes to the link that is connected with div element. The
following code, however, the jQuery for div element overwrite everything
so even if I have the link for the icon(png), it goes to the div link.
How do I separate with all the icons still in the div element?
Thanks
<script type="text/javascript">
$(document).ready(function(){
$(".Apps").click(function(){
window.open($(this).find("a").last().attr("href"));
return false;
});
});
</script>
<div class="Apps">
<p><b>Web Dev Project 3</b><br><i>(coming soon)</i></p>
<a href="https://github.com/" target="blank">
<img src="https://github.com/apple-touch-icon-114.png" width="30"
height="30"/></a>
<a href="http://google.com" target="blank">
<img id="logo"
src="http://cclub.slc.engr.wisc.edu/images/Under-Construction.gif"
width="30" height="30"/></a>
<a href="http://google.com" target="blank"></a>
</div>
How do I set the div link except my custom links inside the div element?
What I want is that if I click the icon in the div box, it connects the
link connected with the icons, and if I click the rest area of the div
element, it goes to the link that is connected with div element. The
following code, however, the jQuery for div element overwrite everything
so even if I have the link for the icon(png), it goes to the div link.
How do I separate with all the icons still in the div element?
Thanks
<script type="text/javascript">
$(document).ready(function(){
$(".Apps").click(function(){
window.open($(this).find("a").last().attr("href"));
return false;
});
});
</script>
<div class="Apps">
<p><b>Web Dev Project 3</b><br><i>(coming soon)</i></p>
<a href="https://github.com/" target="blank">
<img src="https://github.com/apple-touch-icon-114.png" width="30"
height="30"/></a>
<a href="http://google.com" target="blank">
<img id="logo"
src="http://cclub.slc.engr.wisc.edu/images/Under-Construction.gif"
width="30" height="30"/></a>
<a href="http://google.com" target="blank"></a>
</div>
Processing php code after readfile()
Processing php code after readfile()
I'm trying to wrap my head around processing of headers and readfile(). It
appears that no code is executed after readfile() is called. I presume
because of the "One HTTP Request, one file" rule.
I read a suggestion of using an iframe to perhaps get around this
limitation. I've tried putting this function in a separate file (e.g.
writezip) and calling it from a another file like:
<? echo '<iframe src="writezip.php">' ?>
echo "File was sent to you";
But this doesn't appear to work. Any suggestions? How would you display a
message saying "A file was sent" - Thanks in advance
<?php
function writezip(){
$fullfilename = "post.zip";
$outfilename = "test.zip";
$mode = "download";
if (file_exists($fullfilename)){
// Parse Info / Get Extension
$fsize = filesize($fullfilename);
$path_parts = pathinfo($fullfilename);
$ext = strtolower($path_parts["extension"]);
// Determine Content Type
switch ($ext) {
case "pdf": $ctype="application/pdf"; break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "doc": $ctype="application/msword"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
default: $ctype="application/force-download";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain
browsers
header("Content-Type: $ctype");
$outfilename = ($outfilename=="" ? basename($fullfilename) :
$outfilename);
if ($mode == "view"){
// View file
header('Content-Disposition: inline; filename='.$outfilename);
}
else {
// Download file
header('Content-Disposition: attachment;
filename='.basename($outfilename));
}
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$fsize);
if (ob_get_length() > 0 ) {
ob_clean();
flush();
}
readfile( $fullfilename );
die("anything here");
}
else
{
echo "File not found: ". $fullfilename;
}
}
?>
I'm trying to wrap my head around processing of headers and readfile(). It
appears that no code is executed after readfile() is called. I presume
because of the "One HTTP Request, one file" rule.
I read a suggestion of using an iframe to perhaps get around this
limitation. I've tried putting this function in a separate file (e.g.
writezip) and calling it from a another file like:
<? echo '<iframe src="writezip.php">' ?>
echo "File was sent to you";
But this doesn't appear to work. Any suggestions? How would you display a
message saying "A file was sent" - Thanks in advance
<?php
function writezip(){
$fullfilename = "post.zip";
$outfilename = "test.zip";
$mode = "download";
if (file_exists($fullfilename)){
// Parse Info / Get Extension
$fsize = filesize($fullfilename);
$path_parts = pathinfo($fullfilename);
$ext = strtolower($path_parts["extension"]);
// Determine Content Type
switch ($ext) {
case "pdf": $ctype="application/pdf"; break;
case "exe": $ctype="application/octet-stream"; break;
case "zip": $ctype="application/zip"; break;
case "doc": $ctype="application/msword"; break;
case "xls": $ctype="application/vnd.ms-excel"; break;
case "ppt": $ctype="application/vnd.ms-powerpoint"; break;
case "gif": $ctype="image/gif"; break;
case "png": $ctype="image/png"; break;
case "jpeg":
case "jpg": $ctype="image/jpg"; break;
default: $ctype="application/force-download";
}
header("Pragma: public"); // required
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: private",false); // required for certain
browsers
header("Content-Type: $ctype");
$outfilename = ($outfilename=="" ? basename($fullfilename) :
$outfilename);
if ($mode == "view"){
// View file
header('Content-Disposition: inline; filename='.$outfilename);
}
else {
// Download file
header('Content-Disposition: attachment;
filename='.basename($outfilename));
}
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".$fsize);
if (ob_get_length() > 0 ) {
ob_clean();
flush();
}
readfile( $fullfilename );
die("anything here");
}
else
{
echo "File not found: ". $fullfilename;
}
}
?>
Facebook cached token after user revokes app permissions returns wrong session state
Facebook cached token after user revokes app permissions returns wrong
session state
I'm using the latest Facebook SDK for iOS (v3.7.1) and I'm having
something confusing happen:
I launch my app, click "Sign into Facebook" and authorize my app
I close my app and goto Facebook where I revoke access to my app
I launch my app again, click "Sign into Facebook" and the app says that it
found a cached token
When I call [FBSession.activeSession openWithCompletionHandler... it
returns that the session is in the FBSessionStateOpen state even though
the session should really be in the FBSessionStateClosed state
Why would Facebook return an invalid state for the cached token? I thought
that was the whole point of using openWithCompletionHandler to check if
the cached token was still valid or not.
I am checking the token status when they click the sign in button:
if (FBSession.activeSession.state == FBSessionStateCreatedTokenLoaded) {
NSLog(@"We have a cached token, so we're going to re-establish the
sign in for the user.");
// Even though we had a cached token, we need to sign in to make the
session usable
// This should happen in the background without having to present any
UI to the user
[FBSession.activeSession openWithCompletionHandler:^(FBSession
*session, FBSessionState status, NSError *error) {
[self handleResponseForFacebookSession:session status:status
error:error];
}];
} else {
// If the token is currently open or an extended token, then we an go
ahead and use it
}
This is the response handler:
// Handles the response from the FBSession open session completion handler
- (void)handleResponseForFacebookSession:(FBSession *)session
status:(FBSessionState)status error:(NSError *)error
{
NSLog(@"Received: %@\nStatus: %u\nError: %@", session, status, error);
switch (status) {
case FBSessionStateOpen:
// We should sign in
break;
case FBSessionStateClosed:
[self authenticateWithFacebook];
NSLog(@"The Facebook session has been closed (maybe they took
access away) so we need to ask the user to login again");
break;
case FBSessionStateClosedLoginFailed:
[self handleFacebookError:error];
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
[self handleFacebookError:error];
NSLog(@"We received an unrecognized status while opening a
Facebook session (%@): %u", session, status);
break;
}
}
session state
I'm using the latest Facebook SDK for iOS (v3.7.1) and I'm having
something confusing happen:
I launch my app, click "Sign into Facebook" and authorize my app
I close my app and goto Facebook where I revoke access to my app
I launch my app again, click "Sign into Facebook" and the app says that it
found a cached token
When I call [FBSession.activeSession openWithCompletionHandler... it
returns that the session is in the FBSessionStateOpen state even though
the session should really be in the FBSessionStateClosed state
Why would Facebook return an invalid state for the cached token? I thought
that was the whole point of using openWithCompletionHandler to check if
the cached token was still valid or not.
I am checking the token status when they click the sign in button:
if (FBSession.activeSession.state == FBSessionStateCreatedTokenLoaded) {
NSLog(@"We have a cached token, so we're going to re-establish the
sign in for the user.");
// Even though we had a cached token, we need to sign in to make the
session usable
// This should happen in the background without having to present any
UI to the user
[FBSession.activeSession openWithCompletionHandler:^(FBSession
*session, FBSessionState status, NSError *error) {
[self handleResponseForFacebookSession:session status:status
error:error];
}];
} else {
// If the token is currently open or an extended token, then we an go
ahead and use it
}
This is the response handler:
// Handles the response from the FBSession open session completion handler
- (void)handleResponseForFacebookSession:(FBSession *)session
status:(FBSessionState)status error:(NSError *)error
{
NSLog(@"Received: %@\nStatus: %u\nError: %@", session, status, error);
switch (status) {
case FBSessionStateOpen:
// We should sign in
break;
case FBSessionStateClosed:
[self authenticateWithFacebook];
NSLog(@"The Facebook session has been closed (maybe they took
access away) so we need to ask the user to login again");
break;
case FBSessionStateClosedLoginFailed:
[self handleFacebookError:error];
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
[self handleFacebookError:error];
NSLog(@"We received an unrecognized status while opening a
Facebook session (%@): %u", session, status);
break;
}
}
Sunday, 15 September 2013
Primefaces saving datatable values
Primefaces saving datatable values
Iam displaying datatable with some empty rows using primefaces datatable
by associating datatable with an empty list class.
Iam able to display the desired number of rows.
Can anyone tell me how to store the datatable after entering all the rows..
Iam displaying datatable with some empty rows using primefaces datatable
by associating datatable with an empty list class.
Iam able to display the desired number of rows.
Can anyone tell me how to store the datatable after entering all the rows..
BindValue in a sql statement between quotes
BindValue in a sql statement between quotes
Im trying to execute something like this
$SQL = "INSERT into cb_sent_alerts(user_id,message)
Select id, ' :message ' from story1";
$stmt->bindValue(':message', $_POST['message']);
But that just sends :message to the database, not the values of
$_POST['message']; What can i do?
Im trying to execute something like this
$SQL = "INSERT into cb_sent_alerts(user_id,message)
Select id, ' :message ' from story1";
$stmt->bindValue(':message', $_POST['message']);
But that just sends :message to the database, not the values of
$_POST['message']; What can i do?
Set Page Scroll to show content in Fixed div
Set Page Scroll to show content in Fixed div
HTML5 is awesome! Bit to learn with formatting for a novice like me however.
I have a layout page in MVC4 and it is using two fixed div's. One is a
menu and so on and the other is a content holder.
My css snipit:
.maincontent
{
position: fixed;
top:7px;
left:382px;
right:7px;
width: auto;
height: auto;
}
I want to auto scroll the page if this div overflows. I have tried:
overflow-y:auto;
in both the body css and maincontent css elements but its not working.
Am I missing something?
Thanks
HTML5 is awesome! Bit to learn with formatting for a novice like me however.
I have a layout page in MVC4 and it is using two fixed div's. One is a
menu and so on and the other is a content holder.
My css snipit:
.maincontent
{
position: fixed;
top:7px;
left:382px;
right:7px;
width: auto;
height: auto;
}
I want to auto scroll the page if this div overflows. I have tried:
overflow-y:auto;
in both the body css and maincontent css elements but its not working.
Am I missing something?
Thanks
fake input text javascript
fake input text javascript
i have 2 input like this
<input type="password" maxlength="4" id="fakepassword" />
<input type="hidden" maxlength="8" id="password" />
how to insert value to password when type and focus on fakepassword, i try
to get value from fakepassword with OnkeyUp event but stuck in maxlength,
is there a way to get value from keyboard press?
my real problem is, i have login form and i want my password field just
showing 4 character lengt no matter how much i put character into it
please help and sorry for my terrible english
i have 2 input like this
<input type="password" maxlength="4" id="fakepassword" />
<input type="hidden" maxlength="8" id="password" />
how to insert value to password when type and focus on fakepassword, i try
to get value from fakepassword with OnkeyUp event but stuck in maxlength,
is there a way to get value from keyboard press?
my real problem is, i have login form and i want my password field just
showing 4 character lengt no matter how much i put character into it
please help and sorry for my terrible english
C - multidimensional array allocation
C - multidimensional array allocation
I'm using the following C function to emulate a 4D array. Other than
adding additional loops, is there a good way to make this function generic
enought to create n size arrays?
double ****alloc_4D_data(int wlen, int xlen, int ylen, int zlen)
{
int i,j,k;
double ****ary = (jdouble****)malloc(wlen*sizeof(jdouble***));
for (i = 0; i < wlen; i++)
{
ary[i] = (jdouble***)malloc(xlen*sizeof(jdouble**));
for (j = 0; j < xlen; j++)
{
ary[i][j] = (jdouble**)malloc(ylen*sizeof(jdouble*));
for (k = 0; k < ylen; k++)
{
ary[i][j][k] = (jdouble*)malloc(zlen*sizeof(jdouble));
}
}
}
return ary;
}
I'm using the following C function to emulate a 4D array. Other than
adding additional loops, is there a good way to make this function generic
enought to create n size arrays?
double ****alloc_4D_data(int wlen, int xlen, int ylen, int zlen)
{
int i,j,k;
double ****ary = (jdouble****)malloc(wlen*sizeof(jdouble***));
for (i = 0; i < wlen; i++)
{
ary[i] = (jdouble***)malloc(xlen*sizeof(jdouble**));
for (j = 0; j < xlen; j++)
{
ary[i][j] = (jdouble**)malloc(ylen*sizeof(jdouble*));
for (k = 0; k < ylen; k++)
{
ary[i][j][k] = (jdouble*)malloc(zlen*sizeof(jdouble));
}
}
}
return ary;
}
check if radio button is not empty
check if radio button is not empty
radio = $('input:radio[name=priority]:checked').val();
// if radio hv checked
if(radio !== ""){
// do something
}
this doesn't work, what should be inside my if statement? I tried other
field like username !=="" it work fine, but not for the radio field..
radio = $('input:radio[name=priority]:checked').val();
// if radio hv checked
if(radio !== ""){
// do something
}
this doesn't work, what should be inside my if statement? I tried other
field like username !=="" it work fine, but not for the radio field..
how to calculate the time complexity for the following code?
how to calculate the time complexity for the following code?
For (int i=1; i <=n;i/=2){
System.out.println(i);
}
For the time complexity about the above coding, is ot log (n)?
Thanks!
For (int i=1; i <=n;i/=2){
System.out.println(i);
}
For the time complexity about the above coding, is ot log (n)?
Thanks!
MySQL, Perl, and LaTeX: Looping through results by day to get custom PDF
MySQL, Perl, and LaTeX: Looping through results by day to get custom PDF
I have written a Perl script (shown below) to loop through my MySQL
database and then output a .tex file, as a sort of programmed custom
report. As it stands, it works rather well.
However, I'd like to "separate" each individual day (as a section in
LaTeX), so that I can eventually add a table of contents and see l day per
section (there can be many entries a day).
Here's what the script looks like now (I know it's a little ugly, feel
free to give me pointers on anything weird you might notice); it's too
large for pretty display on stackoverflow, so here's the link to pastebin
(hope you don't mind):
http://pastebin.com/YH8qcWXb
Please let me know if you have any ideas/suggestions or need more
information.
I have written a Perl script (shown below) to loop through my MySQL
database and then output a .tex file, as a sort of programmed custom
report. As it stands, it works rather well.
However, I'd like to "separate" each individual day (as a section in
LaTeX), so that I can eventually add a table of contents and see l day per
section (there can be many entries a day).
Here's what the script looks like now (I know it's a little ugly, feel
free to give me pointers on anything weird you might notice); it's too
large for pretty display on stackoverflow, so here's the link to pastebin
(hope you don't mind):
http://pastebin.com/YH8qcWXb
Please let me know if you have any ideas/suggestions or need more
information.
Saturday, 14 September 2013
Angular-ui modal issue
Angular-ui modal issue
I'm trying to include an angular-ui modal in my web application but am
having issues with getting everything set up.
The documentation indicate that you can use $modalInstance to inject the
child controller into the parent controller but I don't quite understand
how to go about doing so.
Here is the current code (it is straight from the modal demo from the
documentation):
angular.module('myApp.controllers', []).
controller('addContent', function ($scope, $http, $modal, $log){
//modaltest
$scope.items = ['item1', 'item2', 'item3'];
$scope.addTerm = function () {
var newTerm = $modal.open({
templateUrl: 'newTermModal.jade',
controller: newTerms,
resolve: {
items: function () {
return $scope.items;
}
}
});
newTerm.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
}).
controller("newTerms",function($scope, $modalInstance, items){
$scope.items = items;
$scope.selected = {
item: $scope.items[0]
};
$scope.ok = function () {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
When I run the app like it is now and click the button to open the modal
(addTerm function) the app crashes with the error "ReferenceError:
newTerms is not defined."
As I mentioned above, the angular-ui site indicates you can inject a
controller with $modalInstance but I have not been able to figure out how.
a Any help would be greatly appreciated!
I'm trying to include an angular-ui modal in my web application but am
having issues with getting everything set up.
The documentation indicate that you can use $modalInstance to inject the
child controller into the parent controller but I don't quite understand
how to go about doing so.
Here is the current code (it is straight from the modal demo from the
documentation):
angular.module('myApp.controllers', []).
controller('addContent', function ($scope, $http, $modal, $log){
//modaltest
$scope.items = ['item1', 'item2', 'item3'];
$scope.addTerm = function () {
var newTerm = $modal.open({
templateUrl: 'newTermModal.jade',
controller: newTerms,
resolve: {
items: function () {
return $scope.items;
}
}
});
newTerm.result.then(function (selectedItem) {
$scope.selected = selectedItem;
}, function () {
$log.info('Modal dismissed at: ' + new Date());
});
};
}).
controller("newTerms",function($scope, $modalInstance, items){
$scope.items = items;
$scope.selected = {
item: $scope.items[0]
};
$scope.ok = function () {
$modalInstance.close($scope.selected.item);
};
$scope.cancel = function () {
$modalInstance.dismiss('cancel');
};
});
When I run the app like it is now and click the button to open the modal
(addTerm function) the app crashes with the error "ReferenceError:
newTerms is not defined."
As I mentioned above, the angular-ui site indicates you can inject a
controller with $modalInstance but I have not been able to figure out how.
a Any help would be greatly appreciated!
How do I get Java to output unique integers from a command-line argument?
How do I get Java to output unique integers from a command-line argument?
The code below checks to ensure the command-line arguments are integers?
However, I need it to only print each integer in the command line once,
regardless of how many times that integer appears in the command line. How
do I do that?
public class Unique {
public static void main(String[] args) {
for (int i = 0; i<args.length; i++) {
try {
int j = Integer.parseInt(args[i]);
System.out.println(j);
}
catch (NumberFormatException e) {
System.out.println("Your command line argument "+ args[i] +"
is a non-integer!");
}
}
}
}
The code below checks to ensure the command-line arguments are integers?
However, I need it to only print each integer in the command line once,
regardless of how many times that integer appears in the command line. How
do I do that?
public class Unique {
public static void main(String[] args) {
for (int i = 0; i<args.length; i++) {
try {
int j = Integer.parseInt(args[i]);
System.out.println(j);
}
catch (NumberFormatException e) {
System.out.println("Your command line argument "+ args[i] +"
is a non-integer!");
}
}
}
}
Sending email in PHP, forcing go to line
Sending email in PHP, forcing go to line
I'm using PHPmailer to send an email. I input my Alt Text (for users with
HTML disabled) between double quotes. I'm trying to go to line between
sentences and paragraphs but when viewing the email the text all appears
on the same line.
How can I go to line in my text based emails sent from PHPmailer?
I'm using PHPmailer to send an email. I input my Alt Text (for users with
HTML disabled) between double quotes. I'm trying to go to line between
sentences and paragraphs but when viewing the email the text all appears
on the same line.
How can I go to line in my text based emails sent from PHPmailer?
How to reuse animation in SVG without javascript
How to reuse animation in SVG without javascript
I want to reuse tags without javascript but can't find a way. something
like this:
<svg>
<defs>
<animation id="shrink"
attributeName="width"
from="100%" to="0%"
dur="5s"
repeatCount="1"
fill="freeze" />
</defs>
<rect
width="100%" height="10%"
fill="blue"
animate="#shrink"/>
</svg>
But all the examples I find have the animation inside the tag or they use
javascript/jQuery etc.
there must be a way since you can reuse graphics gradients and masks.
thanks for your help!
I want to reuse tags without javascript but can't find a way. something
like this:
<svg>
<defs>
<animation id="shrink"
attributeName="width"
from="100%" to="0%"
dur="5s"
repeatCount="1"
fill="freeze" />
</defs>
<rect
width="100%" height="10%"
fill="blue"
animate="#shrink"/>
</svg>
But all the examples I find have the animation inside the tag or they use
javascript/jQuery etc.
there must be a way since you can reuse graphics gradients and masks.
thanks for your help!
Looping in laravel 4
Looping in laravel 4
How can i properly loop this
If i tick one checkbox, it works properly, but if i tick more than 1, not
even one will be updated.
Controller
if (Input::has('orderIds'))
{
Order::whereIn('id',
Input::get('orderIds'))->update(array('top_up_id' =>
$topUp->id));
}
javascript
$('#top-up-pending-payment-table tbody
input:checkbox:checked').each(function(){
orderIdsHtml += '<input type="hidden" name="orderIds[]" value="' +
$(this).data('id') + '">';
});
How can i properly loop this
If i tick one checkbox, it works properly, but if i tick more than 1, not
even one will be updated.
Controller
if (Input::has('orderIds'))
{
Order::whereIn('id',
Input::get('orderIds'))->update(array('top_up_id' =>
$topUp->id));
}
javascript
$('#top-up-pending-payment-table tbody
input:checkbox:checked').each(function(){
orderIdsHtml += '<input type="hidden" name="orderIds[]" value="' +
$(this).data('id') + '">';
});
allow textbox to support numbers and OemMinus only?
allow textbox to support numbers and OemMinus only?
in my code i use this peace of code to validate textbox to support only
numbers
private void card_No_KeyDown(object sender, KeyEventArgs e)
{
nonNumberEntered = false;
// Determine whether the keystroke is a number from the top of the
keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
// Determine whether the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9 &&
e.KeyCode == Keys.Oemplus)
{
// Determine whether the keystroke is a backspace.
if (e.KeyCode != Keys.Back)
{
// A non-numerical keystroke was pressed.
// Set the flag to true and evaluate in KeyPress event.
nonNumberEntered = true;
}
}
}
}
private void card_No_KeyPress(object sender, KeyPressEventArgs e)
{
if (nonNumberEntered == true)
{
MessageBox.Show("not allowed");
e.Handled = true;
}
}`, but know i want my textbox to allow OemMinus (-) character ? how
can i do this?
in my code i use this peace of code to validate textbox to support only
numbers
private void card_No_KeyDown(object sender, KeyEventArgs e)
{
nonNumberEntered = false;
// Determine whether the keystroke is a number from the top of the
keyboard.
if (e.KeyCode < Keys.D0 || e.KeyCode > Keys.D9)
{
// Determine whether the keystroke is a number from the keypad.
if (e.KeyCode < Keys.NumPad0 || e.KeyCode > Keys.NumPad9 &&
e.KeyCode == Keys.Oemplus)
{
// Determine whether the keystroke is a backspace.
if (e.KeyCode != Keys.Back)
{
// A non-numerical keystroke was pressed.
// Set the flag to true and evaluate in KeyPress event.
nonNumberEntered = true;
}
}
}
}
private void card_No_KeyPress(object sender, KeyPressEventArgs e)
{
if (nonNumberEntered == true)
{
MessageBox.Show("not allowed");
e.Handled = true;
}
}`, but know i want my textbox to allow OemMinus (-) character ? how
can i do this?
Error while using in Kaleo
Error while using in Kaleo
I want to create a multiple approver workflow definition xml file.
I have created the below xml file.
<workflow-definition xmlns="urn:liferay.com:liferay-workflow_6.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:liferay.com:liferay-workflow_6.1.0
http://www.liferay.com/dtd/liferay-workflow-definition_6_1_0.xsd">
<name>Multiple Approvers</name>
<description>A multiple approvers can approve a workflow content two
approvals - parallel.</description>
<version>1</version>
<state>
<name>created</name>
<metadata>
<![CDATA[{"xy":[36,51]}]]>
</metadata>
<initial>true</initial>
<transitions>
<transition>
<name>review</name>
<target>review</target>
</transition>
</transitions>
</state>
<task>
<name>update</name>
<metadata>
<![CDATA[{"xy":[397,191]}]]>
</metadata>
<actions>
<notification>
<name>Creator Modification Notification</name>
<template>Your submission was rejected by a reviewer, please
modify and resubmit.</template>
<template-language>text</template-language>
<notification-type>email</notification-type>
<execution-type>onAssignment</execution-type>
</notification>
</actions>
<assignments>
<user />
</assignments>
<transitions>
<transition>
<name>resubmit</name>
<target>review</target>
</transition>
</transitions>
</task>
<fork>
<name>review</name>
<transitions>
<transition>
<name>managerreview</name>
<target>managerreview</target>
</transition>
<transition>
<name>vpreview</name>
<target>vpreview</target>
</transition>
</transitions>
</fork>
<task>
<name>vpreview</name>
<metadata>
<![CDATA[{"xy":[225,45]}]]>
</metadata>
<actions>
<notification>
<name>Review Notification</name>
<template>You have a new submission waiting for your review in
the workflow.</template>
<template-language>text</template-language>
<notification-type>email</notification-type>
<execution-type>onAssignment</execution-type>
</notification>
<notification>
<name>Review Completion Notification</name>
<template>
Your submission has been reviewed and the reviewer has
applied the following ${taskComments}.</template>
<template-language>freemarker</template-language>
<notification-type>email</notification-type>
<recipients>
<user />
</recipients>
<execution-type>onExit</execution-type>
</notification>
</actions>
<assignments>
<roles>
<role>
<role-type>regular</role-type>
<name>Portal Content Reviewer</name>
</role>
<role>
<role-type>regular</role-type>
<name>HR-VP</name>
</role>
<role>
<role-type>regular</role-type>
<name>Finance-VP</name>
</role>
</roles>
</assignments>
<transitions>
<transition>
<name>approve</name>
<target>approved</target>
</transition>
<transition>
<name>reject</name>
<target>update</target>
<default>false</default>
</transition>
</transitions>
</task>
<task>
<name>managerreview</name>
<metadata>
<![CDATA[{"xy":[225,45]}]]>
</metadata>
<actions>
<notification>
<name>Review Notification</name>
<template>You have a new submission waiting for your review in
the workflow.</template>
<template-language>text</template-language>
<notification-type>email</notification-type>
<execution-type>onAssignment</execution-type>
</notification>
<notification>
<name>Review Completion Notification</name>
<template>
Your submission has been reviewed and the reviewer has
applied the following ${taskComments}.</template>
<template-language>freemarker</template-language>
<notification-type>email</notification-type>
<recipients>
<user />
</recipients>
<execution-type>onExit</execution-type>
</notification>
</actions>
<assignments>
<roles>
<role>
<role-type>regular</role-type>
<name>Portal Content Reviewer</name>
</role>
<role>
<role-type>regular</role-type>
<name>Finance-Manager</name>
</role>
<role>
<role-type>regular</role-type>
<name>HR-Manager</name>
</role>
</roles>
</assignments>
<transitions>
<transition>
<name>approve</name>
<target>approved</target>
</transition>
<transition>
<name>reject</name>
<target>update</target>
<default>false</default>
</transition>
</transitions>
</task>
<join>
<name>approved</name>
<transitions>
<transition>
<name>result</name>
<target>done</target>
<default>true</default>
</transition>
</transitions>
</join>
<state>
<name>done</name>
<metadata>
<![CDATA[{"xy":[422,56]}]]>
</metadata>
<actions>
<action>
<name>approve</name>
<script>
<![CDATA[
Packages.com.liferay.portal.kernel.workflow.WorkflowStatusManagerUtil.updateStatus(Packages.com.liferay.portal.kernel.workflow.WorkflowConstants.toStatus("approved"),
workflowContext);
]]>
</script>
<script-language>javascript</script-language>
<execution-type>onEntry</execution-type>
</action>
</actions>
</state>
I uploaded in Control Panel -> Workflow -> Definitions -> Add -> New
Workflow Definition.
An error occurred in the workflow engine as below
Please guide me to solve this error.
Thanks in advance.
Regards, Dinesh
I want to create a multiple approver workflow definition xml file.
I have created the below xml file.
<workflow-definition xmlns="urn:liferay.com:liferay-workflow_6.1.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="urn:liferay.com:liferay-workflow_6.1.0
http://www.liferay.com/dtd/liferay-workflow-definition_6_1_0.xsd">
<name>Multiple Approvers</name>
<description>A multiple approvers can approve a workflow content two
approvals - parallel.</description>
<version>1</version>
<state>
<name>created</name>
<metadata>
<![CDATA[{"xy":[36,51]}]]>
</metadata>
<initial>true</initial>
<transitions>
<transition>
<name>review</name>
<target>review</target>
</transition>
</transitions>
</state>
<task>
<name>update</name>
<metadata>
<![CDATA[{"xy":[397,191]}]]>
</metadata>
<actions>
<notification>
<name>Creator Modification Notification</name>
<template>Your submission was rejected by a reviewer, please
modify and resubmit.</template>
<template-language>text</template-language>
<notification-type>email</notification-type>
<execution-type>onAssignment</execution-type>
</notification>
</actions>
<assignments>
<user />
</assignments>
<transitions>
<transition>
<name>resubmit</name>
<target>review</target>
</transition>
</transitions>
</task>
<fork>
<name>review</name>
<transitions>
<transition>
<name>managerreview</name>
<target>managerreview</target>
</transition>
<transition>
<name>vpreview</name>
<target>vpreview</target>
</transition>
</transitions>
</fork>
<task>
<name>vpreview</name>
<metadata>
<![CDATA[{"xy":[225,45]}]]>
</metadata>
<actions>
<notification>
<name>Review Notification</name>
<template>You have a new submission waiting for your review in
the workflow.</template>
<template-language>text</template-language>
<notification-type>email</notification-type>
<execution-type>onAssignment</execution-type>
</notification>
<notification>
<name>Review Completion Notification</name>
<template>
Your submission has been reviewed and the reviewer has
applied the following ${taskComments}.</template>
<template-language>freemarker</template-language>
<notification-type>email</notification-type>
<recipients>
<user />
</recipients>
<execution-type>onExit</execution-type>
</notification>
</actions>
<assignments>
<roles>
<role>
<role-type>regular</role-type>
<name>Portal Content Reviewer</name>
</role>
<role>
<role-type>regular</role-type>
<name>HR-VP</name>
</role>
<role>
<role-type>regular</role-type>
<name>Finance-VP</name>
</role>
</roles>
</assignments>
<transitions>
<transition>
<name>approve</name>
<target>approved</target>
</transition>
<transition>
<name>reject</name>
<target>update</target>
<default>false</default>
</transition>
</transitions>
</task>
<task>
<name>managerreview</name>
<metadata>
<![CDATA[{"xy":[225,45]}]]>
</metadata>
<actions>
<notification>
<name>Review Notification</name>
<template>You have a new submission waiting for your review in
the workflow.</template>
<template-language>text</template-language>
<notification-type>email</notification-type>
<execution-type>onAssignment</execution-type>
</notification>
<notification>
<name>Review Completion Notification</name>
<template>
Your submission has been reviewed and the reviewer has
applied the following ${taskComments}.</template>
<template-language>freemarker</template-language>
<notification-type>email</notification-type>
<recipients>
<user />
</recipients>
<execution-type>onExit</execution-type>
</notification>
</actions>
<assignments>
<roles>
<role>
<role-type>regular</role-type>
<name>Portal Content Reviewer</name>
</role>
<role>
<role-type>regular</role-type>
<name>Finance-Manager</name>
</role>
<role>
<role-type>regular</role-type>
<name>HR-Manager</name>
</role>
</roles>
</assignments>
<transitions>
<transition>
<name>approve</name>
<target>approved</target>
</transition>
<transition>
<name>reject</name>
<target>update</target>
<default>false</default>
</transition>
</transitions>
</task>
<join>
<name>approved</name>
<transitions>
<transition>
<name>result</name>
<target>done</target>
<default>true</default>
</transition>
</transitions>
</join>
<state>
<name>done</name>
<metadata>
<![CDATA[{"xy":[422,56]}]]>
</metadata>
<actions>
<action>
<name>approve</name>
<script>
<![CDATA[
Packages.com.liferay.portal.kernel.workflow.WorkflowStatusManagerUtil.updateStatus(Packages.com.liferay.portal.kernel.workflow.WorkflowConstants.toStatus("approved"),
workflowContext);
]]>
</script>
<script-language>javascript</script-language>
<execution-type>onEntry</execution-type>
</action>
</actions>
</state>
I uploaded in Control Panel -> Workflow -> Definitions -> Add -> New
Workflow Definition.
An error occurred in the workflow engine as below
Please guide me to solve this error.
Thanks in advance.
Regards, Dinesh
Friday, 13 September 2013
How to overcome duplicate title tag issue on a classified website
How to overcome duplicate title tag issue on a classified website
I have an Automobile classified website.If someone submit an ad for my
website,the heading of the ad automatically generated from the
"make","model","registered year" and a custom text like follows,
Make:-Toyota
Model:-Corolla 121
registered year:-2005
generated heading: Toyota Corolla 121 REG-2005 for sale
Make:-Nissan
Model:-Sunny N16
registered year:-2006
generated heading: Nissan Sunny N16 REG-2006 for sale
And I used this heading as my title tag on the individual ad page.
I have used this method for sometime.
But now those pages are listed in Google webmaster tools with duplicate
title tags,because there are plenty of ads containing same make,model,and
year
Does it make any sense if I use any random id along with the heading to
make ad heading unique.If I do so, will it effect me to blacklist from
google? OR what is the best practices to overcome this issue. Thanks
I have an Automobile classified website.If someone submit an ad for my
website,the heading of the ad automatically generated from the
"make","model","registered year" and a custom text like follows,
Make:-Toyota
Model:-Corolla 121
registered year:-2005
generated heading: Toyota Corolla 121 REG-2005 for sale
Make:-Nissan
Model:-Sunny N16
registered year:-2006
generated heading: Nissan Sunny N16 REG-2006 for sale
And I used this heading as my title tag on the individual ad page.
I have used this method for sometime.
But now those pages are listed in Google webmaster tools with duplicate
title tags,because there are plenty of ads containing same make,model,and
year
Does it make any sense if I use any random id along with the heading to
make ad heading unique.If I do so, will it effect me to blacklist from
google? OR what is the best practices to overcome this issue. Thanks
Which route when combining two HTML create forms
Which route when combining two HTML create forms
Let's say I have the routes
/magazines/new
/magazines/:magazines_ads/new
but I want to display both forms on the same page, because they are very
small and for convenience it would make more sense. How would one handle
this situation normally?
Let's say I have the routes
/magazines/new
/magazines/:magazines_ads/new
but I want to display both forms on the same page, because they are very
small and for convenience it would make more sense. How would one handle
this situation normally?
Get JSON data from array in php
Get JSON data from array in php
I'm trying to use json_decode to get "short_name" from with the
"universities" section of the code attached at the bottom of this post -
it's from Coursera (online course website).
I first do:
$Course= json_decode(file_get_contents(COURSES_URL), true);
Then I have no problem getting the top-level data such as "id" by doing:
$CourseId = $Course['id'];
But when it comes to within the "universities" array, I cant access any
data, I keep getting "Undefined index: short_name" I have tried all sorts,
such as:
$university= $courseraCourse['university']['short_name'];
But I am getting nowhere now...How do you access this data ?
Coursera JSON:
[
{
"subtitle_languages_csv":"",
"photo":"https://s3.amazonaws.com/coursera/topics/ml/large-icon.png",
"preview_link":"https://class.coursera.org/ml/lecture/preview",
"small_icon_hover":"https://s3.amazonaws.com/coursera/topics/ml/small-icon.hover.png",
"large_icon":"https://s3.amazonaws.com/coursera/topics/ml/large-icon.png",
"video":"e0WKJLovaZg",
"university-ids":[
"stanford"
],
"id":2,
"universities":[
{
"rectangular_logo_svg":"",
"wordmark":null,
"website_twitter":"",
"china_mirror":2,
"favicon":"https://coursera-university-assets.s3.amazonaws.com/dc/581cda352d067023dcdcc0d9efd36e/favicon-stanford.ico",
"website_facebook":"",
"logo":"https://coursera-university-assets.s3.amazonaws.com/d8/4c69670e0826e42c6cd80b4a02b9a2/stanford.png",
"background_color":"",
"id":1,
"location_city":"Palo Alto",
"location_country":"US",
"location_lat":37.44188340000000000,
"location":"Palo Alto, CA, United States",
"primary_color":"#8c1515",
"abbr_name":"Stanford",
"website":"",
"description":"The Leland Stanford Junior University, commonly referred to
as Stanford University or Stanford, is an American private research
university located in Stanford, California on an 8,180-acre (3,310 ha)
campus near Palo Alto, California, United States.",
"short_name":"stanford",
"landing_page_banner":"",
"mailing_list_id":null,
"website_youtube":"",
"partner_type":1,
"banner":"",
"location_state":"CA",
"name":"Stanford University",
"square_logo":"",
"square_logo_source":"",
"square_logo_svg":"",
"location_lng":-122.14301949999998000,
"home_link":"http://online.stanford.edu/",
"class_logo":"https://coursera-university-assets.s3.amazonaws.com/21/9a0294e2bf773901afbfcb5ef47d97/Stanford_Coursera-200x48_RedText_BG.png",
"display":true
}
],
I'm trying to use json_decode to get "short_name" from with the
"universities" section of the code attached at the bottom of this post -
it's from Coursera (online course website).
I first do:
$Course= json_decode(file_get_contents(COURSES_URL), true);
Then I have no problem getting the top-level data such as "id" by doing:
$CourseId = $Course['id'];
But when it comes to within the "universities" array, I cant access any
data, I keep getting "Undefined index: short_name" I have tried all sorts,
such as:
$university= $courseraCourse['university']['short_name'];
But I am getting nowhere now...How do you access this data ?
Coursera JSON:
[
{
"subtitle_languages_csv":"",
"photo":"https://s3.amazonaws.com/coursera/topics/ml/large-icon.png",
"preview_link":"https://class.coursera.org/ml/lecture/preview",
"small_icon_hover":"https://s3.amazonaws.com/coursera/topics/ml/small-icon.hover.png",
"large_icon":"https://s3.amazonaws.com/coursera/topics/ml/large-icon.png",
"video":"e0WKJLovaZg",
"university-ids":[
"stanford"
],
"id":2,
"universities":[
{
"rectangular_logo_svg":"",
"wordmark":null,
"website_twitter":"",
"china_mirror":2,
"favicon":"https://coursera-university-assets.s3.amazonaws.com/dc/581cda352d067023dcdcc0d9efd36e/favicon-stanford.ico",
"website_facebook":"",
"logo":"https://coursera-university-assets.s3.amazonaws.com/d8/4c69670e0826e42c6cd80b4a02b9a2/stanford.png",
"background_color":"",
"id":1,
"location_city":"Palo Alto",
"location_country":"US",
"location_lat":37.44188340000000000,
"location":"Palo Alto, CA, United States",
"primary_color":"#8c1515",
"abbr_name":"Stanford",
"website":"",
"description":"The Leland Stanford Junior University, commonly referred to
as Stanford University or Stanford, is an American private research
university located in Stanford, California on an 8,180-acre (3,310 ha)
campus near Palo Alto, California, United States.",
"short_name":"stanford",
"landing_page_banner":"",
"mailing_list_id":null,
"website_youtube":"",
"partner_type":1,
"banner":"",
"location_state":"CA",
"name":"Stanford University",
"square_logo":"",
"square_logo_source":"",
"square_logo_svg":"",
"location_lng":-122.14301949999998000,
"home_link":"http://online.stanford.edu/",
"class_logo":"https://coursera-university-assets.s3.amazonaws.com/21/9a0294e2bf773901afbfcb5ef47d97/Stanford_Coursera-200x48_RedText_BG.png",
"display":true
}
],
Removing Format from the already formatted string
Removing Format from the already formatted string
I need to remove the from the string where i have already formated.
For eg:
class Helper {
public string GetFormatedString(string format, object value)
{
return String.Format(format,value);
}
public value GetValue(string formatedString, string format)
{
// TODO: here need to implement
//Here we need to remove "format" applied on formatedString variable
and return.
// Is there a way to remove the format from formated string ?
//return null;
}
}
Is there a way to remove the format from formated string ?
Thanks Dinesh S
I need to remove the from the string where i have already formated.
For eg:
class Helper {
public string GetFormatedString(string format, object value)
{
return String.Format(format,value);
}
public value GetValue(string formatedString, string format)
{
// TODO: here need to implement
//Here we need to remove "format" applied on formatedString variable
and return.
// Is there a way to remove the format from formated string ?
//return null;
}
}
Is there a way to remove the format from formated string ?
Thanks Dinesh S
Use django's modelform validation with angularjs
Use django's modelform validation with angularjs
I have been asked to rewrite the admin dashboard that comes with Django
and make it into a single page app.
I am noob to angular and what I understand till now is that I will be
creating a form just like my admin-forms in the angular-project. This form
when post will interact with django using tasty-pie.
Is there a way through which I can create the forms in angular using
django's ModelForm ?
The idea here is that I can use all the existing forms in various apps
that exist in my project and re-use the ModelForm validation like clean().
Is this even possible ?
I have been asked to rewrite the admin dashboard that comes with Django
and make it into a single page app.
I am noob to angular and what I understand till now is that I will be
creating a form just like my admin-forms in the angular-project. This form
when post will interact with django using tasty-pie.
Is there a way through which I can create the forms in angular using
django's ModelForm ?
The idea here is that I can use all the existing forms in various apps
that exist in my project and re-use the ModelForm validation like clean().
Is this even possible ?
Thursday, 12 September 2013
Can we able to run a decompiled java (jar to java)
Can we able to run a decompiled java (jar to java)
I have decompiled the jar file. Can we able to run this file using eclipse
or some other IDE. Or any way to do this. Thanks in Advance.
I have decompiled the jar file. Can we able to run this file using eclipse
or some other IDE. Or any way to do this. Thanks in Advance.
dense ranking based on a quantity field without distinct join on two tables
dense ranking based on a quantity field without distinct join on two tables
I have a very strange requirement at site, I have two tables Header and
Details. I can join on two fields [Item Code] and [Contract Number] but
they are not unique. But the end result which they are expecting is to
select the records from the details table based on a quantity field in
header. I know this sounds crazy but they dont have any other distinct
joins.
Ex: Header table
Item code |Contract Number | Quantity
1000 50000 2 1000 50000 3 1000 50000 2
Item Table
Item code |Contract Number | Work Order
1000 50000 abc 1000 50000 def 1000 50000 ghi 1000 50000 jkl 1000 50000 mno
1000 50000 pqr 1000 50000 stv
Now, I need to pick the work orders based on quantity i.e for first row in
header with quantity 2 I need to pick first two records in Item table and
like wise.
Need to fix ASAP. Could anyone help tackle this issue?
Millions of thanks in advance!!!!!!!
Prabhu
I have a very strange requirement at site, I have two tables Header and
Details. I can join on two fields [Item Code] and [Contract Number] but
they are not unique. But the end result which they are expecting is to
select the records from the details table based on a quantity field in
header. I know this sounds crazy but they dont have any other distinct
joins.
Ex: Header table
Item code |Contract Number | Quantity
1000 50000 2 1000 50000 3 1000 50000 2
Item Table
Item code |Contract Number | Work Order
1000 50000 abc 1000 50000 def 1000 50000 ghi 1000 50000 jkl 1000 50000 mno
1000 50000 pqr 1000 50000 stv
Now, I need to pick the work orders based on quantity i.e for first row in
header with quantity 2 I need to pick first two records in Item table and
like wise.
Need to fix ASAP. Could anyone help tackle this issue?
Millions of thanks in advance!!!!!!!
Prabhu
Using the mic as sound impact sensor
Using the mic as sound impact sensor
I want to use the mic of an Android device as sound impact sensor (like in
some music visulization projects).
Example: http://www.youtube.com/watch?v=pJGM3PiYpqk
I wasn't able to find anything related here or via google.
Is this possible with as little delay as possible and without recording to
a file?
I want to use the mic of an Android device as sound impact sensor (like in
some music visulization projects).
Example: http://www.youtube.com/watch?v=pJGM3PiYpqk
I wasn't able to find anything related here or via google.
Is this possible with as little delay as possible and without recording to
a file?
Implicit conversion paradox
Implicit conversion paradox
If I try to define an implicit conversion for a primitive type, then it
doesn't seem to work. E.g.:
implicit def globalIntToString(a: Int) : String = { a.toString() +
"globalhi" }
1.toInt + "hi"
The above will still return simply "1hi" as the result.
However, it seems that if I parameterize a class or a def and then pass in
the implicit for the parametrized case, then it seems to work. Does anyone
know what the reasons are? E.g. does this have something to do with
boxing/unboxing of primtives (e.g., parameterized primitives are boxed)?
Does implicit only work with reference types and not primitive types?
class typeConv[T] { implicit def tToStr(a: T) : String = { a.toString() +
"hi" } }
class t[K](a: K)(tc : typeConv[K]) { import tc._; println(a + "cool");
println(1.toInt + "cool" ) }
new t(1)(new typeConv[Int])
If I try to define an implicit conversion for a primitive type, then it
doesn't seem to work. E.g.:
implicit def globalIntToString(a: Int) : String = { a.toString() +
"globalhi" }
1.toInt + "hi"
The above will still return simply "1hi" as the result.
However, it seems that if I parameterize a class or a def and then pass in
the implicit for the parametrized case, then it seems to work. Does anyone
know what the reasons are? E.g. does this have something to do with
boxing/unboxing of primtives (e.g., parameterized primitives are boxed)?
Does implicit only work with reference types and not primitive types?
class typeConv[T] { implicit def tToStr(a: T) : String = { a.toString() +
"hi" } }
class t[K](a: K)(tc : typeConv[K]) { import tc._; println(a + "cool");
println(1.toInt + "cool" ) }
new t(1)(new typeConv[Int])
Title Tag Does Not Update TextView - Java/Android
Title Tag Does Not Update TextView - Java/Android
I have an android app which is supposed to pull the title tags off of
google.com and replace my textview with the title tag (it should simply
say: google.com) however when I click my "load webpage" button the
textview simply disappears and is never updated with the title tag and I'm
not sure exactly why this is happening.
SOURCE:
package com.example.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView textView;
private String response;
public interface Callback {
void onModifiedTextView(String value);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.TextView01);
textView.setVisibility(View.VISIBLE);
}
public void onModifiedTextView(final String title) {
runOnUiThread(new Runnable() {
public void run() {
textView.setText(title);
}
});
}
public class DownloadWebPageTask extends AsyncTask<String, Void,
String> {
public DownloadWebPageTask(MainActivity mainActivity) {
this.callback = mainActivity;
}
private MainActivity callback;
private String title;
public DownloadWebPageTask() {
// TODO Auto-generated constructor stub
}
public DownloadWebPageTask(TextView textView) {
// TODO Auto-generated constructor stub
}
@Override
protected String doInBackground(String... urls) {
String response = title;
for (String url : urls) {
try {
Document doc = Jsoup.connect("http://google.com")
.userAgent("Mozilla")
.get();
// get page title
String title = doc.title();
System.out.println("title : " + title);
// get all links
Elements links = doc.select("a[href]");
for (Element link : links) {
// get the value from href attribute
System.out.println("\nlink : " + link.attr("href"));
System.out.println("text : " + link.text());
}
} catch (IOException e) {
e.printStackTrace();
}
}
// callback.onModifiedTextView(response);
return response;
}
@Override
protected void onPostExecute(final String title) {
callback.onModifiedTextView(title);
callback.onModifiedTextView(response);
}
}
public void onClick(View view) {
DownloadWebPageTask task = new DownloadWebPageTask(this);
task.execute(new String[] { "http://www.google.com" });
}
}
EDIT IN RESPONSE TO FIRST ANSWER:
package com.example.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView textView;
private String response;
String title;
public interface Callback {
void onModifiedTextView(String value);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.TextView01);
textView.setVisibility(View.VISIBLE);
}
public void onModifiedTextView(final String title) {
runOnUiThread(new Runnable() {
public void run() {
textView.setText(title);
textView.invalidate(); // not even necessary
}
});
}
public class DownloadWebPageTask extends AsyncTask<String, Void,
String> {
public DownloadWebPageTask(MainActivity mainActivity) {
this.callback = mainActivity;
}
private MainActivity callback;
// private String title;
public DownloadWebPageTask() {
// TODO Auto-generated constructor stub
}
public DownloadWebPageTask(TextView textView) {
// TODO Auto-generated constructor stub
}
@Override
protected String doInBackground(String... urls) {
//String response = title;
for (String url : urls) {
try {
Document doc = Jsoup.connect("http://google.com")
.userAgent("Mozilla")
.get();
// get page title
title = doc.title();
System.out.println("title : " + title);
// get all links
Elements links = doc.select("a[href]");
for (Element link : links) {
// get the value from href attribute
System.out.println("\nlink : " + link.attr("href"));
System.out.println("text : " + link.text());
}
} catch (IOException e) {
e.printStackTrace();
}
}
// callback.onModifiedTextView(response);
return response;
}
@Override
protected void onPostExecute(final String title) {
callback.onModifiedTextView(title);
callback.onModifiedTextView(response);
}
}
public void onClick(View view) {
DownloadWebPageTask task = new DownloadWebPageTask(this);
task.execute(new String[] { "http://www.google.com" });
}
}
I have an android app which is supposed to pull the title tags off of
google.com and replace my textview with the title tag (it should simply
say: google.com) however when I click my "load webpage" button the
textview simply disappears and is never updated with the title tag and I'm
not sure exactly why this is happening.
SOURCE:
package com.example.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView textView;
private String response;
public interface Callback {
void onModifiedTextView(String value);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.TextView01);
textView.setVisibility(View.VISIBLE);
}
public void onModifiedTextView(final String title) {
runOnUiThread(new Runnable() {
public void run() {
textView.setText(title);
}
});
}
public class DownloadWebPageTask extends AsyncTask<String, Void,
String> {
public DownloadWebPageTask(MainActivity mainActivity) {
this.callback = mainActivity;
}
private MainActivity callback;
private String title;
public DownloadWebPageTask() {
// TODO Auto-generated constructor stub
}
public DownloadWebPageTask(TextView textView) {
// TODO Auto-generated constructor stub
}
@Override
protected String doInBackground(String... urls) {
String response = title;
for (String url : urls) {
try {
Document doc = Jsoup.connect("http://google.com")
.userAgent("Mozilla")
.get();
// get page title
String title = doc.title();
System.out.println("title : " + title);
// get all links
Elements links = doc.select("a[href]");
for (Element link : links) {
// get the value from href attribute
System.out.println("\nlink : " + link.attr("href"));
System.out.println("text : " + link.text());
}
} catch (IOException e) {
e.printStackTrace();
}
}
// callback.onModifiedTextView(response);
return response;
}
@Override
protected void onPostExecute(final String title) {
callback.onModifiedTextView(title);
callback.onModifiedTextView(response);
}
}
public void onClick(View view) {
DownloadWebPageTask task = new DownloadWebPageTask(this);
task.execute(new String[] { "http://www.google.com" });
}
}
EDIT IN RESPONSE TO FIRST ANSWER:
package com.example.test;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends Activity {
private TextView textView;
private String response;
String title;
public interface Callback {
void onModifiedTextView(String value);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.TextView01);
textView.setVisibility(View.VISIBLE);
}
public void onModifiedTextView(final String title) {
runOnUiThread(new Runnable() {
public void run() {
textView.setText(title);
textView.invalidate(); // not even necessary
}
});
}
public class DownloadWebPageTask extends AsyncTask<String, Void,
String> {
public DownloadWebPageTask(MainActivity mainActivity) {
this.callback = mainActivity;
}
private MainActivity callback;
// private String title;
public DownloadWebPageTask() {
// TODO Auto-generated constructor stub
}
public DownloadWebPageTask(TextView textView) {
// TODO Auto-generated constructor stub
}
@Override
protected String doInBackground(String... urls) {
//String response = title;
for (String url : urls) {
try {
Document doc = Jsoup.connect("http://google.com")
.userAgent("Mozilla")
.get();
// get page title
title = doc.title();
System.out.println("title : " + title);
// get all links
Elements links = doc.select("a[href]");
for (Element link : links) {
// get the value from href attribute
System.out.println("\nlink : " + link.attr("href"));
System.out.println("text : " + link.text());
}
} catch (IOException e) {
e.printStackTrace();
}
}
// callback.onModifiedTextView(response);
return response;
}
@Override
protected void onPostExecute(final String title) {
callback.onModifiedTextView(title);
callback.onModifiedTextView(response);
}
}
public void onClick(View view) {
DownloadWebPageTask task = new DownloadWebPageTask(this);
task.execute(new String[] { "http://www.google.com" });
}
}
Ubuntu : Connecting Ubuntu to a projector
Ubuntu : Connecting Ubuntu to a projector
I have an HP laptop that I made dual boot: Windows 8 and Ubuntu
12.04...(one at a time)
I want to connect the laptop to a projector: Whiles it works perfectly in
Windows 8 it will not show any signal if it is in ubuntu. I have tried all
possible suggestions like: 1. C-F5 .......and even all other functions ,
fn-f5.....and many more it will not work. 2. I have gone to system
settings -----> Displays....and tried all possible settings it will still
not work.
Does any one know how I can resolve this in Ubuntu connection to a projector.
Thanks
Wasteva
I have an HP laptop that I made dual boot: Windows 8 and Ubuntu
12.04...(one at a time)
I want to connect the laptop to a projector: Whiles it works perfectly in
Windows 8 it will not show any signal if it is in ubuntu. I have tried all
possible suggestions like: 1. C-F5 .......and even all other functions ,
fn-f5.....and many more it will not work. 2. I have gone to system
settings -----> Displays....and tried all possible settings it will still
not work.
Does any one know how I can resolve this in Ubuntu connection to a projector.
Thanks
Wasteva
Is it possible to have a :after pseudo element on a button?
Is it possible to have a :after pseudo element on a button?
I have a button and on a hover i want a after element to show. But i can't
see it. Is it impossible to have a :after element on a button?
html:
<button class="button button-primary">My button</button>
css/sass:
.button { cursor:pointer; height:30px;}
.button-primary {
color:$regular-text-light;
background-color: $dark-blue;
border:none;
&:hover:after {
display: block;
position:relative;
top: 3px;
right:3px;
width:100px;
height:5px;
background-color: $dark-blue;
}
I have a button and on a hover i want a after element to show. But i can't
see it. Is it impossible to have a :after element on a button?
html:
<button class="button button-primary">My button</button>
css/sass:
.button { cursor:pointer; height:30px;}
.button-primary {
color:$regular-text-light;
background-color: $dark-blue;
border:none;
&:hover:after {
display: block;
position:relative;
top: 3px;
right:3px;
width:100px;
height:5px;
background-color: $dark-blue;
}
Advanced Compiler for JS, PHP, HTML and CSS with Multiple Files
Advanced Compiler for JS, PHP, HTML and CSS with Multiple Files
I've not been able to find one, but does anyone know of a compiler for
javascript that compresses all variable names, white spaces etc and
validates the script for any errors?
Closure compiler has an advanced option but it won't work for my purposes:
I have mandatory ajax calls.
The ajax calls output javascript to be evaluated by the eval() function.
The answer I think is to have a closure compiler with the advanced option
for multiple scripts and wherever the same variable name is used, the same
substitute short character is replaced by it etc.
Does anyone know of an application with these features? If so, is there a
similar one for php, css and html?
Thanks for reading, most likely I will get back tomorrow to read the answers.
Regards, Oscar
I've not been able to find one, but does anyone know of a compiler for
javascript that compresses all variable names, white spaces etc and
validates the script for any errors?
Closure compiler has an advanced option but it won't work for my purposes:
I have mandatory ajax calls.
The ajax calls output javascript to be evaluated by the eval() function.
The answer I think is to have a closure compiler with the advanced option
for multiple scripts and wherever the same variable name is used, the same
substitute short character is replaced by it etc.
Does anyone know of an application with these features? If so, is there a
similar one for php, css and html?
Thanks for reading, most likely I will get back tomorrow to read the answers.
Regards, Oscar
Wednesday, 11 September 2013
magento get coupon details from price rule
magento get coupon details from price rule
How do i get the coupons details from rule id.
i am able to getting all the rules from the following code,
$sopping_cart_rules =
Mage::getResourceModel('salesrule/rule_collection')->load();
$sopping_cart_rule_info = array();
foreach ($sopping_cart_rules as $rule) {
//only for active rules
if ($rule->getIsActive()) {
$sopping_cart_rule_info['shopping_cart_rules'] = array(
'id'=>$rule->getId(),
'name'=>$rule->getName()
);
}
}
But, how do i get the coupon codes from rule id(i.e passing rule id as the
parameter )
How do i get the coupons details from rule id.
i am able to getting all the rules from the following code,
$sopping_cart_rules =
Mage::getResourceModel('salesrule/rule_collection')->load();
$sopping_cart_rule_info = array();
foreach ($sopping_cart_rules as $rule) {
//only for active rules
if ($rule->getIsActive()) {
$sopping_cart_rule_info['shopping_cart_rules'] = array(
'id'=>$rule->getId(),
'name'=>$rule->getName()
);
}
}
But, how do i get the coupon codes from rule id(i.e passing rule id as the
parameter )
header location not working properly php
header location not working properly php
can some point me out why the below isn't working? It only redirects to
the first location even though I choose different radio buttons.
if(isset($_POST['submit'])){
if(!empty($_POST['electronics'])){
if($_POST['electronics'] = "camera"){
header("location: camera.php"); exit();
}
if($_POST['electronics'] = "cell"){
header("location: cellphones.php"); exit();
}
if($_POST['electronics'] = "cable"){
header("location: cables.php"); exit();
}
if($_POST['electronics'] = "tv"){
header("location: tv.php"); exit();
}
}
<form action="" method="post">
<input type="radio" name="electronics" value="cell"/>
<input type="radio" name="electronics" value="camera"/>
<input type="radio" name="electronics" value="cable"/>
<input type="radio" name="electronics" value="tv"/>
<input type="submit" name="submit">
</form>
can some point me out why the below isn't working? It only redirects to
the first location even though I choose different radio buttons.
if(isset($_POST['submit'])){
if(!empty($_POST['electronics'])){
if($_POST['electronics'] = "camera"){
header("location: camera.php"); exit();
}
if($_POST['electronics'] = "cell"){
header("location: cellphones.php"); exit();
}
if($_POST['electronics'] = "cable"){
header("location: cables.php"); exit();
}
if($_POST['electronics'] = "tv"){
header("location: tv.php"); exit();
}
}
<form action="" method="post">
<input type="radio" name="electronics" value="cell"/>
<input type="radio" name="electronics" value="camera"/>
<input type="radio" name="electronics" value="cable"/>
<input type="radio" name="electronics" value="tv"/>
<input type="submit" name="submit">
</form>
How to prevent multiple joins to the same table when using PredicateBuilder
How to prevent multiple joins to the same table when using PredicateBuilder
In this example I am using the NorthWind database supplied by MS.
I am trying to use a predicate builder to assemble multiple
Expression<Func<T,bool>>
into a single expression tree. It mostly works great in my opinion, but
there is one major flaw that I can't seem to address.
I currently have two expressions defined as such:
Expression<Func<Customer, bool>> UnitPriceLessThan2 = c =>
c.Orders.Any(o => o.Order_Details.Any(d => d.Product.UnitPrice <= 2));
Expression<Func<Customer, bool>> UnitPriceGreaterThan5 = c =>
c.Orders.Any(o => o.Order_Details.Any(d => d.Product.UnitPrice >= 5));
I use the universal predicate builder from Pete Montgomery to OR these two
together like such:
Expression<Func<Customer,bool>> PriceMoreThan5orLessThan2 =
UnitPriceLessThan2.Or(UnitPriceGreaterThan5);
Both of those expressions need to navigate to the Product entity through
the same path, so it makes sense to reuse the same sub query for both
conditions. If I was just manually writing the condition it would look
something like this:
Expression<Func<Customer,bool>> PriceMoreThan5orLessThan2 = c =>
c.Orders.Any(o => o.Order_Details.Any(d => d.Product.UnitPrice >= 5 ||
d.Product.UnitPrice <= 2));
However, because of the requirements to build these predicates
dynamically, I can't do that because there would be hundreds of possible
combinations...or more.
So my question is how can I prevent LINQ to Entities from creating a query
like this:
SELECT
/*all the customer columns*/
FROM [dbo].[Customers] AS [Extent1]
WHERE ( EXISTS (SELECT
1 AS [C1]
FROM ( SELECT
[Extent2].[OrderID] AS [OrderID]
FROM [dbo].[Orders] AS [Extent2]
WHERE [Extent1].[CustomerID] = [Extent2].[CustomerID]
) AS [Project1]
WHERE EXISTS (SELECT
1 AS [C1]
FROM [dbo].[Order Details] AS [Extent3]
INNER JOIN [dbo].[Products] AS [Extent4] ON [Extent3].[ProductID]
= [Extent4].[ProductID]
WHERE ([Project1].[OrderID] = [Extent3].[OrderID]) AND
([Extent4].[UnitPrice] <= cast(2 as decimal(18)))
)
)) OR ( EXISTS (SELECT
1 AS [C1]
FROM ( SELECT
[Extent5].[OrderID] AS [OrderID]
FROM [dbo].[Orders] AS [Extent5]
WHERE [Extent1].[CustomerID] = [Extent5].[CustomerID]
) AS [Project4]
WHERE EXISTS (SELECT
1 AS [C1]
FROM [dbo].[Order Details] AS [Extent6]
INNER JOIN [dbo].[Products] AS [Extent7] ON [Extent6].[ProductID]
= [Extent7].[ProductID]
WHERE ([Project4].[OrderID] = [Extent6].[OrderID]) AND
(([Extent7].[UnitPrice] >= cast(5 as decimal(18)))))));
The problem being that we've created two EXISTS sub queries when we really
only needed one.
Instead I would like the query to look like this:
SELECT
/*all the customer columns*/
FROM [dbo].[Customers] AS [Extent1]
WHERE( EXISTS (SELECT
1 AS [C1]
FROM ( SELECT
[Extent5].[OrderID] AS [OrderID]
FROM [dbo].[Orders] AS [Extent5]
WHERE [Extent1].[CustomerID] = [Extent5].[CustomerID]
) AS [Project4]
WHERE EXISTS (SELECT
1 AS [C1]
FROM [dbo].[Order Details] AS [Extent6]
INNER JOIN [dbo].[Products] AS [Extent7] ON [Extent6].[ProductID]
= [Extent7].[ProductID]
WHERE ([Project4].[OrderID] = [Extent6].[OrderID]) AND
(([Extent7].[UnitPrice] >= cast(5 as decimal(18))) OR
([Extent7].[UnitPrice] <= cast(2 as decimal(18))))
)
))
Can I somehow store and reuse the navigation path as an expression and
then inject the two conditions with their appropriate user supplied
operators and values into that?
Or use some expression visitor implementation to...I don't know what
exactly, find and replace?
Thank you for reading my rather lengthy question :)
In this example I am using the NorthWind database supplied by MS.
I am trying to use a predicate builder to assemble multiple
Expression<Func<T,bool>>
into a single expression tree. It mostly works great in my opinion, but
there is one major flaw that I can't seem to address.
I currently have two expressions defined as such:
Expression<Func<Customer, bool>> UnitPriceLessThan2 = c =>
c.Orders.Any(o => o.Order_Details.Any(d => d.Product.UnitPrice <= 2));
Expression<Func<Customer, bool>> UnitPriceGreaterThan5 = c =>
c.Orders.Any(o => o.Order_Details.Any(d => d.Product.UnitPrice >= 5));
I use the universal predicate builder from Pete Montgomery to OR these two
together like such:
Expression<Func<Customer,bool>> PriceMoreThan5orLessThan2 =
UnitPriceLessThan2.Or(UnitPriceGreaterThan5);
Both of those expressions need to navigate to the Product entity through
the same path, so it makes sense to reuse the same sub query for both
conditions. If I was just manually writing the condition it would look
something like this:
Expression<Func<Customer,bool>> PriceMoreThan5orLessThan2 = c =>
c.Orders.Any(o => o.Order_Details.Any(d => d.Product.UnitPrice >= 5 ||
d.Product.UnitPrice <= 2));
However, because of the requirements to build these predicates
dynamically, I can't do that because there would be hundreds of possible
combinations...or more.
So my question is how can I prevent LINQ to Entities from creating a query
like this:
SELECT
/*all the customer columns*/
FROM [dbo].[Customers] AS [Extent1]
WHERE ( EXISTS (SELECT
1 AS [C1]
FROM ( SELECT
[Extent2].[OrderID] AS [OrderID]
FROM [dbo].[Orders] AS [Extent2]
WHERE [Extent1].[CustomerID] = [Extent2].[CustomerID]
) AS [Project1]
WHERE EXISTS (SELECT
1 AS [C1]
FROM [dbo].[Order Details] AS [Extent3]
INNER JOIN [dbo].[Products] AS [Extent4] ON [Extent3].[ProductID]
= [Extent4].[ProductID]
WHERE ([Project1].[OrderID] = [Extent3].[OrderID]) AND
([Extent4].[UnitPrice] <= cast(2 as decimal(18)))
)
)) OR ( EXISTS (SELECT
1 AS [C1]
FROM ( SELECT
[Extent5].[OrderID] AS [OrderID]
FROM [dbo].[Orders] AS [Extent5]
WHERE [Extent1].[CustomerID] = [Extent5].[CustomerID]
) AS [Project4]
WHERE EXISTS (SELECT
1 AS [C1]
FROM [dbo].[Order Details] AS [Extent6]
INNER JOIN [dbo].[Products] AS [Extent7] ON [Extent6].[ProductID]
= [Extent7].[ProductID]
WHERE ([Project4].[OrderID] = [Extent6].[OrderID]) AND
(([Extent7].[UnitPrice] >= cast(5 as decimal(18)))))));
The problem being that we've created two EXISTS sub queries when we really
only needed one.
Instead I would like the query to look like this:
SELECT
/*all the customer columns*/
FROM [dbo].[Customers] AS [Extent1]
WHERE( EXISTS (SELECT
1 AS [C1]
FROM ( SELECT
[Extent5].[OrderID] AS [OrderID]
FROM [dbo].[Orders] AS [Extent5]
WHERE [Extent1].[CustomerID] = [Extent5].[CustomerID]
) AS [Project4]
WHERE EXISTS (SELECT
1 AS [C1]
FROM [dbo].[Order Details] AS [Extent6]
INNER JOIN [dbo].[Products] AS [Extent7] ON [Extent6].[ProductID]
= [Extent7].[ProductID]
WHERE ([Project4].[OrderID] = [Extent6].[OrderID]) AND
(([Extent7].[UnitPrice] >= cast(5 as decimal(18))) OR
([Extent7].[UnitPrice] <= cast(2 as decimal(18))))
)
))
Can I somehow store and reuse the navigation path as an expression and
then inject the two conditions with their appropriate user supplied
operators and values into that?
Or use some expression visitor implementation to...I don't know what
exactly, find and replace?
Thank you for reading my rather lengthy question :)
Get ID from ROW and include in a linkable result - PHP MYSQL
Get ID from ROW and include in a linkable result - PHP MYSQL
I have this code for a search engine. I need to make linkable the results,
only in the column name, but when I add the code ALL the colums turns as a
link.
Here is how the results looks like now: http://postimg.org/image/59y36mih7/
I need to construct the link for the column name in this way:
http://www.mysite.com/id, (coma included)
Can you help me how to make the query to get the info from id column and
make only the results from name column clickable? I´m quite lost.
> <?php
>
>
>
> $MySQLPassword = "*****";
> $HostName = "***";
> $UserName = "***";
> $Database = "****";
>
> mysql_connect($HostName,$UserName,$MySQLPassword)
> or die("ERROR: Could not connect to database!");
> mysql_select_db($Database) or die("cannot select db");
>
>
> $default_sort = 'ID';
> $allowed_order = array ('name','description');
>
> if (!isset ($_GET['order']) ||
> !in_array ($_GET['order'], $allowed_order)) {
> $order = $default_sort;
> } else {
> $order = $_GET['order'];
> }
>
>
> if (isset($_GET['keyword'])) {
>
> if(!$_GET['keyword']) {
> die('<p>Please enter a search term.</p>');
> }
>
>
>
>
>
> /////////////////////////HERE IS THE BEGINING OF CODE WHERE I THINK
> SHOULD BE THE PROBLEM ////////////////////////////
>
> $tables = 'reports';
> $return_fields = 'name organizer_id no_pages publication_date price';
> $check_fields = 'name description';
>
>
> $query_text = $_GET['keyword'];
>
> $clean_query_text =cleanQuery($query_text);
>
> $newquery=bq_simple ($return_fields, $tables, $check_fields,
$clean_query_text);
> $newquery = $newquery . " ORDER BY $order;";
>
> $result = mysql_query($newquery) or die(mysql_error());
>
>
> $numrows = mysql_num_rows($result);
> if ($numrows == 0) {
> echo "<H4>No data to display!</H4>";
> exit;
> }
> echo "<p>Your search '$query_text' returned ".$numrows. "
results.</p>\n";
> echo "<p>Click on the headings to sort.</p>\n";
>
> $row = mysql_fetch_assoc ($result);
> echo "<TABLE border=1>\n";
> echo "<TR>\n";
> foreach ($row as $heading=>$column) {
>
>
> echo "<TD><b>";
> if (in_array ($heading, $allowed_order)) {
> echo "<a
href=\"{$_SERVER['PHP_SELF']}?order=$heading&keyword=$query_text\">$heading</a>";
> } else {
> echo $heading;
> }
> echo "</b></TD>\n";
> }
> echo "</TR>\n";
>
mysql_data_seek ($result, 0); while ($row =
> mysql_fetch_assoc ($result)) {
> echo "<TR>\n";
> foreach ($row as $column) {
> echo "<TD><a href='http://mysite.com/(here should be the
ID)'>$column</TD>\n";
> }
> echo "</TR>\n"; } echo "</TABLE>\n"; }
>
> ////////////////////////FINISH OF THE CODE WITH PROBLEM
> ////////////////////////////
>
> /* * * * * * * * * * * * * * F U N C T I O N S * * * * * * * * * * *
> */
>
> function cleanQuery($string)
> {
> $string = trim($string);
> $string = strip_tags($string); // remove any html/javascript.
>
> if(get_magic_quotes_gpc()) // prevents duplicate backslashes
> {
> $string = stripslashes($string);
> }
> if (phpversion() >= '4.3.0')
> {
> $string = mysql_real_escape_string($string);
> }
> else
> {
> $string = mysql_escape_string($string);
> }
> return $string;
> }
>
>
> function bq_handle_shorthand($text) {
> $text = preg_replace("/ \+/", " and ", $text);
> $text = preg_replace("/ -/", " not ", $text);
> return $text; }
>
>
> function bq_explode_respect_quotes($line) {
> $quote_level = 0; #keep track if we are in or out of quote-space
> $buffer = "";
>
> for ($a = 0; $a < strlen($line); $a++) {
> if ($line[$a] == "\"") {
> $quote_level++;
> if ($quote_level == 2) { $quote_level = 0; }
> }
> else {
> if ($line[$a] == " " and $quote_level == 0) {
> $buffer = $buffer . "~~~~"; #Hackish
magic key
> }
> else {
> $buffer = $buffer . $line[$a];
> }
> }
>
> }
>
> $buffer = str_replace("\\", "", $buffer);
>
> $array = explode("~~~~", $buffer);
> return $array; }
>
>
> function bq_make_subquery($fields, $word, $mode) {
>
> if ($mode == "not") {
> $back = " LIKE '%$word%'))";
> }
> else {
> $back = " LIKE '%$word%')";
> }
>
> if ($mode == "not") {
> $front = "(NOT (";
> $glue = " LIKE '%$word%' AND ";
> }
> else {
> $front = "(";
> $glue = " LIKE '%$word%' AND ";
> }
>
> $text = str_replace(" ", $glue, $fields);
> $text = $front . $text . $back;
>
> return $text; }
>
>
>
> function bq_make_query($fields, $text) {
>
> $text = strtolower($text);
>
>
> $text = bq_handle_shorthand($text);
>
>
> $wordarray = bq_explode_respect_quotes($text);
>
> $buffer = "";
> $output = "";
>
> for ($i = 0; $i<count($wordarray); $i++) {
> $word = $wordarray[$i];
>
> if ($word == "and" or $word == "not" and $i > 0) {
> if ($word == "not") {
>
>
> $i++;
> if ($i == 1) { #invalid sql syntax to prefix the first
check with and/or/not
> $buffer = bq_make_subquery($fields, $wordarray[$i],
"not");
> }
> else {
> $buffer = " AND " . bq_make_subquery($fields,
$wordarray[$i], "not");
> }
> }
> else {
> if ($word == "and") {
> $i++;
> if ($i == 1) {
> $buffer = bq_make_subquery($fields,
$wordarray[$i], "");
> }
> else {
>
> $buffer = " AND " . bq_make_subquery($fields,
$wordarray[$i], "");
> }
> }
> else {
> if ($word == "and") {
> $i++;
> if ($i == 1) {
> $buffer = bq_make_subquery($fields,
$wordarray[$i], "");
> }
> else {
>
> $buffer = " AND " .
bq_make_subquery($fields, $wordarray[$i],
"");
> }
> }
> }
> }
> }
> else {
> if ($i == 0) { # 0 instead of 1 here because there was no
conditional word to skip and no $i++;
> $buffer = bq_make_subquery($fields, $wordarray[$i], "");
> }
> else {
> $buffer = " AND " . bq_make_subquery($fields,
$wordarray[$i], "");
> }
> }
> $output = $output . $buffer;
> }
> return $output; }
>
>
>
> function bq_simple ($return_fields, $tables, $check_fields,
> $query_text) {
>
>
> $return_fields = str_replace(" ", ", ", $return_fields);
> $tables = str_replace(" ", ", ", $tables);
>
>
> $query = "SELECT $return_fields FROM $tables WHERE ";
> $query = $query . bq_make_query($check_fields, $query_text);
>
> #
> # Uncomment to debug
> #
>
> return $query; }
>
>
>
> ?>
I have this code for a search engine. I need to make linkable the results,
only in the column name, but when I add the code ALL the colums turns as a
link.
Here is how the results looks like now: http://postimg.org/image/59y36mih7/
I need to construct the link for the column name in this way:
http://www.mysite.com/id, (coma included)
Can you help me how to make the query to get the info from id column and
make only the results from name column clickable? I´m quite lost.
> <?php
>
>
>
> $MySQLPassword = "*****";
> $HostName = "***";
> $UserName = "***";
> $Database = "****";
>
> mysql_connect($HostName,$UserName,$MySQLPassword)
> or die("ERROR: Could not connect to database!");
> mysql_select_db($Database) or die("cannot select db");
>
>
> $default_sort = 'ID';
> $allowed_order = array ('name','description');
>
> if (!isset ($_GET['order']) ||
> !in_array ($_GET['order'], $allowed_order)) {
> $order = $default_sort;
> } else {
> $order = $_GET['order'];
> }
>
>
> if (isset($_GET['keyword'])) {
>
> if(!$_GET['keyword']) {
> die('<p>Please enter a search term.</p>');
> }
>
>
>
>
>
> /////////////////////////HERE IS THE BEGINING OF CODE WHERE I THINK
> SHOULD BE THE PROBLEM ////////////////////////////
>
> $tables = 'reports';
> $return_fields = 'name organizer_id no_pages publication_date price';
> $check_fields = 'name description';
>
>
> $query_text = $_GET['keyword'];
>
> $clean_query_text =cleanQuery($query_text);
>
> $newquery=bq_simple ($return_fields, $tables, $check_fields,
$clean_query_text);
> $newquery = $newquery . " ORDER BY $order;";
>
> $result = mysql_query($newquery) or die(mysql_error());
>
>
> $numrows = mysql_num_rows($result);
> if ($numrows == 0) {
> echo "<H4>No data to display!</H4>";
> exit;
> }
> echo "<p>Your search '$query_text' returned ".$numrows. "
results.</p>\n";
> echo "<p>Click on the headings to sort.</p>\n";
>
> $row = mysql_fetch_assoc ($result);
> echo "<TABLE border=1>\n";
> echo "<TR>\n";
> foreach ($row as $heading=>$column) {
>
>
> echo "<TD><b>";
> if (in_array ($heading, $allowed_order)) {
> echo "<a
href=\"{$_SERVER['PHP_SELF']}?order=$heading&keyword=$query_text\">$heading</a>";
> } else {
> echo $heading;
> }
> echo "</b></TD>\n";
> }
> echo "</TR>\n";
>
mysql_data_seek ($result, 0); while ($row =
> mysql_fetch_assoc ($result)) {
> echo "<TR>\n";
> foreach ($row as $column) {
> echo "<TD><a href='http://mysite.com/(here should be the
ID)'>$column</TD>\n";
> }
> echo "</TR>\n"; } echo "</TABLE>\n"; }
>
> ////////////////////////FINISH OF THE CODE WITH PROBLEM
> ////////////////////////////
>
> /* * * * * * * * * * * * * * F U N C T I O N S * * * * * * * * * * *
> */
>
> function cleanQuery($string)
> {
> $string = trim($string);
> $string = strip_tags($string); // remove any html/javascript.
>
> if(get_magic_quotes_gpc()) // prevents duplicate backslashes
> {
> $string = stripslashes($string);
> }
> if (phpversion() >= '4.3.0')
> {
> $string = mysql_real_escape_string($string);
> }
> else
> {
> $string = mysql_escape_string($string);
> }
> return $string;
> }
>
>
> function bq_handle_shorthand($text) {
> $text = preg_replace("/ \+/", " and ", $text);
> $text = preg_replace("/ -/", " not ", $text);
> return $text; }
>
>
> function bq_explode_respect_quotes($line) {
> $quote_level = 0; #keep track if we are in or out of quote-space
> $buffer = "";
>
> for ($a = 0; $a < strlen($line); $a++) {
> if ($line[$a] == "\"") {
> $quote_level++;
> if ($quote_level == 2) { $quote_level = 0; }
> }
> else {
> if ($line[$a] == " " and $quote_level == 0) {
> $buffer = $buffer . "~~~~"; #Hackish
magic key
> }
> else {
> $buffer = $buffer . $line[$a];
> }
> }
>
> }
>
> $buffer = str_replace("\\", "", $buffer);
>
> $array = explode("~~~~", $buffer);
> return $array; }
>
>
> function bq_make_subquery($fields, $word, $mode) {
>
> if ($mode == "not") {
> $back = " LIKE '%$word%'))";
> }
> else {
> $back = " LIKE '%$word%')";
> }
>
> if ($mode == "not") {
> $front = "(NOT (";
> $glue = " LIKE '%$word%' AND ";
> }
> else {
> $front = "(";
> $glue = " LIKE '%$word%' AND ";
> }
>
> $text = str_replace(" ", $glue, $fields);
> $text = $front . $text . $back;
>
> return $text; }
>
>
>
> function bq_make_query($fields, $text) {
>
> $text = strtolower($text);
>
>
> $text = bq_handle_shorthand($text);
>
>
> $wordarray = bq_explode_respect_quotes($text);
>
> $buffer = "";
> $output = "";
>
> for ($i = 0; $i<count($wordarray); $i++) {
> $word = $wordarray[$i];
>
> if ($word == "and" or $word == "not" and $i > 0) {
> if ($word == "not") {
>
>
> $i++;
> if ($i == 1) { #invalid sql syntax to prefix the first
check with and/or/not
> $buffer = bq_make_subquery($fields, $wordarray[$i],
"not");
> }
> else {
> $buffer = " AND " . bq_make_subquery($fields,
$wordarray[$i], "not");
> }
> }
> else {
> if ($word == "and") {
> $i++;
> if ($i == 1) {
> $buffer = bq_make_subquery($fields,
$wordarray[$i], "");
> }
> else {
>
> $buffer = " AND " . bq_make_subquery($fields,
$wordarray[$i], "");
> }
> }
> else {
> if ($word == "and") {
> $i++;
> if ($i == 1) {
> $buffer = bq_make_subquery($fields,
$wordarray[$i], "");
> }
> else {
>
> $buffer = " AND " .
bq_make_subquery($fields, $wordarray[$i],
"");
> }
> }
> }
> }
> }
> else {
> if ($i == 0) { # 0 instead of 1 here because there was no
conditional word to skip and no $i++;
> $buffer = bq_make_subquery($fields, $wordarray[$i], "");
> }
> else {
> $buffer = " AND " . bq_make_subquery($fields,
$wordarray[$i], "");
> }
> }
> $output = $output . $buffer;
> }
> return $output; }
>
>
>
> function bq_simple ($return_fields, $tables, $check_fields,
> $query_text) {
>
>
> $return_fields = str_replace(" ", ", ", $return_fields);
> $tables = str_replace(" ", ", ", $tables);
>
>
> $query = "SELECT $return_fields FROM $tables WHERE ";
> $query = $query . bq_make_query($check_fields, $query_text);
>
> #
> # Uncomment to debug
> #
>
> return $query; }
>
>
>
> ?>
Subscribe to:
Comments (Atom)