text stringlengths 8 267k | meta dict |
|---|---|
Q: Maven Local Repository using environment variables How can I set up the < localRepository > tag with an environment user var. I tried this path:
%myRepo%/repo but it doesn't works (myRepo=C:/maven/repo). I can't use an absolute path for portability issues but I can setup %myRepo% to the correct place on each system in which the absolute path may vary but the /repo stays the same. Can someone help me? Thanks. Using windows. Maven 2.2.1.
A: You can use ${env.HOME} to refer to the environment variable %HOME%, and similarly any other environment variable.
However, you may want to set the repository location on each machine by specifying it in settings.xml which is allows each user to enter their own settings. See http://maven.apache.org/settings.html for detail on this and setting environment variables in general (note some parts specific to Maven 3 as marked).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: changing the colour of an echo command ive searched this question on google and i've found many answers but none of them seem to work in my situation.
i need to echo out a command in orange, but everything i do doesn't seem to work.
while($row = mysql_fetch_array($result))
{
echo $row ['title_name'];
echo "<br />";
echo $row['date'];
echo "<br />";
echo $row['message'];
echo "<br />";
}
i need the title_name to be in orange "#FF9900"
has any got got any ideas on how i can do this
many thanks Connor
A: ...
echo "<span style=\"color: #FF9900;\">".$row['title_name']."</span>";
...
A: while($row = mysql_fetch_array($result))
{
echo "<span style='color:orange'>".$row ['title_name']."</span>";
echo "<br />";
echo $row['date'];
echo "<br />";
echo $row['message'];
echo "<br />";
}
that all
A: echo '<span style="color: #FF9900">' . $row ['title_name'] . '</span>';
?
A: There's this thing called HTML... and another thing called CSS...
echo '<span style="color: #ff9900">', $row['title_name'], '</span>';
echo '<font color="#ff9900">', $row['title_name'], '</font>';
A: Use some HTML.
echo '<span style="color: #ff9900;">'.$row['title_name'].'</span>';
Actually you should put the CSS seperately, but this works as an example :X
A: echo "<font style='color:#FF9900'>".$row ['title_name']."</font>"; should work as it looks like you are developing a web app.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do i alter the name of a default home page in the breadcrumb in sharepoint 2010? I'm customizing a team site in SharePoint 2010 and have been tweaking the breadcrumb to include a link back to the root. Now it says "Home > Home" for the main site and all subsites. How do i rename the home page so that it isn't called "Home" in the breadcrumb?
I tried creating a new page and naming it the way i wanted, and it worked until i set it to the home page. SharePoint overrides your title name with home EVERY time. Anybody know a way around this so that i can turn this automatic renaming off? I'm open to hacks.
A: If jQuery is an option for you then use it. You will need to construct the selector to get to the Home node and replace it with whatever text you need. For example,
Let's assume you have the following HTML for the breadcrumb:
<ul class="breadCrumb">
<li class="breadCrumbNode"><a title="Home" href="">Home</a></li>
<li class="breadCrumbNode"><span class="breadCrumbArrow"> > </span></li>
<li class="breadCrumbNode"><a title="Page1" href="">Page1</a></li>
<li class="breadCrumbNode"><span class="breadCrumbArrow"> > </span></li>
<li class="breadCrumbNode"><span class="breadCrumbCurrentNode">This Page</span></li>
</ul>
Your JavaScript would be:
$(document).ready(function (){
$('.breadCrumbNode>a[title=Home]').text('New Title for Home Page');
});
See the example here (jsfiddle.net)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: ILGenerator. Whats wrong with this Code I am trying to build a dynamic Property Accessor. Want something which is like really fast as close to calling the actually Property. Dont want to go the Reflection route as its very slow. So i opted to using DynamicAssembly and inject IL using ILGenerator. Below is the ILGenerator related code which seems to work
Label nulllabel = getIL.DefineLabel();
Label returnlabel = getIL.DefineLabel();
//_type = targetGetMethod.ReturnType;
if (methods.Count > 0)
{
getIL.DeclareLocal(typeof(object));
getIL.DeclareLocal(typeof(bool));
getIL.Emit(OpCodes.Ldarg_1); //Load the first argument
//(target object)
//Cast to the source type
getIL.Emit(OpCodes.Castclass, this.mTargetType);
//Get the property value
foreach (var methodInfo in methods)
{
getIL.EmitCall(OpCodes.Call, methodInfo, null);
if (methodInfo.ReturnType.IsValueType)
{
getIL.Emit(OpCodes.Box, methodInfo.ReturnType);
//Box if necessary
}
}
getIL.Emit(OpCodes.Stloc_0); //Store it
getIL.Emit(OpCodes.Br_S,returnlabel);
getIL.MarkLabel(nulllabel);
getIL.Emit(OpCodes.Ldnull);
getIL.Emit(OpCodes.Stloc_0);
getIL.MarkLabel(returnlabel);
getIL.Emit(OpCodes.Ldloc_0);
}
else
{
getIL.ThrowException(typeof(MissingMethodException));
}
getIL.Emit(OpCodes.Ret);
So above get the first argument which is the object that contains the property. the methods collection contains the nested property if any. for each property i use EmitCall which puts the the value on the stack and then i try to box it. This works like a charm.
The only issue is if you have a property like Order.Instrument.Symbol.Name and assume that Instrument object is null. Then the code will throw an null object exception.
So this what i did, i introduced a null check
foreach (var methodInfo in methods)
{
getIL.EmitCall(OpCodes.Call, methodInfo, null);
getIL.Emit(OpCodes.Stloc_0);
getIL.Emit(OpCodes.Ldloc_0);
getIL.Emit(OpCodes.Ldnull);
getIL.Emit(OpCodes.Ceq);
getIL.Emit(OpCodes.Stloc_1);
getIL.Emit(OpCodes.Ldloc_1);
getIL.Emit(OpCodes.Brtrue_S, nulllabel);
getIL.Emit(OpCodes.Ldloc_0);
if (methodInfo.ReturnType.IsValueType)
{
getIL.Emit(OpCodes.Box, methodInfo.ReturnType);
//Box if necessary
}
}
Now this code breaks saying That the object/memory is corrupted etc. So what exactly is wrong with this code. Am i missing something here.
Thanks in Advance.
A: Previously, if you had consecutive properties P returning string and then Q returning int, you would get something like this:
...
call P // returns string
call Q // requires a string on the stack, returns an int
box
...
Now you have something like this:
...
call P // returns string
store // stores to object
... // load, compare to null, etc.
load // loads an *object*
call Q // requires a *string* on the stack
store // stores to object *without boxing*
...
So I see two clear problems:
*
*You are calling methods in such a way that the target is only known to be an object, not a specific type which has that method.
*You are not boxing value types before storing them to a local of type object.
These can be solved by reworking your logic slightly. There are also a few other minor details you could clean up:
*
*Rather than ceq followed by brtrue, just use beq.
*There's no point in doing Stloc_1 followed by Ldloc_1 rather than just using the value on the stack since that local isn't used anywhere else.
Incorporating these changes, here's what I'd do:
Type finalType = null;
foreach (var methodInfo in methods)
{
finalType = methodInfo.ReturnType;
getIL.EmitCall(OpCodes.Call, methodInfo, null);
if (!finalType.IsValueType)
{
getIL.Emit(OpCodes.Dup);
getIL.Emit(OpCodes.Ldnull);
getIL.Emit(OpCodes.Beq_S, nulllabel);
}
}
if (finalType.IsValueType)
{
getIL.Emit(OpCodes.Box, methodInfo.ReturnType);
//Box if necessary
}
getIL.Emit(OpCodes.Br_S, returnLabel);
getIL.MarkLabel(nulllabel);
getIL.Emit(OpCodes.Pop);
getIL.Emit(OpCodes.Ldnull);
getIL.MarkLabel(returnlabel);
Note that we can get rid of both locals since we now just duplicate the top value on the stack before comparing against null.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: click listener for button inside list view in android In my android app I have a list and in each row I have a button. On pressing the button, another activity should open. I am a little confused how to do the click listener. Can anyone kindly suggest ? Thanks.
note: i can create a click listened inside the array adapter. However, I am unable to start a new activity from there :(
A: Put a button in your custom view and handle click event in getView method.
Your code should look something like this.
public View getView(final int position, View convertView,ViewGroup parent)
{
if(convertView == null)
{
LayoutInflater inflater = getLayoutInflater();
convertView = (LinearLayout)inflater.inflate(R.layout.YOUR_LAYOUT, null);
}
Button yourButton= (Button) convertView .findViewById(R.id.YOUR_BUTTON_ID);
yourButton.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
// Your code that you want to execute on this button click
Intent myIntent = new Intent(CurrentActivity.this, NextActivity.class);
CurrentActivity.this.startActivity(myIntent);
}
});
return convertView ;
}
Hope this helps.
A: where ever you are inflating the row view, get the reference to the button in the listItem, and add clickListener to it. You set the listener by
button.setOnClickListener()
and in the listener click call new activity.
declare a field your activity class like this-
private Context mCurrentContext = this;
and when you call the new Activity,
mCurrentContext.startActivity(Intent, int);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Qt 4.7+Xlib crash on QWidget::winId() method Sorry for my english, but I have the next problem. I am writing a window manager using Qt 4.7 and Xlib. I have class Manager that inherits QApplication and reimplemented method X11EventFilter in it. In X11EventFilter method I catch necessary events from XServer. When I receive MapRequest event, I catch appearing of new window and reparent it to my own widget. And when I create that widget and call QWidget::show() or QWidget::winId() methods, program crashes. What is the problem?
Here is a method where widget is creating. I wonder, when this function calls few times on start of program, everything is OK.
void Manager::createClientWindow(Qt::HANDLE pWinID)
{
QMWindowWidget *lWindowWidget = new QMWindowWidget(pWinID);
/*some code*/
lWindowWidget->show();//crash is here
Qt::HANDLE widgetId = lWindowWidget->winId();//and here
/*some code*/
}
Here is a x11EventFilter method where createClientWindow function is called
bool Manager::x11EventFilter(XEvent *pEvent)
{
switch(pEvent.type)
{
/*some code*/
case MapRequest:
{
Qt::HANDLE lWindow = pEvent->xmaprequest.window;
QMWindowWidget* lWidget = findWidget(lWindow);
if (!lWidget)
{
lWidget = dynamic_cast<QMWindowWidget*>(QWidget::find(lWindow));
}
if (lWidget)
{
XMapWindow(QX11Info::display(), lWindow);
lWidget->show();
XRaiseWindow(QX11Info::display(), lWidget->winId());
return true;
}
else
{
createClientWindow(lWindow);//here is where function is called
return true;
}
}
break;
/*some code*/
} //switch
return false;
}
A: The problem most likely resides in the code represented by /*some code*/. Since it is not known what's there, it's very difficult to pinpoint the exact cause of the problem. If you cannot show all the code, you will have to track the problem down yourself.
You will need to build in debug mode and link with the debug version of Qt. Then when the crash happens, look at the exact line of Qt source and analyse the broken data structures with a debugger and try to figure out why they are broken. Maybe set a watchpoint on a problematic variable and find out what code writes an invalid value there.
In order to program in low level languages such as C and C++ one has to learn how to do this stuff.
A: Problem is resolved! I paste this two strings before QApplication::exec()
XClearWindow(QX11Info::display(), QX11Info::appRootWindow());
XSync(QX11Info::display(), false);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MongoDB Query for records with non-existant field & indexing We have a mongo database with around 1M documents, and we want to poll this database using a processed field to find documents which we havent seen before. To do this we are setting a new field called _processed.
To query for documents which need to be processed, we query for documents which do not have this processed field:
db.stocktwits.find({ "_processed" : { "$exists" : false } })
However, this query takes around 30 seconds to complete each time, which is rather slow. There is an index (asc) which sits on the _processed field:
db.stocktwits.ensureIndex({ "_processed" : -1 },{ "name" : "idx_processed" });
Adding this index does not change query performance. There are a few other indexes sitting on the collection (namely the ID idx & a unique index of a couple of fields in each document).
The _processed field is a long, perhaps this should be changed to a bool to make things quicker?
We have tried using a $where query (i.e. $where : this._processed==null) to do the same thing as $exists : false and the performance is about the same (few secs slower which makes sense)...
Any ideas on what would be casusing the slow performance (or is it normal)? Does anyone have any suggestions on how to improve the query speed?
Cheers!
A: Upgrading to 2.0 is going to do this for you:
From MongoDB.org:
Before v2.0, $exists is not able to use an index. Indexes on other fields are still used.
A: Its slow because checking for _processed -> not exists doesnt offer much selectivity. Its like having an index on "Gender" - and since there are only two possible options male or female then if you have 1M rows and an index on Gender it will have to scan 50% or 500K rows to find all males.
You need to make your index more selective.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502875",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: SQL Permission Problem I have having an issue with a SQL execution where I am getting an error message
-2147217843 Login Failed for user.
I am able to successfully open the connection to the database and execute select count(*) queries.
I am getting this error when I include fields.
In a separate application that uses the same fields I am able to retrieve the same data so seems to rule out column permissions.
The query coming back with no error is:-
SELECT tbl_PersonalDetails.SystemID
FROM tbl_PersonalDetails
WHERE tbl_PersonalDetails.Title IS NOT NULL
And tbl_PersonalDetails.HospitalNumber IS NOT NULL
AND tbl_PersonalDetails.SiteID = 1
The query coming back with the error is:-
SELECT DISTINCT tbl_PersonalDetails.Title,tbl_PersonalDetails.HospitalNumber
FROM tbl_PersonalDetails
WHERE tbl_PersonalDetails.SiteID = 1
ORDER BY tbl_PersonalDetails.Title,tbl_PersonalDetails.HospitalNumber ASC
This is not specific to these particular queries, in the first query where we are just doing a count I always get a count back with no issue, when I try to request fields such as in the second I always get the Login Error.
A: Your problem isn't in the SQL queries you've posted. They would either all fail or all succeed based on the information given.
Your problem is your calling/client code. Sounds like you're using Classic ASP ("recordset....adodb connection").
Double check that your ASP code is using the proper connection strings.
To prove this, run any of these queries in SQL Server Management Studio. Connect using the credentials that your connection string contains.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502876",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Joining Query from Two Tables [Using SQL Server 2000]
I can't believe a simple task is being this complex to write in SQL.
Perhaps I'm missing something.
Here's the query that will not run because the column names are ambiguous:
SELECT serial_Number, system_id, date_time
FROM acp_parts ap
INNER JOIN join test_results tr ON (ap.serial_Number=tr.serial_Number)
WHERE serial_Number IN (
'C037687 1000 11', 'C037687 1001 11', 'C037687 1002 11', 'C037687 1003 11',
'C037687 1004 11', 'C037687 1005 11', 'C037687 1006 11', 'C037687 1007 11',
'C037687 1008 11', 'C037687 1009 11', 'C037687 1010 11', 'C037687 1011 11',
'C037687 1012 11', 'C037687 1013 11', 'C037687 1014 11', 'C037687 1015 11',
'C037687 1016 11', 'C037687 1017 11', 'C037687 1018 11', 'C037687 1019 11',
'C037687 1020 11', 'C037687 1021 11', 'C037687 1022 11', 'C037687 1023 11',
'C037687 1024 11')
ORDER BY serial_Number, date_time
I'd just like a simple table with these serial numbers in one column, what table they are in (system_id), and when they were logged (date_time).
I do NOT want a separate column for each table - that would defeat the purpose of my query.
This is probably something simple that I'm missing.
[EDIT]: Sorry! I should have added that serial numbers in one table may or may not be in one of the other tables, so I do not want to display ap.serial_Number, etc.
[Solution]: Here's what I went with that solved my problem:
SELECT serial_Number, system_id, date_time FROM (
select serial_Number, system_id, date_time
from acp_parts ap
UNION ALL
select serial_Number, system_id, date_time
from test_results tr
) T
where serial_Number in (
'C037687 1000 11', 'C037687 1001 11', 'C037687 1002 11', 'C037687 1003 11', 'C037687 1004 11', 'C037687 1005 11',
'C037687 1006 11', 'C037687 1007 11', 'C037687 1008 11', 'C037687 1009 11', 'C037687 1010 11', 'C037687 1011 11',
'C037687 1012 11', 'C037687 1013 11', 'C037687 1014 11', 'C037687 1015 11', 'C037687 1016 11', 'C037687 1017 11',
'C037687 1018 11', 'C037687 1019 11', 'C037687 1020 11', 'C037687 1021 11', 'C037687 1022 11', 'C037687 1023 11',
'C037687 1024 11')
order by serial_Number, date_time
A: You are joining on the column serial_Number, but your order by statement isn't specifying which table to use for the order by statement. Anytime tables share column names you need specify which table you're referring to.
A: When in doubt, I always put table name before each field name like 'acp_parts.serial_Number' instead of 'serial_Number' etc, that usually resolves ambiguity.
A: You surely have the same column names on both tables. You need to alias the tables and specify which column from which table are you trying to select. Example:
select ap.serial_Number, tr.system_id, ap.date_time
from acp_parts ap inner join test_results tr on (ap.serial_Number=tr.serial_Number)
where serial_Number in (
'C037687 1000 11', 'C037687 1001 11', 'C037687 1002 11', 'C037687 1003 11', 'C037687 1004 11', 'C037687 1005 11',
'C037687 1006 11', 'C037687 1007 11', 'C037687 1008 11', 'C037687 1009 11', 'C037687 1010 11', 'C037687 1011 11',
'C037687 1012 11', 'C037687 1013 11', 'C037687 1014 11', 'C037687 1015 11', 'C037687 1016 11', 'C037687 1017 11',
'C037687 1018 11', 'C037687 1019 11', 'C037687 1020 11', 'C037687 1021 11', 'C037687 1022 11', 'C037687 1023 11',
'C037687 1024 11')
order by ap.serial_Number, tr.date_time
A: I guess you should be using ap.serial_Number in both the select statement and the order by clause.
Hope this Helps!!
A: You're not using the table aliases in the SELECT other than the JOIN. Assuming I have the tables correct:
select
ap.serial_Number
,tr.system_id
,tr.date_time
from acp_parts AS ap
inner join test_results AS tr on ap.serial_Number=tr.serial_Number
where ap.serial_Number in (
'C037687 1000 11', 'C037687 1001 11', 'C037687 1002 11', 'C037687 1003 11', 'C037687 1004 11', 'C037687 1005 11',
'C037687 1006 11', 'C037687 1007 11', 'C037687 1008 11', 'C037687 1009 11', 'C037687 1010 11', 'C037687 1011 11',
'C037687 1012 11', 'C037687 1013 11', 'C037687 1014 11', 'C037687 1015 11', 'C037687 1016 11', 'C037687 1017 11',
'C037687 1018 11', 'C037687 1019 11', 'C037687 1020 11', 'C037687 1021 11', 'C037687 1022 11', 'C037687 1023 11',
'C037687 1024 11')
order by
ap.serial_Number
,tr.date_time
A: So, the number will only exist in one table or the other? I think you want a UNION ALL. The following is not syntax checked, but should get you started:
SELECT * FROM
(
select
serial_Number,
system_id,
date_time
from
acp_parts ap
UNION ALL
select
serial_Number,
system_id,
date_time
from
acp_parts test_results tr
)
ORDER BY serial_Number, date_time
A: Yes, you are missing something simple: serial_Number is in both tables, so it always has to be qualified, even though the result won't necessarily matter:
SELECT ap.serial_Number, system_id, date_time
FROM acp_parts ap
INNER JOIN join test_results tr ON (ap.serial_Number = tr.serial_Number)
WHERE ap.serial_Number IN (
'C037687 1000 11', 'C037687 1001 11', 'C037687 1002 11', 'C037687 1003 11',
'C037687 1004 11', 'C037687 1005 11', 'C037687 1006 11', 'C037687 1007 11',
'C037687 1008 11', 'C037687 1009 11', 'C037687 1010 11', 'C037687 1011 11',
'C037687 1012 11', 'C037687 1013 11', 'C037687 1014 11', 'C037687 1015 11',
'C037687 1016 11', 'C037687 1017 11', 'C037687 1018 11', 'C037687 1019 11',
'C037687 1020 11', 'C037687 1021 11', 'C037687 1022 11', 'C037687 1023 11',
'C037687 1024 11')
ORDER BY ap.serial_Number, date_time
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502881",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: C# Datetimepicker -Date search is not same as return result I have a problem with my stand alone C#.net application when comes to datetimepicker.
It tooks me weeks and not able to get it solve. I hope you can give me a hand.
I have a [create booking], [Search Booking], and [DB] using ms access.
1) Create booking date using the datetimepicker.
format= short
cmd.CommandText = "insert into booking(cname, bdate, btime, ccontact, sname) Values('" + txt_cname.Text + "','" + **dtp_bdate.Value.Date** + "','" + dtp_btime.Value + "','" + txt_ccontact.Text + "','" + txt_sname.Text + "')";
2) Data store in DB is correct.
Example: 01/10/2011 (it is 1st of October 2011)
3) Search Booking date using the datetimepicker.
format= short
string strSql = String.Format("SELECT * FROM booking WHERE bdate = #{0}#", dtp_search.Value.Date);
When I try to search as in 01/10/2011. It doesn't return the result for me.
But when I try to search as in 10/1/2011, it then appeared the result.
I checked on the DB and confirm the date format is saved as 01/10/2011.
But I don't understand why and how this weird thing happen.
Can any kind man give me a hand?
Truly appreciated in advance.
Thank you,
Gary Yee
A: Looks like Access allows fixed format dates in sql queries (MM/DD/YYYY). And the date is displayed formatted according to the current culture of the database browser (so you get DD/MM/YYYY). Just use (MM/DD/YYYY) in queries.
A: "IF" your data is correct, try using parameters instead:
DataTable dt = new DataTable();
using (var cn = new OleDbConnection(strConn))
{
cn.Open();
using (var cmd = new OleDbCommand("SELECT * FROM booking WHERE bdate = @bdate", cn))
{
cmd.Parameters.AddWithValue("@bdate", dtp_bdate.Value.Date);
using (OleDbDataAdapter oda = new OleDbDataAdapter(cmd))
oda.Fill(dt);
}
}
Otherwise, try debugging your statement by trying >= or <= for your "WHERE bdate = @bdate" statement to see if that changes the results.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Getting java.io.NotSerializableException with a spring service when stopping tomcat i am using spring 3 with JSF 2
and i replaced JSF managed beans with spring beans, by adding on top of bean:
@Component("mybean")
@Scope("session")
and in my bean i am autowiring a spring service (which was declared with the annotation @service)
well, everything works fine with the service, but when i tried to stop tomcat 6, i am getting this exception with my spring service
java.io.NotSerializableException
any ideas why i am getting this exception, and how to solve it.
UPDATE:
after making my service implements serializable, sometimes i am getting following exception:
java.lang.IllegalStateException: Cannot deserialize BeanFactory with id org.springframework.web.context.WebApplicationContext:/spring_faces: no factory registered for this id
at org.springframework.beans.factory.support.DefaultListableBeanFactory$SerializedBeanFactoryReference.readResolve(DefaultListableBeanFactory.java:972)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at java.io.ObjectStreamClass.invokeReadResolve(ObjectStreamClass.java:1061)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1762)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947)
at java.io.ObjectInputStream.defaultReadObject(ObjectInputStream.java:480)
at org.springframework.aop.support.AbstractBeanFactoryPointcutAdvisor.readObject(AbstractBeanFactoryPointcutAdvisor.java:98)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:974)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1849)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.readArray(ObjectInputStream.java:1667)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1323)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947)
at java.io.ObjectInputStream.defaultReadObject(ObjectInputStream.java:480)
at org.springframework.aop.framework.AdvisedSupport.readObject(AdvisedSupport.java:550)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at java.io.ObjectStreamClass.invokeReadObject(ObjectStreamClass.java:974)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1849)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1871)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1871)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1871)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1871)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1871)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:1947)
at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1871)
at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1753)
at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1329)
at java.io.ObjectInputStream.readObject(ObjectInputStream.java:351)
at org.apache.catalina.session.StandardSession.readObject(StandardSession.java:1496)
at org.apache.catalina.session.StandardSession.readObjectData(StandardSession.java:998)
at org.apache.catalina.session.StandardManager.doLoad(StandardManager.java:394)
at org.apache.catalina.session.StandardManager.load(StandardManager.java:321)
at org.apache.catalina.session.StandardManager.start(StandardManager.java:648)
at org.apache.catalina.core.ContainerBase.setManager(ContainerBase.java:446)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4631)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
at org.apache.catalina.core.StandardService.start(StandardService.java:525)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
please advise.
A: Looking at the error, It looks like tomcat is trying to serialize the entire spring context, I think it might be due to the fact that your are implementing Serializable on Service. I was thinking may be you need to do this, I don't know JSF that well but my understanding of scoped beans makes me think, You might need some thing like this
@Component
@Scope(proxyMode=ScopedProxyMode.TARGET_CLASS, value="session")
public class MyBean implements Serializable
{
//no need to implement serializable on service
@Autowired(required=true)
private MyService service;
}
A: You get this exception because the class does not implement Serializable. Tomcat serializes currently running HttpSession objects including all its attributes to disk whenever it is about to restart/redeploy, so that they are revived after the cycle. Session scoped objects are stored as attributes of the HttpSession, hence they need to implement Serializable to survive the restart/redeploy as well.
If you would like to make them Serializable, then implement it accordingly:
public class YourSpringService implements Serializable {}
Otherwise, just ignore the exception or turn off serializing sessions to disk in Tomcat's config.
Note that the same story also applies to JSF view/session scoped beans.
A: Well, finally i was able to make it work fine as follows:
1- The Service:
@Service
@Scope("singleton")
public class PersonService{
}
2- The Spring Managed Bean:
@Component("person")
@Scope("session")
public class PersonBean implements Serializable{
@Inject
private PersonService personService;
}
waiting for your feedback.
A: I had to use readObject() + static ApplicationContext hack to solve the issue:
@Component
@Scope(value = SCOPE_SESSION, proxyMode = ScopedProxyMode.TARGET_CLASS)
public class FlashMessages implements Serializable {
@Autowired
transient private SomeBean someBean;
private void readObject(ObjectInputStream ois) throws ClassNotFoundException, IOException {
ois.defaultReadObject();
// restore someBean field on deserialization
SpringUtils.getContext().getAutowireCapableBeanFactory().autowireBean(this);
}
}
@Component
public class SpringUtils implements ApplicationContextAware {
static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringUtils.applicationContext = applicationContext;
}
public static ApplicationContext getContext() {
return applicationContext;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502891",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Java shallow and deep copying JLS
Possible Duplicate:
Java pass by reference issue
In my codes below, methodA will be called, which then delegates a call to methodB, in doing so, methodB assigns the input parameter with String literal "bbb", however, back at methodA, the string literal was not there, which section of the JLS defines this behavior?
package sg.java.test2;
public class TestApple {
public static void main(String args[]){
methodA();
}
public static void methodA(){
String a = null;
methodB(a);
System.out.println(a);
}
public static void methodB(String a){
a = new String("bbb");
}
}
A: this is a pass by value vs pass by reference issue. Java is pass by value ONLY. When you call
methodB(a)
the reference a gets copied; in the context of methodB, a is a different variable that has the same value as in methodA. So when you change it in methodB, a in methodA still points to the original String.
Another issue that comes into play here is that Strings are immutable, so you can't change the value of a String once it is set. From the docs.
Strings are constant; their values cannot be changed after they are
created.
What you could do is
a = methodB();
and return "bbb" in methodB. There is no reason to pass a in because you are not operating on it; I think you were only doing it to try to change a in the context that calls methodB, which you cannot do.
Finally, the relevant part of the JLS is 8.4.1, which says
When the method or constructor is invoked (§15.12), the values of the
actual argument expressions initialize newly created parameter
variables, each of the declared Type, before execution of the body of
the method or constructor. The Identifier that appears in the
DeclaratorId may be used as a simple name in the body of the method or
constructor to refer to the formal parameter.
A: Java is pass by value, not pass by reference.
The method signature is shorthand for this:
methodB() {
String a = arguments[0];
i.e. it is a difference reference. When you assign to 'a', you are assigning to the reference 'a' created as part of the method signature, not to the 'a' you declared in the code block that contained the call to methodB().
You can modify the value if it is an object, however.
class MyObj {
String prop;
public MyObj(String s) { prop = s; }
public MyObj() { }
}
public void methodB(MyObj o) {
o.prop = "foo";
}
public void methodA() {
MyObj a = new MyObj();
System.out.println(a.prop); // null
methodB(a);
System.out.println(a.prop); // foo
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: WMIC MangementClass RemoteCommand - determining when it is finished? STDOUT? I'm executing a remote CMD line command via WMIC that takes a few seconds to run. I'm currently doing Thread.Sleep(4000) before moving on...there MUST be a better way! Is there a variable or method I can use to determine if the command I issued finished / a status byte?
Thanks!
Im using the following code to issue the commands:
ManagementClass processTask = new ManagementClass(@"\\" + this.wmiConnection.machineName + @"\root\CIMV2", "Win32_Process", null);
ManagementBaseObject methodParams = processTask.GetMethodParameters("Create");
methodParams["CommandLine"] = command;
methodParams["CurrentDirectory"] = @"C:\";
Just need to figure out how to determine when the command finishes :). Thanks!
A: In my understanding, when you write this :
ManagementClass processTask = new ManagementClass(@"\\192.168.183.100\root\CIMV2", "Win32_Process", null);
ManagementBaseObject methodParams = processTask.GetMethodParameters("Create");
methodParams["CommandLine"] = "cmd.exe";
methodParams["CurrentDirectory"] = @"C:\";
//Execute the method
ManagementBaseObject outParams = processTask.InvokeMethod("Create", methodParams, null);
You are launching the remote process in a synchronous way, so
outParams["returnvalue"]
outParams["processid"]
Will give the return code and processId as explain in How To: Execute a Method, if you want to run it asynchronously you can read this : How To: Call a Method Asynchronously.
A: There is a similar question posted here: Wait for service.InvokeMethod to finish - WMI, C#
The following documentation How To: Execute a Method and How To: Call a Method Asynchronously describe semi-synchronous and asynchronous execution. What you are doing is semi-synchronous execution.
As far as I can tell, this provides feedback on where WMI executed the command successfully. If it is a long running command such as running an installer, stopping a service, or executing a batch file, WMI will return when the installer launches, the service was told to start stopping or the batch file process is started.
To really wait for the new process to exit, as far as I can tell, you will need to poll to see if the process is running, or query if the service is stopped. In your case, depending on the command, poll the process id.
I am still looking into this myself as well.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How do I capture JavaScript errors generated in a page fetched by PhantomJS? I have a PhantomJS script that loads a local HTML file, injects some javascript files, then executes some javascript in the context of the page. The javascript that runs generates an exception, but I only get output from the console, which doesn't seem to distinguish between an error and a normal log and doesn't have file, line numbers or a stacktrace.
What I need is a way to capture or otherwise distinguish these errors. I have already tried:
*
*Wrapping my PhantomJS script in a try-catch
*
*Result: nothing is thrown far enough to be caught by this
*Define a window.onerror function
*
*Result: nothing happens. WebKit does not implement an onerror event on the window
I would prefer to be able to retrieve the error object itself so that I can retrieve the stacktrace.
A: I think there were issues with window.onerror not properly working in WebKit (https://bugs.webkit.org/show_bug.cgi?id=8519). Don't know if this has been fixed at all, and if so, if the QT WebKit version is already up-to-date.
However, you should be able to catch the exceptions thrown in your code. If you are using something like webPage.evaluate(...)to run your code, you cannot wrap the complete call in a try/catch block, since the script is evaluated in a different context and the errors will not appear in the main execution context. Insteadyou will need to catch the errors in page execution context. Unfortunately, there is no way of accessing any functions defined in the main context, we therefore have to explicitly write the wrapping code around your code to be executed.
The following is a modified example of the phantomwebintro.js file as included in the PhantomJS source. It loads an HTML page, inserts a script and then runs some code in the page context (here with a line throwing a type error). This code is wrapped with a try/catch block and will return the wrapped result or error object to the main context.
...
// Load an HTML page:
page.open("http://www.phantomjs.org", function(status) {
if (status == "success") {
// Inject some scripts:
page.includeJs("http://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js", function() {
// Run your own code in the loaded page context:
var resultWrapper = page.evaluate(function() {
var wrapper = {};
try {
// Your code goes here
// ...
var x = undefined.x; // force an error
// store your return values in the wrapper
wrapper.result = 42;
} catch(error) {
wrapper.error = error;
}
return wrapper;
});
// Handle the result and possible errors:
if (resultWrapper.error) {
var error = resultWrapper.error;
console.log("An error occurred: " + error.message);
// continue handling the error
// ...
} else {
var result = resultWrapper.result;
// continue using the returned result
// ...
}
...
});
}
});
...
A: The solution? return true!
// Error tracking
page.onError = function(msg, trace) {
console.log('= onError()');
var msgStack = [' ERROR: ' + msg];
if (trace) {
msgStack.push(' TRACE:');
trace.forEach(function(t) {
msgStack.push(' -> ' + t.file + ': ' + t.line + (t.function ? ' (in function "' + t.function + '")' : ''));
});
}
console.log(msgStack.join('\n'));
// Consider error fully handled
return true;
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502899",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
} |
Q: Is there a way to make NAnt catch exceptions and run a roll back script? I am using NAnt to run some scrips for a deployment. It has simplified the process a lot. The issue now is that when there is an error I want the NAnt task to run my roll back scripts. However I only know of the option to fail on error for my tasks. Is there any sort of baked in way to set properties on error or to use the the chose statement to redirect the flow of the tasks if a previous task fails?
A: I found the answer looking for another question about NAnt (error handling in nant build scripts). This will fill the need I have to automatically kick off roll back scripts. Only thing catch is that is not a part of base NAnt but NAntContrib, but that a minor detail.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What can cause IllegalMonitorStateException from inside a synchronized block? We hit an extremely surprising exception today. Inside of a synchronized block, we call wait() and it throws IllegalMonitorStateException. What can cause this?
This is happening in well-tested open source code:
http://svn.apache.org/viewvc/river/jtsk/trunk/src/com/sun/jini/jeri/internal/mux/Mux.java?view=markup#l222
We eliminated the obvious causes:
*
*are we synchronized on the right variable? Yes, it's muxLock
*is it a mutable variable? No, muxLock is final
*are we using any weird "-XX:" JVM flags that might affect monitor behavior? No, but we are launching the JVM embedded inside a C++ app via JNI.
*is this a strange JVM? No, it's Sun's 1.6.0_25 win/x64 JRE
*is this a known JVM bug? Can't find anything relevant at http://bugs.sun.com/bugdatabase
So, I'm trying to think of more far-fetched explanations.
*
*could an uncaught out-of-memory error cause the monitor state to be screwed up? We're looking at this, but we're seeing no evidence of memory errors yet.
UPDATE: (based on comment)
I've also verified from the stacktrace and breakpoint that the thread is indeed inside the synchronized block when the exception is thrown. It's not the case that some other unrelated code is emitting the exception (unless something is REALLY confusing Eclipse!)
A: The only suspicious thing I see that you are passing a reference to 'this' to some other object in your constructor. Is it possible (in fact, not unlikely) that, through weird re-ordering of things, if some other thread gets that reference to 'this' and calls the method that uses the muxlock, things can go extremely wrong.
The Java Language Specification is pretty specific about this:
An object is considered to be completely initialized when its constructor finishes. A thread that can only see a reference to an object after that object has been completely initialized is guaranteed to see the correctly initialized values for that object's final fields.
In other words, if another thread gets hold of the 'this' reference before the constructor is finished, the final field 'muxlock' might not be correctly initialized yet. In general, publishing a reference to 'this' before the constructor has finished can be pretty dangerous, especially in threaded situations.
Some potentially useful discussion about such things:
http://madpropellerhead.com/random/20100328-java-final-fields-are-not-as-final-as-you-may-think
For some older, but still useful general discussion of why publishing 'this' in a constructor is a very bad idea in general, see for instance:
http://www.ibm.com/developerworks/java/library/j-jtp0618/index.html
A: http://svn.apache.org/viewvc/river/jtsk/trunk/src/com/sun/jini/jeri/internal/mux/Mux.java?r1=1069292&r2=1135026&diff_format=h
here i can see that timeout was added lately
make sure that startTimeout is > than 0 otherwise you will wait(0) or wait(-n) this probably cause IllegalMonitorStateException
EDIT: Ok above is a disaster But lets try this :
we are in Mux constructor : http://svn.apache.org/viewvc/river/jtsk/trunk/src/com/sun/jini/jeri/internal/mux/Mux.java?view=markup
line 176 we create SocketChannelConnectionIO andd pass this after that we break and and different thread takes over .
in constructor of SocketChannelConnectionIO defined here : http://svn.apache.org/viewvc/river/jtsk/trunk/src/com/sun/jini/jeri/internal/mux/SocketChannelConnectionIO.java?view=markup
line 112 we register to channel with the new handler().
handler recieaves something on chanel and function let say function handleReadReady is executed we synchronize on muxLock .
now we are still in constructor so object in final is still mutable !!!
let assume it changes , now we have something waiting on different muxLock
One in a million scenario
EDIT
http://svn.apache.org/viewvc/river/jtsk/trunk/src/com/sun/jini/jeri/internal/mux/Mux.java?revision=1135026&view=co
Mux(SocketChannel channel,
int role, int initialInboundRation, int maxFragmentSize)
throws IOException
{
this.role = role;
if ((initialInboundRation & ~0x00FFFF00) != 0) {
throw new IllegalArgumentException(
"illegal initial inbound ration: " +
toHexString(initialInboundRation));
}
this.initialInboundRation = initialInboundRation;
this.maxFragmentSize = maxFragmentSize;
//LINE BELOW IS CAUSING PROBLEM it passes this to SocketChannelConnectionIO
this.connectionIO = new SocketChannelConnectionIO(this, channel);
//Lets assume it stops here we are still in constructor
//and we are not in synchronized block
directBuffersUseful = true;
}
now in constructor of SocketChannelConnectionIO
http://svn.apache.org/viewvc/river/jtsk/trunk/src/com/sun/jini/jeri/internal/mux/SocketChannelConnectionIO.java?revision=1069292&view=co
SocketChannelConnectionIO(Mux mux, SocketChannel channel)
throws IOException
{
super(mux);
channel.configureBlocking(false);
this.channel = channel;
//Line below we are registering to the channel with mux that is still mutable
//this is the line that actually is causing the problem move that to
// start() and it should work
key = selectionManager.register(channel, new Handler());
}
move this code to start() should work key = selectionManager.register(channel, new Handler()); (i am assuming start is executet when we want to start prosessing)
/**
* Starts processing connection data.
*/
void start() throws IOException {
key = selectionManager.register(channel, new Handler());
key.renewInterestMask(SelectionKey.OP_READ);
}
But it would be much better not to create SocketChannelConnectionIO in the constructor of mux but maybe somewhere after that the same for second constructor creating StreamConnectionIO with this
A: The answer is in my opinion that its either a bug, or someone changed the object behind the reference despite its being final. If you can reproduce it, I recommend to set a read/write breakpoint on muxlock field to see if it is touched or not. You could check the identityhashcode of the muxlock in the first line of the synchronized block, and before waits and notifies with appropiate log entries or breakpoints. With reflection you can change final references. Quote from http://download.oracle.com/javase/6/docs/api/java/lang/reflect/Field.html:
"If the underlying field is final, the method throws an IllegalAccessException unless setAccessible(true) has succeeded for this field and this field is non-static. Setting a final field in this way is meaningful only during deserialization or reconstruction of instances of classes with blank final fields, before they are made available for access by other parts of a program. Use in any other context may have unpredictable effects, including cases in which other parts of a program continue to use the original value of this field."
Maybe its a bug in eclispe, and during debugging it somehow changes the field. Is it reproducable outside eclispe as well? Put a printstractrace in catch and see what happens.
A: Member variables are not as final as one would hope to. You should put the synchronized object into a final local variable, first. This does not explain why the member variable is altered, but if it fixes the problem you at least know that the member variable is really modified.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "30"
} |
Q: clang optimization bug? I've been trying to track down what seems like a bug in clang, and I think I've got a reasonably minimal reproduction of it. Here's my program:
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define x_Is_Digit(x) isdigit((unsigned char) (x))
void Odd_Behavior(char * version)
{
char * ptr, *tmp;
for (ptr = version; x_Is_Digit(*ptr); ptr++);
ptr++;
for (tmp = ptr; x_Is_Digit(*ptr); ptr++);
if (ptr == tmp)
printf("%08x == %08x! Really?\n", ptr, tmp);
}
int main()
{
char buffer[100];
strcpy(buffer, "3.8a");
Odd_Behavior(buffer);
return(0);
}
When I compile it with optimization, in the clang included with the Xcode download ("Apple clang 2.1"):
clang++ -Os optimizebug.cpp
And run it, it reports:
6b6f2be3 == 6b6f2be2! Really?
This strikes me as a tad odd, to say the least. If I remove the (unsigned char) cast in x_Is_Digit, it works properly.
Have I run into a bug in clang? Or am I doing something here that's causing some sort of undefined behavior? If I compile it with -O0, I don't get the problem.
A: Certainly looks like a bug to me. Clang mainline doesn't display this (at least on darwin/x86-64). Please file a bug at llvm.org/bugs with full details on how to reproduce this. Stack overflow isn't a great place to report compiler bugs :)
A: Definitively a bug. If the two pointers are equal at the if statement, they must also be equal in the printf statement.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502908",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to see what my Java process is doing right now? I have an app server process that's constantly at 100% CPU. By constantly I mean hours, or even days.
I know how to generate a heap/thread dump, but I'm looking for more dynamic information. I would like to know what is using so much CPU in there. There are tens (or probably 100+) threads. I know what those threads are, but I need to know which of them are using my CPU so much.
How can I obtain this information?
A: Use a profiler. There is one included in VisualVM which comes with the Oracle JDK.
An advanced commercial one (trial licenses available) is YourKit.
A: By creating a thread dump. You can use the jstack to connect to a running java process to get the thread dump. If you take two or more thread dumps over a period of time you can by analyzing them figure out which ones are actively using CPU. Typically the threads in the RUNNING state are the ones you need to focus on.
A: I personally use YourKit for this.
VisualVM also has some profiling capabilities, but I haven't used them.
A: in linux try kill -3 processid it will generate thread dump. You can analyze this to see what is happening in the java process.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Carrierwave storage path management with a staging instance on Heroku I have two instances of my app in production on Heroku, staging.myapp.com and www.myapp.com, and I am following this workflow: Staging instance on Heroku.
As I am using Carrierwave with AWS S3, I would like to know if it is possible to modify the storage path in order to specify each instance, e.g.:
def store_dir
instance = "staging" | "production"
#{instance}/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}
end
A: I keep my assets in seperate buckets and do it like this;
config.fog_directory = "myappname-#{Rails.env}-assets"
so it will use a bucket name myappname-production-assets or myappname-staging-assets.
in my carrierwave initializer. Make sure you read 'Configuring Carrierwave' on https://github.com/jnicklas/carrierwave and 'Using Amazon S3'
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: builtin password reset view problem in django1.3 Hi am absolutely new to django,Now I am tring for builtin reset password view..
I follow the link link
But I got the error when I click on reset password button at /password_reset/ :
error at /accounts/password_reset/
[Errno 10061] No connection could be made because the target machine actively refused it.
Exception Location: C:\Python27\lib\socket.py in create_connection, line 571
'urls.py'
(r'^accounts/password_reset$','django.contrib.auth.views.password_reset','template_name':'user/password_reset_form.html','email_template_name':'user/password_reset_email.html'}),
(r'^accounts/password/reset/confirm/(?P[0-9A-Za-z]{1,13})-(?P[0-9Aa-z]{1,13}-[0-9A-Za-z]{1,20})/$', 'django.contrib.auth.views.password_reset_confirm', {'template_name' : 'user/password_reset.html', 'post_reset_redirect': '/logout/' }),
(r'^accounts/password_reset/done/$',<b>'django.contrib.auth.views.password_reset_done'</b>,{'template_name':'user/password_reset_done.html'}),
(r'^accounts/change_password/$',<b> 'password_change'</b>, {'post_change_redirect' : '/accounts/change_password/done/'}),
(r'^accounts/change_password/done/$',<b> 'password_change_done'</b>,{'template_name':'user/password_change_done.html'}),
<b>password_reset_email.html</b>
{% extends 'base.html'%}
{% block content%}
{% url django.contrib.auth.views.password_reset_confirm uidb36=uid, token=token %}
{% endblock %}
I add necessary templates in the folder 'user'.Please help me,Thanks in advance.
A: As rdegges said, it's a connection error. Check which port the request is trying to access, and make sure windows firewall is set up to receive on that port. You can check the port by looking through django's traceback page, and looking at the "local vars".
From the looks of it, it's an email port. Take another look at the traceback and look out for django trying to send a request to port 25. If it does, make sure your port 25 is configured to receive.
Also, you'll need a makeshift SMTP server for testing purposes because you probably wouldn't want to be using a real one. Just have this running in a separate command prompt window while you're running django, and any emails that django tries to send through your port 25 will be saved in an "emails" folder in the working directory.
#/usr/bin/env python
from datetime import datetime
import asyncore
from smtpd import SMTPServer
class EmlServer(SMTPServer):
no = 0
def process_message(self, peer, mailfrom, rcpttos, data):
filename = '%s-%d.eml' % (datetime.now().strftime('%Y%m%d%H%M%S'), self.no)
f = open(filename, 'w')
f.write(data)
f.close()
print '%s saved.' % filename
self.no += 1
def run():
foo = EmlServer(('localhost', 25), None)
try:
asyncore.loop()
except KeyboardInterrupt:
pass
if __name__ == '__main__':
from os.path import exists, join
from os import mkdir, chdir, getcwd
target_directory = join( getcwd(), "emails" )
if exists(target_directory):
chdir(target_directory)
else:
try:
mkdir(target_directory)
except OSError:
from sys import exit
exit("The containing folder couldn't be created, check your permissions.")
chdir(target_directory)
print "Using directory %s" % target_directory
run()
A: The error you're getting is a connection error--that means that the server you're using to run your Django site is likely not working correctly. Here are some things you can try on your Django server:
*
*If you're running your Django site via python manage.py runserver, you can try to simply re-run that command.
*If you're running your site via a webserver like apache, try restarting apache.
If neither of those work, post a comment and let me know what operating system you're running your site on, and how you're running it, and we can do further debugging.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502925",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What is atoi equivalent for 64bit integer(uint64_t) in C that works on both Unix and Windows? I'm trying to convert 64bit integer string to integer, but I don't know which one to use.
A: Something like...
#ifdef WINDOWS
#define atoll(S) _atoi64(S)
#endif
..then just use atoll(). You may want to change the #ifdef WINDOWS to something else, just use something that you can rely on to indicate that atoll() is missing but atoi64() is there (at least for the scenarios you're concerned about).
A: Use strtoull if you have it or _strtoui64() with visual studio.
unsigned long long strtoull(const char *restrict str,
char **restrict endptr, int base);
/* I am sure MS had a good reason not to name it "strtoull" or
* "_strtoull" at least.
*/
unsigned __int64 _strtoui64(
const char *nptr,
char **endptr,
int base
);
A: Try strtoull(), or strtoul(). The former is only in C99 and C++11, but it's usually widely available.
A: You've tagged this question c++, so I'm assuming you might be interested in C++ solutions too. You can do this using boost::lexical_cast or std::istringstream if boost isn't available to you:
#include <boost/lexical_cast.hpp>
#include <sstream>
#include <iostream>
#include <cstdint>
#include <string>
int main() {
uint64_t test;
test = boost::lexical_cast<uint64_t>("594348534879");
// or
std::istringstream ss("48543954385");
if (!(ss >> test))
std::cout << "failed" << std::endl;
}
Both styles work on Windows and Linux (and others).
In C++11 there's also functions that operate on std::string, including std::stoull which you can use:
#include <string>
int main() {
const std::string str="594348534879";
unsigned long long v = std::stoull(str);
}
A: In modern c++ I would use std::stoll.
http://en.cppreference.com/w/cpp/string/basic_string/stol
std::stoi, std::stol, std::stoll
C++ Strings library std::basic_string
Defined in header <string>
int stoi( const std::string& str, std::size_t* pos = 0, int base = 10 );
int stoi( const std::wstring& str, std::size_t* pos = 0, int base = 10 );
(1) (since C++11)
long stol( const std::string& str, std::size_t* pos = 0, int base = 10 );
long stol( const std::wstring& str, std::size_t* pos = 0, int base = 10 );
(2) (since C++11)
long long stoll( const std::string& str, std::size_t* pos = 0, int base = 10 );
long long stoll( const std::wstring& str, std::size_t* pos = 0, int base = 10 );
(3) (since C++11)
Interprets a signed integer value in the string str.
1) calls std::strtol(str.c_str(), &ptr, base) or std::wcstol(str.c_str(), &ptr, base)
2) calls std::strtol(str.c_str(), &ptr, base) or std::wcstol(str.c_str(), &ptr, base)
3) calls std::strtoll(str.c_str(), &ptr, base) or std::wcstoll(str.c_str(), &ptr, base)
Discards any whitespace characters (as identified by calling isspace()) until the first non-whitespace character is found, then takes as many characters as possible to form a valid base-n (where n=base) integer number representation and converts them to an integer value. The valid integer value consists of the following parts:
(optional) plus or minus sign
(optional) prefix (0) indicating octal base (applies only when the base is 8 or 0)
(optional) prefix (0x or 0X) indicating hexadecimal base (applies only when the base is 16 or 0)
a sequence of digits
The set of valid values for base is {0,2,3,...,36}. The set of valid digits for base-2 integers is {0,1}, for base-3 integers is {0,1,2}, and so on. For bases larger than 10, valid digits include alphabetic characters, starting from Aa for base-11 integer, to Zz for base-36 integer. The case of the characters is ignored.
Additional numeric formats may be accepted by the currently installed C locale.
If the value of base is 0, the numeric base is auto-detected: if the prefix is 0, the base is octal, if the prefix is 0x or 0X, the base is hexadecimal, otherwise the base is decimal.
If the minus sign was part of the input sequence, the numeric value calculated from the sequence of digits is negated as if by unary minus in the result type.
If pos is not a null pointer, then a pointer ptr - internal to the conversion functions - will receive the address of the first unconverted character in str.c_str(), and the index of that character will be calculated and stored in *pos, giving the number of characters that were processed by the conversion.
Parameters
str - the string to convert
pos - address of an integer to store the number of characters processed
base - the number base
Return value
The string converted to the specified signed integer type.
Exceptions
std::invalid_argument if no conversion could be performed
std::out_of_range if the converted value would fall out of the range of the result type or if the underlying function (std::strtol or std::strtoll) sets errno to ERANGE.
A: When choosing between C-style functions like strtoll (which are of course easy to use with std::string as well) and std::stoll (which at first glance appears better suited for std::string) or boost::lexical_cast: Be aware that the two latter will throw exceptions in case they cannot parse the input string or the range overflows.
Sometimes this is useful, sometimes not, depends what you're trying to achive.
If you are not in control of the string to parse (as it's external data) but you want to write robust code (which always should be your desire) you always need to expect corrupted data injected by some malicious attacker or broken outside components. For corrupted data strtoll will not throw but needs more explicit code to detect illegal input data. std::stoll and boost::lexical_cast do auto detect and signal crappy input but you must make sure to catch exceptions somewhere to avoid being terminated(TM).
So choose one or the other depending on the structure of the surrounding code, the needs of the parsed results (sometimes illegal data being "parsed" into a 0 is absolutely OK) the source of the data to parse and last but not least your personal preferences. Neither of the functions available is generally superiour to the others.
A: Here we convert String consisting of HEX character to uint64_t hex value. All individual characters of string is converted to hex integer ony by one. For example in base 10 -> String = "123":
*
*1st loop : value is 1
*2nd loop : value is 1*10 + 2 = 12
*3rd loop : value is 12*10 + 3 = 123
So like this logic is used to convert String of HEX character to uint_64hex value.
uint64_t stringToUint_64(String value) {
int stringLenght = value.length();
uint64_t uint64Value = 0x0;
for(int i = 0; i<=stringLenght-1; i++) {
char charValue = value.charAt(i);
uint64Value = 0x10 * uint64Value;
uint64Value += stringToHexInt(charValue);
}
return uint64Value;
}
int stringToHexInt(char value) {
switch(value) {
case '0':
return 0;
break;
case '1':
return 0x1;
break;
case '2':
return 0x2;
break;
case '3':
return 0x3;
break;
case '4':
return 0x4;
break;
case '5':
return 0x5;
break;
case '6':
return 0x6;
break;
case '7':
return 0x7;
break;
case '8':
return 0x8;
break;
case '9':
return 0x9;
break;
case 'A':
case 'a':
return 0xA;
break;
case 'B':
case 'b':
return 0xB;
break;
case 'C':
case 'c':
return 0xC;
break;
case 'D':
case 'd':
return 0xD;
break;
case 'E':
case 'e':
return 0xE;
break;
case 'F':
case 'f':
return 0xF;
break;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502926",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "35"
} |
Q: Web application form post not receiving a file I have a form
<form action="/" method="post">
<input type="file" name="myFile" />
<input type="submit" name="submit" value="submit" />
</form>
I also have some C# code
if (Request["submit"] == "submit") {
Response.Write(Request.Files.Count);
}
If a user chooses a file on their system and submits, What reasons could there be for me seeing a "0" instead of a "1" in the Request.Files.Count property?
A: Try adding the enctype attribute to your <form>
<form enctype="multipart/form-data" action="/" method="post">
A: If you are using any kind of ajax (i.e. update panel) then you have to make sure you're doing a full page post back when submitting not a partial page postback.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: how to create a video for iPod touch app video ? for ppt presentation i want to create video for ipod touch app.
is their any possibility to create video
*
*from Xcode using simulator
*or directly from device
*or any other possibility
thank you very much
A: Please see: Is there a way I can capture my iPhone screen as a video?
This post describes many ways to capture video. It looks like there isn't a completely intuitive way to record the video, but this post lists some of the options others have used for their applications.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: c++: initializing static string members I'm having some problems initializing static string members in c++. I have several classes and each one is holding several static string members that represent an id. When I am initializing the variables by calling a static function everything is fine. However, when I'd like to assign one variable with the value of another it still holds empty string. What's problem with this code?
std::string A::id()
{
std::stringstream sst;
sst << "id" << i;
i++;
return sst.str();
}
std::string B::str = A::id(); //prints "id0";
std::string C::str = "str"; //prints str
std::string D::str = B::str; //prints "" <-- what's wrong here?
std::string D::str2 = C::str; //prints ""
It appears as if the variables I am referring to (B::str and C::str) havent been initialized yet. But I assume when D::str = B::str is executed C::str is initialized at the latest and therefore D::str should also hold the string "id0".
A: There is no guaranteed order of initialization for static variables. So don't rely on it.
Instead init them with actual literal's, or better yet, init them at run-time when they are really needed.
A: This is Static Initialization Fiasco.
As per the C++ Standard the initialization order of objects with static storage duration is unspecified if they are declared in different Translation units.
Hence any code that relies on the order of initialization of such objects is bound to fail, and this problem is famously known as The Static Initialization Fiasco in C++.
Your code relies on the condition that Initialization of B::str and C::str happens before D::str, which is not guaranteed by the Standard. Since these 3 static storage duration objects reside in different translation units they might be initialized in Any order.
How to avoid it?
The solution is to use Construct On First Use Idiom,in short it means replacing the global object, with a global function, that returns the object by reference. The object returned by reference should be local static, Since static local objects are constructed the first time control flows over their declaration, the object will be created only on the first call and on every subsequent call the same object will be returned, thus simulating the behavior you need.
This should be an Interesting read:
How do I prevent the "static initialization order fiasco"?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502934",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to change the sharpness and make a photo black and white using JavaScript? I have designed a basic webpage in HTML which is basically web app to edit the photos online.
Now I am unable to code the program as to how the colour sharpness brightness blurness, making a photo black and white and others haven't been possible.
How do we use HTML and JavaScript to make this work online?
A: You can do this using <canvas>:
https://developer.mozilla.org/en/Canvas_tutorial
*
*Draw image on <canvas> using Javascript
*Canvas gives raw pixel access. Run filtering code written in Javascript. Example: http://blog.nihilogic.dk/2008/03/jsimagefx-javascript-image-effects.html
*You can use <canvas> in a similar manner in HTML code as <img> - both are basically pixel buffers
Note that you cannot access pixel data of images loaded from different origin.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: TYPO3: how to supress deprecated warnings? I tried modifying the php.ini file (error_reporting = E_ALL & ~E_DEPRECATED), but with no result. There's an older TYPO3 project which I would like to examine, and all these warnings are really annoying..
Thanks in advance.
A: I'm not sure if this will work on your version of Typo3 but try setting the following options in the typo3conf/localconf.php or via the Install Tool.
$TYPO3_CONF_VARS['SYS']['displayErrors'] = '0'; // or '-1' to see other errors
$TYPO3_CONF_VARS['SYS']['errorHandlerErrors'] = 22519; // E_ALL ^ E_DEPRECATED ^ E_NOTICE (everything except deprecated-msgs and notices)
$TYPO3_CONF_VARS['SYS']['syslogErrorReporting'] = 22519; // E_ALL ^ E_DEPRECATED ^ E_NOTICE (everything except deprecated-msgs and notices)
$TYPO3_CONF_VARS['SYS']['belogErrorReporting'] = 22519; // E_ALL ^ E_DEPRECATED ^ E_NOTICE (everything except deprecated-msgs and notices)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502948",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Can a script update the Identity tab fields of Application Pool properties in IIS 6.0+ I am a developer and I have arrived at a solution to a webservice authentication problem that involved ensuring Kerberos was maintained because of multiple network hops. In short:
*
*A separate application pool for the virtual directory hosting the webservice was established
*The Identity of this application pool is set to a configurable account (DOMAINname\username which will remain constant but the strong password is somehow changed every 90 days I think); at a given point in time, the password is known or obtainable somehow by our system admin).
Is there a script language that could be used to setup a new application pool for this application and then set the identity as described (rather than manual data entry into property pages in IIS)?
I think our system admin knows a little about Powershell but can someone help me offer him something to use (he will need to repeat this on 2 more servers as the app is rolled out). Thanks.
A: You can use such PowerShell script:
Import-Module WebAdministration
$appPool = New-WebAppPool -Name "MyAppPool"
$appPool.processModel.userName = "domain\username"
$appPool.processModel.password = "ReallyStrongPassword"
$appPool.processModel.identityType = "SpecificUser"
$appPool | Set-Item
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Why is Spring Container Destroying Beans Immediately After Creating Them? Immediately after creating all the beans declared in the various context files of my application, Spring notifies (see below) that it is destroying singletons and that context initialization failed.
[INFO] Destroying singletons in
org.springframework.beans.factory.support.DefaultListableBeanFactory
org.springframework.web.context.ContextLoader [ERROR] Context
initialization failed
Does anyone know why the Spring container is destroying all the beans right after creating them?
NOTE: There are no warnings or errors in the log output aside from the above context initialization failure error -- see below.
[DEBUG] Eagerly caching bean 'uploadService' to allow for resolving potential circular references
2011-09-21 15:19:08 org.springframework.beans.factory.annotation.InjectionMetadata
[DEBUG] Processing injected method of bean 'uploadService': AutowiredFieldElement for private
org.apache.commons.fileupload.disk.DiskFileItemFactory com.faciler.ws.services.UploadService.diskFileFactory 2011-09-21 15:19:08
org.springframework.beans.factory.support.DefaultListableBeanFactory
[DEBUG] Creating shared instance of singleton bean
'diskFileItemFactory' 2011-09-21 15:19:08
org.springframework.beans.factory.support.DefaultListableBeanFactory
[DEBUG] Creating instance of bean 'diskFileItemFactory' 2011-09-21
15:19:08
org.springframework.beans.factory.support.DefaultListableBeanFactory
[INFO] Destroying singletons in
org.springframework.beans.factory.support.DefaultListableBeanFactory@b0ede6:
defining beans [org.springframework.beans.
A: When faced with a situation where you don't know what's causing the issue, remove complexity. In your case, remove most of your beans from the configuration, whether XML or annotation-based. Start adding them back in and see which one breaks the startup cycle. Then you can focus in on why that one bean is causing the failure.
A: Short answer:
Try increasing JVM memory
here: -XX:PermSize=64m -XX:MaxPermSize=128m -Xms256m -Xmx768m
Detailed answer:
Often Spring desperately destroys beans (hence the communicate) as a way of gaining some memory.
Additionally high Garbage Collector activity slows down spring initialization.
Above I provide settings working for me. Depending on your application complexity you may want to play around with these values.
Disclaimer: It's not always the case. But frequently my spring apps beak down as a result of running them with default JVM memory settings.
A: The context initialization failure is causing spring to destroy the beans already successfully created - not the other way round. You will probably need to up the log level to INFO or DEBUG to get to the root cause.
A: Debuging is the best way to find the root cause. If you are using Eclipse for development, run in the debug mode. wait for the control goes to the catch block and in the variables editor you can find the exception object, which should have the stack trace. This way you can find the root cause of the issue.
A: I have recently faced similar issue. One possible solution to the problem would be to check your main class or wherever you initialize the spring context. Sometimes it happens that exceptions thrown by spring context are caught and never printed or re-thrown. Consider the example below:
AbstractApplicationContext context = null;
try {
context = new ClassPathXmlApplicationContext("beans.xml");
// context.registerShutdownHook();
} catch (Exception e) {
e.printStackTrace();
//print or log error
} finally {
if (context != null) {
context.close();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502950",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "17"
} |
Q: Creating a Help Center in VB.NET I'm developing a program in vb.net, and I want to add in some help pages to the program, without using web-based help, so more like when you hit F1 in the Microsoft Office programs.
Is there a straightforward way of doing this, other than just making it via lots of forms?
Thanks in advance!
A: Perhaps a small Sqlite database with the help content and a help browser that reads the content from the database?
Other than that you have CHM and HLP formats. With CHM you can use the HelpProvider to provide this information to your user.
http://en.wikipedia.org/wiki/Microsoft_Compiled_HTML_Help
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What's the best way to distribute your SDK if the end user is required to link against the Debug CRT? I work for a camera company and we provide an SDK for our customers. Historically we only provided a release build of our SDK that was built against the non-debug CRT. As part of our SDK package we provide a number of examples on how to use the SDK. The examples have Debug project configurations which use the debug CRT. In some cases we run into strange behaviour due to the fact that these examples and the library that they link against use different CRT's.
My questions is what is the appropriate way to deal with this sort of situation? Should we be distributing a debug version of our library that uses the debug CRT? As long as we don't provide a pdb or at most a stripped pdb, then all proprietary information should still remain hidden. Is it correct to assume that in doing this there should be no other negative effects other then a larger, not optimised binary?
Is it common practice to distribute a debug binary linked against the debug CRT or should we just continue distributing only the release build?
A: Yes, you'll need to distribute Debug and Release builds of your library. Built with respectively /MDd and /MD so the CRT can be shared. Different versions too, built against, say, the VS2005, VS2008 and VS2010 versions of the CRT.
This is of course painful. To narrow it down to a single library, you'll need to carefully craft your public interface so it doesn't expose any C++ objects or any pointers that need to be released by the client code. Exceptions are also taboo. A common solution is to use COM. Especially an Automation compatible interface is useable by most any language runtime in common use on Windows.
A: You might consider an Optimized Debug build, where it is set to use the debug versions of the libraries but has all the optimization flags set as they would be in a Release build. This will prevent subtle differences in execution from affecting the user experience.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502952",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery 'if' statement not working This should be a simple if statement, but it's not working for me. Essentially, when you click an element, I want that element to be highlighted and the ID to be put into a the variable value. However, if in the situation the same element is clicked twice, I want to value = NULL.
(function($){
$(".list").click(function() {
$(this).toggleClass("hilite");
var temp = $(this).attr('id');
if (value != temp) {
var value = $(this).attr('id');
} else {
value = NULL;
}
});
})(jQuery);
A: Your primary problem is that you're "hoisting" the value variable by redefining it with the var keyword. This code can also be written more efficiently with a lot less code. This should work:
(function($) {
// somewhere outside click handler
var value = '';
// click handler
$(".list").click(function() {
var id = $(this).toggleClass('hilite').attr('id');
value = (value === id) ? null : id;
/* or if you prefer an actual if/else...
if (value === id) {
value = null;
else {
value = id;
}
*/
});
})(jQuery);
Edit: a couple general comments about the original snippet that might be useful:
*
*NULL should be null
*Try not to run the same selector multiple times, or recreate a jQuery object from the same DOM object multiple times - it's much more efficient and maintainable to simply cache the result to a variable (e.g., var $this = $(this);)
*Your comparison there is probably "safe", but better to use !== than != to avoid unintentional type coercion.
*Not sure how exactly you intended to use value in the original example, but always remember that variables are function-scoped in JavaScript, so your var value statement is hoisting the value identifier for that entire function, which means your assignments have no effect on anything outside that click handler.
A: You need to declare var value outside the scope of the function, so that its value is maintained across function calls. As it is, the value variable is lost right after it is set, because it goes out of scope.
var value = null;
(function($){
$(".list").click(function() {
$(this).toggleClass("hilite");
var temp = $(this).attr('id');
if (value != temp) {
value = temp;
} else {
value = null;
}
});
})(jQuery);
A: You could do:
(function($){
var tmp = {};
$(".list").click(function() {
$(this).toggleClass("hilite");
var id = $(this).attr('id');
if (!tmp[id]) {
var value = id;
tmp[id] = true;
} else {
value = NULL;
tmp[id] = false;
}
});
})(jQuery);
In this way you use a tmp object that stores the state for all the different id's
A: It might not be skipping that statement, you might just be getting a confusion over the implied global "value" and the local "value".
(function($){
$(".list").click(function() {
$(this).toggleClass("hilite");
var temp = $(this).attr('id');
if (value != temp) { // <-----------------Implied global var called "value"
var value = $(this).attr('id'); // <---Local variable valled "value"
} else {
value = NULL; // <---------------------Which one am I
}
});
})(jQuery);
Also, it ought to be value = null as NULL is just an undefined variable.
This should be a working example of both points:
var value = null;
(function($){
$(".list").click(function() {
$(this).toggleClass("hilite");
var temp = $(this).attr('id');
if (value != temp) {
value = $(this).attr('id');
} else {
value = null;
}
});
})(jQuery);
A: Do you not need to declare value before you use it in the conditional statement?
A: you aren't setting a value in this function.
var value = "NULL";
(function($){
$(".list").click(function() {
$(this).toggleClass("hilite");
var temp = $(this).attr('id');
if (value != temp) {
value = $(this).attr('id');
} else {
value = "NULL";
}
});
})(jQuery);
A: The variable value is not defined. And it either needs to be a global variable or you could use jQuery's $('.selector).data() method to attach it to the element:
http://api.jquery.com/data/
I also recommend using !== for the comparison, since that compares the type of the variable as well as the content.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Zend navigation breadcrumbs I have an xml navigation system with article as an element. The breadcrumb works as far as my article page where i display the list of articles with their title (as a link) and a teaser paragraph. The page where i display the full article does not show any breadcrumb navigation.
I know i'm doing something wrong but since i am new to zend i can't figure out where.
I would be grateful if someone could point me towards the right direction.
The XML Navigation:
<?xml version="1.0" encoding="UTF-8"?>
<configdata>
<nav>
<home>
<label>Home</label>
<controller>index</controller>
<action>index</action>
<pages>
<about>
<label>About</label>
<controller>index</controller>
<action>about</action>
</about>
<board>
<label>Executive Committee</label>
<controller>index</controller>
<action>committee</action>
</board>
<events>
<label>Events</label>
<controller>index</controller>
<action>events</action>
</events>
<member>
<label>CNFS Members</label>
<controller>index</controller>
<action>member</action>
</member>
<news>
<label>Blog</label>
<controller>blog</controller>
<action>index</action>
</news>
<contact>
<label>Contact</label>
<controller>index</controller>
<action>contact</action>
</contact>
</pages>
</home>
</nav>
</configdata>
This is the function in the bootstrap file for navigation.
<?php
protected function _initViewNavigation(){
$this->bootstrap('layout');
$layout = $this->getResource('layout');
$view = $layout->getView();
$config = new Zend_Config_Xml(APPLICATION_PATH.'/configs/navigation.xml','nav');
$navigation = new Zend_Navigation($config);
$view->navigation($navigation);
}
?>
This is how i display the breadcrumbs in the view:
<?php echo 'Your are here: ' . $this->navigation()->breadcrumbs() ->setMinDepth(0)->setLinkLast(false)->setSeparator(" / ");?>
A: From your xml, i guess that your articles list is at /blog, and an single article at /blog/article/'articleId' or something similar.
Your "news" section in your navigation map defines an action, "index" but to display an article you use an other action, that's why this node isn't matched anymore.
I guess you would like the current article's title to show at the end of your breadcrumb, and to do that you must append a custom page as a child of the "news" node, and setting it as 'active' :
public function articleAction(){
//get your article
$article = ....
$page = new Zend_Navigation_Page_Mvc(array(
'label' => $article->getTitle(),
'controller' => 'blog',
'action' => 'article',
'params' => array(
'id' => $article->getId() // replace with the param name + value that you actually use in your url
)
)
);
$page->setActive(true);
$this->view->_helper->navigation()->getContainer()->findOneBy('controller','blog')->addPage($page);
I wrote this code by memory without testing, so if it doesn't work as expected just tell me, i'll test and update this answer
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Get foreach() loop to display array output in given manner SQL:
SELECT uFName, uLName, listTitle, listPropPrice, listCmt, listDt, mFName, mLName, moAmt, moDtOff
FROM User U, Listing L, Merchant M, MerchantOffer MO
WHERE U.uID = L.uID
and L.listID = MO.listID
and M.mID = MO.mId
PHP
<?php
$result = $sth->fetchAll();
print_r($result); //or var_dump($result); for more info
foreach($result as $row){
print_r($row);
}
?>
Kolinks output:
Why is it duplicating everything twice??
A: Try this:
$half = array_splice($row,0,5);
echo implode(" ",$half)."<br /><br />Merchant Offered:<br />".implode(" ",$row);
Basically it extracts the first five values and concatenates them with space, then puts in the "Merchant Offered" text, then concatenates the remaining values.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Maximum range error on click event in jQuery I have a reproducable error here, where I run into a Uncaught RangeError: Maximum call stack size exceeded
It's just a click event I call onto a link.
My HTML:
<div id="box">
<a href="#">test</a>
</div>
My Javascript:
$('#box').click(function() {
("a", $(this)).click();
});
Now, clicking the #box leads to an error.
http://jsfiddle.net/DMAMv/2/
A: That's because it is recursively triggering the click event. This is caused by two problems.
The first is this innocent looking line:
("a", $(this)).click(); # note the missing $ at the beginning
That essentially reduces to $(this).click() (because the comma operator evaluates both operands and returns the second one) and so your click event on #container triggers itself. Consider the following examples - http://jsfiddle.net/2VnbG/ and http://jsfiddle.net/2VnbG/1/ - notice how the parent div is targetted when the $ is missing.
Prepend the line with the missing $ to solve that issue, i.e. $("a", $(this)).click();
The next problem is that a click event on the anchor will bubble up to the parent object (in your case, #container). If the parent has a bound function on the click event which triggers a new event, then the cycle is going to repeat infinitely.
To solve that, use event.stopPropagation() to stop the event from bubbling up the DOM tree.
Here's an example with the above fixes in place: http://jsfiddle.net/DMAMv/9/
A: mine was a list item in a dropdown so i wanted the event to keep bubbling so the dropdown would be closed. this is the solution i used:
$('div#outer').click(function (e) {
if (e.target == e.currentTarget) // prevents bubbled events from triggering
$($(e.currentTarget).children()[0]).trigger('click');
});
A: You should stop the propagation with stopImmediatePropagation(), otherwise you have too much rcursion
$('#box').click(function() {
$("a:first", this).click();
});
$('a').click(function(e){
e.stopImmediatePropagation();
alert('hi');
});
fiddle http://jsfiddle.net/DMAMv/8/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Don't want to tap twice to share message in Facebook using sharekit app? I sharing message in Facebook by integrating sharekit in my iPhone application.I have written the method facebookButtonPressed which I am calling on tapping one button.
First time when facebook screen is appearing its asking for authentication in Facebook . I have given userid and password of my Facebook existing account and tapped for login. Now the facebook authentication screen disappeared.Now again I tapped the button to call the methoed facebookButtonPressed,then I got the message sharing screen.
I don't want to tap twice to get the message sharing screen.If any one has already solved this issue please help me.
-(void)facebookButtonPressed{
NSString* body = @"test body";
SHKSharer *fb = [[SHKFacebook alloc] init];
SHKItem *item = [[SHKItem alloc] init];
item.shareType = SHKShareTypeText;
item.text = [body length]>140?[body substringToIndex:139]:body;
fb.item = item;
if(![fb isAuthorized])
[fb authorize];
[fb tryToSend];
}
A: Try the below code, there will be action sheet to select how to share,you need to select Facebook.
NSString* body = @"test body";
SHKItem *item = [SHKItem text:body];
SHKActionSheet *actionSheet = [SHKActionSheet actionSheetForItem:item];
[actionSheet showFromToolbar:self.navigationController.toolbar];
A: Try to put the following:
item.shareType = SHKShareTypeText;
item.text = [body length]>140?[body substringToIndex:139]:body;
fb.item = item;
behind [fb tryToSend];
So that you first check whether fb is authorized and then share. Hope it helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502963",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I do a `POST` with `Node.js`? I've followed examples and samples and everything and I am struggling.. the equivalent PHP code I'm using is:
$url = json_encode($userArray);
$postURL = "https://mysite.com/v4/bulk?api_key=51076b4234e62c7b4ef8e33717a3bce5";
$ch = curl_init($postURL);
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt ( $ch, CURLOPT_HTTPHEADER, array ( 'Content-Type: application/json'));
curl_setopt ($ch, CURLOPT_POSTFIELDS,$url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($ch);
$result = json_decode($result, true);
I just can't get this to work within Node. Any help would be greatly appreciated.
Thanks.
A: request
var request = require("request");
request({
url: "https://...",
method: "POST",
json: userArray
}, function _callback(err, res, body) {
var result = body;
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Hashing string to integer (no security needed)
Possible Duplicate:
php hash form string to integer
I am looking to hash a url like http://example.com to a integer hash, small in size preferably. I would like to know if there is any built-in php functions that can do that.
The purpose for this is for speed in my mysql database for other operations inside mysql when I am comparing this hashes.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Jackson deserialization Unexpected token (END_OBJECT), I am trying to deserialize a JSON Object into a Java Object using Jackson annotation on one Abstact class "Animal":
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property = "type")
@JsonSubTypes({@Type(value = Dog.class, name = "chien"),
@Type(value = Cat.class, name= "chat")})
and here is a sample JSON string:
{
"name": "Chihuahua",
"type": {
"code": "chien",
"description": "Chien mechant"
}
}
The problem is that the property "type" in the JSON object is also an object. when i try to deserialize i have this Exception:
Caused by: org.codehaus.jackson.map.JsonMappingException: Could not resolve type id '{' into a subtype of [simple type, class Animal]
I tried to use "type.code "as "property" value but nothing. the Exeption is this
Caused by: org.codehaus.jackson.map.JsonMappingException: Unexpected token (END_OBJECT), expected FIELD_NAME: missing property 'type.code' that is to contain type id (for class Animal)
Any idea what's wrong. Thank you.
A: Throwing this out there after having found no solution to this problem. I came up with my own style if it interests anyone who stumbles upon this. Feel free to add your own solutions if you find another way.
I have implemented in my enums to fix this problem has been to add a findByType method that allows you to search on a string representation of the enum key value.
So in your example you have an enum with a key/value pair as such,
pubilc enum MyEnum {
...
CHIEN("chien", "Chien mechant")
...
}
// Map used to hold mappings between the event key and description
private static final Map<String, String> MY_MAP = new HashMap<String, String>();
// Statically fills the #MY_MAP.
static {
for (final MyEnum myEnum: MyEnum.values()) {
MY_MAP.put(myEnum.getKey(), myEnum);
}
}
and then you would have a public method findByTypeCode that would return the type for the key you search on:
public static MyEnum findByKey(String pKey) {
final MyEnum match = MY_MAP.get(pKey);
if (match == null) {
throw new SomeNotFoundException("No match found for the given key: " + pKey);
}
return match;
}
I hope this helps. Like I said, there may be a solution out there that tackles this directly, but I haven't found one and don't need to waste more time searching for a solution when this works well enough.
A: I'm beginner with jackson but I think you must search tree parsing like explained here
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: Popups in XBAP stop receiving anything but mouse events after losing focus? I have a Popup control in my XBAP, and whenever the popup control is open and it loses focus (such as an alert box, a breakpoint, switching to another application in Windows, switching to another Tab in my web browser, etc), the Popup no longer responds to anything but Mouse events.
I cannot:
*
*Select a TextBox with the Mouse
*Highlight Text in a TextBox with the Mouse
*Use the Tab key to change controls
*Select a ComboBox item using the Keyboard when I open it with the Mouse
I can:
*
*Change a ComboBox value with the Mouse
*Click a button with the Mouse
A: Closest thing to this problem I could find was http://social.msdn.microsoft.com/Forums/en/wpf/thread/cd723315-187f-4d8b-a97d-6aac38a2ed1f
Programmer was losing focus to their popup and never able to get it back. According to a Microsoft Supporter. "it looks like you hit a known bug related to Popup in XBAP."
You can see if it's similar to your issue, but the problem was never solved. OP ended up adding a canvas to the main page and a usercontrol to replace the popup window.
If this in fact isn't some sort of unavoidable behaviour, and I were tackling this problem from scratch, I would check when your application regains focus and see whether your application is getting both the keyboard and logical focus, and that the focus scope is correct all the way down to the controls on your popup.
In Logical focus, there is the notion of a “Focus Scope”, which is an application-defined boundary around a group of UIElements. Each Focus Scope maintains its own “Focused Element” which can be different than the element that has Keyboard focus.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to access external mysql database in android? Which library for http requests? I already am planning to use php to access the actual database then post the data so that the android app can then proceed to grab it. I am using the database to store longitude and latitude of geopoints for a location based application. I have my map drawing and class for drawing overlays I am just not sure where to start from here.
I want to use http requests to call a php file that will grab geopoints from the mysql database.
A: You could use AndroidHttpClient if you want and also the Apache DefaultHttpClient.
You'll just have to make a RestService in php that will give you the data you need. You will execute HttpGet or HttpPost and you can return data in XML or JSON. Then you can parse it in Android using XMLPullParser or JSON.
Good luck.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Globally accessible property in EJB I have a JavaEE application that needs to access a file in order to obtain certain informations about the installation.
This access is read-only, I do not need to change that file within the application, i.e. I do not need the "file" directly, just it's content (a byte array).
There's a restriction on EJBs using the filesystem. I do understand the problems associated with it but I can't figure out a alternative solution to this.
The file path should be configurable by the user, but there's no need to track changes to the file contents. Once loaded, it stays the same unless the user choose another file. So, I can't package it within the application archive.
This file-based approach is a decision made long time ago by some legacy systems we have. There's no practical way to change it now, i.e. I need that my JavaEE application uses the file (at least once) to load it's content.
Another restriction is that this file can not be persisted on the database.
How should I do this without violating the EJB restriction of filesystem access?
I thought about user uploading the file to the server and then persisting this information on the server. But how do I do this? This information should be globally accessible, including multiple instances of the server (e.g. in a cluster architecture).
The user should configure this file once (not necessarily within the main application, it could be other app just to configure this). Even if the server restart, the file's content should still be accessible without any further configuration by the user.
I'm using JavaEE 5 with EJB 3.0 specification on a GlassFish v2.1.1 server.
Thanks,
Thiago.
A: My suggestion is as follows:
*
*User JAX-WS with EJB 3 for enable to user upload the file through a WebService (You can provide the client).
*Store the content of the file in the JNDI using the menthod bind() of Context class. As I know the JNDI will be propagated across the cluster, but maybe you need to check the doc of your Java EE Application Server.
Hope it can be useful.
A: You have two choices from an EJB:
1) Violate the spec and use the standard Java File APIs to access it from your EJB. Can be 'safe' if you understand what this means in terms of clustering, transactions etc. Since you are only doing read only access you should be OK.
2) Use a JCA adapter that supports file system access. You could write your own, try an open source one (I think there's one on source forge), or purchase one - I think oracle sells one for use with Glassfish oracle edition. Probably overkill for your situation.
You could also add a web app component to your project (Servlet) which does the file access since file io is permitted in that spec.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to get the output of a shell function without forking a sub shell? I have the following functions.
hello () {
echo "Hello"
}
func () {
hello
echo "world"
}
If I don't want the output of the hello function to be printed but want to do something with it, I want to capture the output in some variable, Is the only possible way is to fork a subshell like below? Is it not an unnecessary creation of a new child process? Can this be optimized?
func () {
local Var=$(hello)
echo "${Var/e/E} world"
}
A: An ugly solution is to temporarily replace echo so that it sets a global variable, which you can access from your function:
func () {
echo () {
result="$@"
}
result=
hello
unset -f echo
echo "Result is $result"
}
I agree it's nasty, but avoids the subshell.
A: How about using a file descriptor and a Bash here string?
hello () {
exec 3<<<"Hello"
}
func () {
local Var
exec 3>&-
hello && read Var <&3
echo "${Var/e/E} world"
exec 3>&-
}
func
A: You can make the caller pass in a variable name to hold the output value and then create a global variable with that name inside the function, like this:
myfunc() { declare -g $1="hello"; }
Then call it as:
myfunc mystring
echo "$mystring world" # gives "hello world"
So, your functions can be re-written as:
hello() {
declare -g $1="Hello"
}
func() {
hello Var
echo "${Var/e/E} world"
}
The only limitation is that variables used for holding the output values can't be local.
Related post which talks about using namerefs:
*
*How to return an array in bash without using globals?
A: Not a bash answer: At least one shell, ksh optimises command substitution $( ... ) to not spawn a subshell for builtin commands. This can be useful when your script tends to perform a lot of these.
A: Do you have the option of modifying the hello() function? If so, then give it an option to store the result in a variable:
#!/bin/bash
hello() {
local text="hello"
if [ ${#1} -ne 0 ]; then
eval "${1}='${text}'"
else
echo "${text}"
fi
}
func () {
local var # Scope extends to called functions.
hello var
echo "${var} world"
}
And a more compact version of hello():
hello() {
local text="hello"
[ ${#1} -ne 0 ] && eval "${1}='${text}'" || echo "${text}"
}
A: This doesn't literally answer the question, but it is a viable alternate approach for some use cases...
This is sort of a spin off from @Andrew Vickers, in that you can lean on eval.
Rather than define a function, define what I'll call a "macro" (the C equivalent):
MACRO="local \$var=\"\$val world\""
func()
{
local var="result"; local val="hello"; eval $MACRO;
echo $result;
}
A: *
*Redirect the stdout of the function to the FD of the write end of an "automatic" pipe. Then, after the (non-forking) call, ...
*Read the FD of the read end of the same pipe.
#!/usr/bin/env bash
# This code prints 'var=2, out=hello' meaning var was set and the stdout got captured
# See: https://stackoverflow.com/questions/7502981/how-to-get-the-output-of-a-shell-function-without-forking-a-sub-shell
main(){
local -i var=1 # Set value
local -i pipe_write=0 pipe_read=0 # Just defensive programming
create_pipe # Get 2 pipe automatic fd, see function below
# HERE IS THE CALL
callee >&"$pipe_write" # Run function, see below
exec {pipe_write}>&- # Close fd of the pipe writter end (to make cat returns)
local out=$(cat <&"$pipe_read") # Grab stdout of callee
exec {pipe_read}>&- # Just defensive programming
echo "var=$var, out=$out" # Show result
}
callee(){
var=2 # Set an outer scope value
echo hello # Print some output
}
create_pipe(){
: 'From: https://superuser.com/questions/184307/bash-create-anonymous-fifo
Return: pipe_write and pipe_read fd => to outer scope
'
exec 2> /dev/null # Avoid job control print like [1] 1030612
tail -f /dev/null | tail -f /dev/null &
exec 2>&1
# Save the process ids
local -i pid2=$!
local -i pid1=$(jobs -p %+)
# Hijack the pipe's file descriptors using procfs
exec {pipe_write}>/proc/"$pid1"/fd/1
# -- Read
exec {pipe_read}</proc/"$pid2"/fd/0
disown "$pid2"; kill "$pid1" "$pid2"
}
main
Note that it would be much shorter code using an automatic normal fd as follows:
exec {fd}<> <(:)
instead of using the create_pipe function as this code does (copying this answer). But then the reading FD line used here like:
local out=$(cat <&"$fd")
would block. And it would be necessary to try reading with a timeout like the following:
local out=''
while read -r -t 0.001 -u "${fd}" line; do
out+="$line"$'\n'
done
But I try to avoid arbitrary sleeps or timeouts if possible.\
Here the closing of the FD of write end of the pipe makes the read cat line returns at the end of content (magically from my poor knowledge).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502981",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: SQL Server 2005 statements returning the same results Why are these two statements returning the same results? I'm looking at the total number of orders and the sum of the prices for some publications. The first statement gets records from the past 24 hours and the second one is supposed to show the same sums but from the start of the month to the current date. When I look at the gridviews to which they are filling, it looks like BOTH of them are displaying the sums from the past 24 hours. Anything noticeable?
SELECT pubName AS Publication, COUNT(*) AS Total, '$' + CONVERT(VARCHAR(12), SUM(CAST(price AS DECIMAL))) AS Price FROM [SecureOrders] WHERE DateTime >= DATEADD(day, -1, GETDATE()) GROUP BY pubName
SELECT pubName AS Publication, COUNT(*) AS Total, '$' + CONVERT(VARCHAR(12), SUM(CAST(price AS DECIMAL))) AS Price FROM [SecureOrders] WHERE DateTime >= DATEADD(DAY, 1-DAY(GETDATE()), DATEDIFF(DAY, 0, GETDATE())) GROUP BY pubName
A: IF one of them is supposed to be the past 24 hours, you should be looking at hours.
SELECT
pubName AS Publication
,COUNT(*) AS Total
,'$' + CONVERT(VARCHAR(12), SUM(CAST(price AS DECIMAL))) AS Price
FROM [SecureOrders]
WHERE DateTime >= DATEADD(hh, -24, GETDATE())
GROUP BY pubName
Otherwise the dates are perfectly fine in both...assuming the DateTime column is in fact DateTime I would check the datasources for the grid.
A: Not sure why you need the DateDiff clause. Maybe I'm missing something.
SELECT pubName AS Publication, COUNT(*) AS Total, '$' + CONVERT(VARCHAR(12), SUM(CAST(price AS DECIMAL))) AS Price FROM [SecureOrders] WHERE DateTime >= DATEADD(DAY, 1-DAY(GETDATE()), GETDATE()) GROUP BY pubName
Edit: Ignore the above, I was being dense(r).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: missing argument & undefined variable; the reason for the errors? I am receiving the following errors, I'm asking if anyone knows a possible reason why I would get these. I am newbish so help would be grateful...
I will also post the lines in question.
A PHP Error was encountered
Severity: Warning
Message: Missing argument 1 for Welcome::quote()
Filename: controllers/welcome.php
Line Number: 64
and
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: productid
Filename: controllers/welcome.php
Line Number: 65
The lines in question;
64 function quote($productid){
65 if ($productid > 0){
66 $fullproduct = $this->MProducts->getProduct($productid);
67 $this->MQuotes->updateQuote($productid,$fullproduct);
68 redirect('welcome/product/'.$productid, 'refresh');
69 }else{
70 $data['title'] = '... | Quote';
..
.. if (count($_SESSION['quote']) == true){
.. $data['main'] = 'quote';
.. $data['navlist'] = $this->MCats->getCategoriesNav();
.. $this->load->vars($data);
.. $this->load->view('template');
.. }else{
.. redirect('welcome/index','refresh');
.. }
.. }
.. }
what's wrong with $productid??
A: It means you're not passing the required amount of segments in your URL
/welcome/quote/product_id
It seems you're requesting:
/welcome/quote
If you want to be able to access the latter without an error, give it a default value:
function quote($productid = -1){
//
}
and then you can do:
function quote($productid = null){
if (is_null($productid)) {
// one workflow
} else {
// another workflow
}
}
If you are passing the required amount of segments however, update the question to include the contents of your /config/routes.php file (assuming you've edited it).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ASP ListBox returns -1 I have a an ASP listBox. Whenever I select a new item in the list, the following function gets called:
protected void prevSubList_SelectedIndexChanged(object sender, EventArgs e)
{
// Get the currently selected item in the ListBox index
int index = prevSubList.SelectedIndex;
if (index < 0)
{
return;
}
//get the nominee for that index
Nominees currNominee = nominees[index];
populateFields(currNominee);
}
<td ID="previousSubmissions" align="left">
<asp:ListBox ID="prevSubList" runat="server" Height="16px" Width="263px"
Rows="1" onselectedindexchanged="prevSubList_SelectedIndexChanged"
AutoPostBack="True">
</asp:ListBox>
</td>
The problem is int index = prevSubList.SelectedIndex; always evaluates to -1. There are three items in my list, say I select the second one, I would expect the value to be 1, but it is -1. Any ideas why?
A: You are probably binding the data on Page_Load and you are not checking whether IsPostBack is true.
Example:
if (!IsPostBack)
{
Dictionary<string, string> data = new Dictionary<string, string>();
for (int i = 0; i < 10; i++)
data.Add("i" + i, "i" + i);
prevSubList.DataSource = data;
prevSubList.DataBind();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502985",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: CollectionAssert.Contains(myList, myItem) != Assert.IsTrue(myList.Contains(myItem)) I have been looking at implementing unit tests for a controller controller, specifically around testing collections. On the MSDN example the use of CollectionAssert.Contains() confirms whether an object appears in a list.
I have a List<myObject> where myObject implements IEquatable (i.e. implementing a Equals(), so that the List<myObject>.Contains() is able to correctly discern the existence (or non-existence of an object of type myObject in the list).
The CollectionAssert.Contains() (for an MS-VS test, not nunit) function however, does not appear to call Equals().
So I'm wondering if it's for use on simple arrays?
If not, how is it able to compare custom objects?
I've simply changed my assert in this case to Assert.IsTrue(myList.Contains(myObjectInstance)).
A: Looking at the code for CollectionAssert.Contains(), the actual comparison is done by iterating the collection, and comparing each element to the target elements with object.Equals(current, target).
So the answer to your question is that if you haven't overridden the object version of Equals() so that it dispatches to your IEquatable<T> version, you should. Otherwise the test is going to fail if reference equality isn't satisfied, since the IEquatable<T> overload of Equals() doesn't override the overload inherited from object.
A: It seems CollectionAssert.Contains is not looking at your object's member values, but is comparing instances' memory address. The following example's CollectionAssert will fail, due to the fact that, although they have the same member values, obj and obj2 are not the same instance object;
MyType obj = new MyType { prop1 = "foo", prop2 = "bar" };
MyType obj2 = new MyType { prop1 = "foo", prop2 = "bar" };
List<MyType> lstObj = new List<MyType> { obj2 };
CollectionAssert.Contains(lstObj, obj);
That being said, the following example's CollectionAssert will succeed because it will be searching for obj2, and not any object that equals obj2;
MyType obj = new MyType { prop1 = "foo", prop2 = "bar" };
MyType obj2 = new MyType { prop1 = "foo", prop2 = "bar" };
List<MyType> lstObj = new List<MyType> { obj2 };
CollectionAssert.Contains(lstObj, obj2);
In other words, CollectionAssert.Contains compares instances and List(T).Contains "determines equality by using the default equality comparer, as defined by the object's implementation of the IEquatable.Equals method for T (the type of values in the list)."
Reference : http://msdn.microsoft.com/en-us/library/bhkz42b3.aspx
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502988",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to clear text box value when user clicks inside it <asp:TextBox ID="Txt_search" runat="server">Group Name..</asp:TextBox>
I want to clear the text inside the text box when user clicks inside the text box to enter the keyword to search. How do I do that?
A: with jquery:
$(function() {
$('input[type=text]').focus(function() {
$(this).val('');
});
});
from: How to clear a textbox onfocus?
A: The script below handles both the onfocus and onblur events removing your default "Group Name.." when focused and adding it back if the user moves off the field without changing anything.
<script type="text/javascript">
var txtsearch = document.getElementById("Txt_search");
txtsearch.onfocus = function () {
if (this.value == "Group Name..") {
this.value = "";
}
};
txtsearch.onblur = function () {
if (this.value.length == 0) {
this.value = "Group Name...";
}
}
</script>
A: using jquery to clear textbox on focus and set it back with default on blur
$(document).ready(function(){
$('#<%=Txt_search.ClientID%>')
.focus(function(){
if($(this).val()=='Group Name..')
{
$(this).val('');
}
})
.blur(function () {
if ($(this).val() == '') {
$(this).val('Group Name..');
}
});
});
Demo
A: I guess you could do that easily using jQuery something like below.
$('#<%=Txt_search.ClientID%>').click(function() {
$(this).val("");
});
A: Since you are using asp.net webforms, i think you'll be better off using the AjaxControlToolkit specifically the TextBoxWaterMarkExtender control.
See sample code below.
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:TextBoxWatermarkExtender ID="TextBox1_TextBoxWatermarkExtender"
runat="server" Enabled="True" TargetControlID="TextBox1"
WatermarkText="Group Name ...">
</asp:TextBoxWatermarkExtender>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7502999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: [Flash Builder] Disable security sandbox warnings (not fix them) I am building a project where I use an external API loaded from the web, and I also load files locally. As I understand it, I cannot load both local and external files without causing a security sandbox error.
Once I open the API it seems to try and listen to mouse events and such, and causes a security sandbox error every single frame.
Its really annoying since I am trying to trace some debug outputs but I can't read them as they get overwhelmed by the error messages.
I know I cannot fix it, but I would simply like to disable these warnings.
Is there any way?
(please don't post solutions to fix the error, I tried all of them)
I just want to disable the messages.
Here is the error message:
* Security Sandbox Violation * SecurityDomain
'http://agi.armorgames.com/assets/agi/AGI.swf' tried to access
incompatible context
'file:///D|/Flash/Projects/LastChapel/bin%2Ddebug/LastChapel.swf'
A: Have you tried to change flash global settings ? Right click on the animation and change trusted locations settings to add your URLs.
There is some info here : http://help.adobe.com/en_US/FlashPlayer/LSM/WS6aa5ec234ff3f285139dc56112e3786b68c-7ff0.html#WS6aa5ec234ff3f285139dc56112e3786b68c-7feb
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503007",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: addEventListener: How to access event I have two questions for the following example:
function doIt(){
this.attribute = someValue; // Works as expected
alert(event.which); // Doesn't work
}
element.addEventListener("click",doIt,false);
Question 1: Why is this bound to the function but event is not?
Question 2: What would be the appropriate way to do this?
A: this is a built-in for JavaScript. It is always accessible. event is not. It is only available if the current method supports it.
You would need to have something like
function doIt(event)
What is this? - http://howtonode.org/what-is-this
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How can you force validation of all fields of nested models, even if they have not changed? (Rails 3.1) When you edit a model with a form that contains nested model attributes, it seems as if the child objects are only validated if at least one field on the child object has changed.
However, suppose that your validation rules have changed, such that one or more of the nested models being edited are no longer considered valid. How can you force Rails to re-validate the all fields for all of the nested models?
UPDATE
Here's a total hack that works. I hope somebody knows a more elegant approach.
# parent.rb
has_many :children
# Manually force validation of all the children.
# This is lame because if you have multiple child associations, you'll have to
# keep updating this method.
def reset_validation
self.children.each{|child| child.valid? }
self.valid?
end
# parent_controller.rb
def update
@parent.reset_validation
if @parent.update_attributes(params[:parent])
redirect_to(root_path, :notice => 'Parent successfully updated.')
else
render :action => "edit"
end
end
A: The answer to this turned out to be rather simple. On the parent model, you simply explicitly declare that you want the associated children validated.
# parent.rb
validates_associated :children
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Smoothly move elements on UIScrollView I have UIScrollView where placed elements(elements placed from the top to down), how can I remove one row and smoothly move items up, without redrawing?
A: As for the removal of views, you need to use CATransition. UIView animations will not work when you remove, as this concept isn't animatable in the context of an animation. However, there the concept of a transition makes sense:
CATransition *transition = [CATransition animation];
transition.duration = 0.4;
[someView.layer addAnimation:transition forKey:kCATransition];
[someView removeFromSuperview];
Note that the order in which you make a change to a layer and when you add the animation to the layer doesn't matter, as long as it occurs within the same stack frame (i.e., as long as it happens before the next main run loop cycle).
As for shifting things around, use UIView animation methods:
[UIView animateWithDuration:0.4 animations:
^{
// Change the frames, bounds, etc. of any number of views here
}];
A: Well, an easy way to move UIViews (and subclasses) is using Core Animation.
An example, let's assume you want to move an UIImageView 10 pixels up, this is how I would do that:
[UIView beginAnimations:@"animation" context:nil];
[UIView setAnimationCurve:UIViewAnimationCurveLinear];
[UIView setAnimationDuration:1.0]; //In seconds
int newPosY = myImage.frame.origin.y - 10;
[myImage setFrame:CGRectMake(self.frame.origin.x, newPosY, myImage.frame.size.width, myImage.frame.size.height)];
[UIView commitAnimations];
EDIT: (Thanks to LucasTizma) Since Apple doesn't recommend this method you'd better use animateWithDuration:animations: or any of it's variants. Check this
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: WPF alpha threshold Is there any alpha threshold in WPF? I use brush #01000000 and on some computers it is non-transparent in regard to mouse hit testing (clicking on surface with this brush), but on some other computers it is considered as totaly transparent and mouse click-through. What is the case?
UPD1: @Alain Nope. The IsHitTestVisible property is independent of alpha click through. Here a body of the border is click throughable on all of computers:
<Window
x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" WindowStyle="None" AllowsTransparency="True" Background="Transparent">
<Border BorderBrush="Red" BorderThickness="20" Background="#00000000" IsHitTestVisible="True"/>
</Window>
And here it is not (but still click-throughable on some computers - that is the question):
<Window
x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" WindowStyle="None" AllowsTransparency="True" Background="Transparent">
<Border BorderBrush="Red" BorderThickness="20" Background="#01000000" IsHitTestVisible="True"/>
</Window>
IsHitTestVisible is True in both cases.
A: Interestingly, David Anson says in his blog here:
http://blogs.msdn.com/b/delay/archive/2011/08/18/invisible-pixels-are-just-as-clickable-as-real-pixels-tip-use-a-transparent-brush-to-make-quot-empty-quot-parts-of-a-xaml-element-respond-to-mouse-and-touch-input.aspx
That you can just set it to Transparent. I had always used #01000000 like the OP. One of the commonets on David's blog says Transparent didn't work for them. I wonder if this is related to the OP's problem of #0100000 working on some computers and not others. Perhaps there is some difference other than just running it on different computers?
A: You should be setting that explicitly using the IsHitTestVisible property.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use Google Analytics with jQuery form I've a form that sends the data to the server via jQuery.
Usually, with a thank you page, it's easy to track the submitted forms using Google Analytics but since there is no thank you page (because the data is sent asynchronously), how can I track those forms submitted ?
Thanks !
A: You should be able to use Google Analytics' trackPageview function in the function called upon form submission.
_gaq.push(['_trackPageview', '/choose/a/path']);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Does DeflateStream "skip" decompression if the data was not originally compressed? I'm not familiar with the internals of DeflateStream, but I need to store files in a Vendor's DB system that uses DeflateStream on binary attachments. The first thing I noticed was that all of my files were 10-50% BIGGER after compression, but I attribute that to a less sophisticated compression algo on top of files that are already highly compressed (in this case they were all PDFs). My question however relates to the fact that when I just wrote the original file into the BLOB the Vendor's application had no problem opening it (it opened the attachments I compressed with deflate as well). Is there a header on the compressed data that tells DeflateStream that the data's not compressed and basically pass it on as-is? This is the specification; can anyone familiar with it point where this is defined - or am I off base and the vendor is doing some magic behind the scenes?
A: no, there is no such magic in DeflateStream.
The built-in deflateStream exhibits a compression anomaly in which previously-compressed data actually increases in size. This has been reported to Microsoft previously, but they declined to fix the problem. it has to do with a naive implementation in DeflateStream of the DEFLATE protocol.
Ways that I know of to avoid the problem:
*
*use an alternative deflateStream that does not exhibit this problem. See DotNetZip for one example.
It includes a DeflateStream that just works.
*use the broken DeflateStream, compress the stream, compare sizes, and if the "compressed" stream is larger, then fallback to using the "uncompressed" stream.
If you choose the former case, you still have the condition where you are compressing stuff that has already been compressed. In other words, unnecessary double-compression. so you may want to look into avoiding that, regardless what you choose.
A: It all depends on how the DEFLATE stream was created.
DEFLATE supports a "non-compressed block" (BTYPE=00) and all data in this block, should it be utilized, is stored verbatim with no compression -- just the block header, length, and raw data. However, a stream can be a valid DEFLATE stream and contain zero (or not enough) "non-compressed" blocks even if this resulted in a sub-par compression ratio.
The overall compression ratio will depend upon the data, compressor algorithm/implementation, and amount of effort it puts into performing the compression.
Happy coding.
A: Stream compression is different from file compression. When compressing a file, it's generally possible to make multiple passes over the entire file and determine which compression scheme to use before having to commit to one. When compressing a stream, it's often necessary to start outputting data before the compression routine has processed enough data to know what compression method is going to be optimal.
This effect can be somewhat mitigated by dividing data into blocks, deciding for each block how to represent the data, and including a header at the start of each block identifying how it is stored. Unfortunately, the extra block headers will add to the size of the resulting stream. Further, many compression schemes improve in effectiveness as they process a stream; it may well be that every 1k block in a file would expand if "compressed" individually, even if compressing the whole file would result in a considerable space savings (since the compresser could e.g. build up a dictionary of common byte sequences). It would be possible to design a compress/uncompress pair so that a block of data which would expand would be written out verbatim by the compresser (with a header byte indicating that's what it was), and have the uncompresser process that block the same way the compresser could have done, so as to add to the dictionary the same byte sequences that would have been added had the block been stored in "compressed" form. Such an approach would probably be a good one, though it would add considerably to the complexity of the uncompresser.
I suspect the biggest problem for DeflateStream, though, is that there may not be any way to improve the worst-case "compression" performance without producing compressed data that is incompatible with the existing "uncompress" code. Suppose one has a string of bytes Q, and one needs a sequence of bytes which, when fed to the "uncompress" code that shipped with .net 2.0, will yield that same sequence. It may well be that for some possible values of Q, there are no such input sequences which aren't a lot bigger than Q. If that's the case, there's no way Microsoft could "fix" the problem without a time machine.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503021",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: AS3 Regex test for URL I want to check if a string contains a URL.
var string:String = "Arbitrary amount of random text before and after.<br/><br/>http://www.somdomain.co.uk<br/><br/>Tel: 0123 456 789<br/>";
var pattern:RegExp = new RegExp("(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:/~\+#]*[\w\-\@?^=%&/~\+#])?");
ExternalInterface.call('console.log',pattern.test(string));
This outputs false to my console, whereas when I feed the regex and string into http://gskinner.com/RegExr/, the url is found.
What am I doing wrong and how do I fix it?
A: I just escaped a couple extra / and it started working. Also, I generally like to use the regex literal notation to create regexes as it gives you better syntax highlighting than converting a string to a regex in the new Regex():
var pattern:RegExp = /(http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&:\/~\+#]*[\w\-\@?^=%&\/~\+#])?/;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android Facebook I have seen a few examples. But all allow the phone user to change the status that will be posted on their wall. Am I able to avoid this as my app will post a score and it will be pointless if the user can just put in any arbitrary number.
A: This is what you need to do.
*
*Create a facebook application with the name of your game.
*In the Android application ask use to authorize it posting to their wall
*Stream to the application text/image/caption and that would be posted on their wall without user interaction.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503029",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Defining my own max function with variable arguments I'm learning Clojure solving the problems listed on 4clojure. One of the exercises is to create your own max function with variable arguments.
I'm trying to solve this easy problem using the REPL and I got to this solution:
(defn my-max
[first & more] (calc-max first more))
(defn calc-max
[m x]
(cond (empty? x) m
(> (first x) m) (calc-max (first x) (rest x))
:else calc-max m (rest x)))
Which works fine but the exercise doesn't allow the use of def and therefore I must crunch both functions into one. When I replace the calc-max reference with its code the result is:
(defn my-max
[first & more]
((fn calc-max
[m x]
(cond (empty? x) m
(> (first x) m) (calc-max (first x) (rest x))
:else calc-max m (rest x)))
first more))
But this code doesn't work and returns the next error:
user=> (my-max 12 3 4 5 612 3)
java.lang.ClassCastException: java.lang.Integer cannot be cast to clojure.lang.IFn (NO_SOURCE_FILE:0)
I guess this error comes from trying to evaluate the result of the calc-max function and I guess it's a syntax error on my part, but I can't figure out how to resolve it.
A: Real error is that you called parameter first - it rebinds real first function to number! Just change name to something other, and your variant will work. Although it maybe better explicitly name function, instead of calling anonymous function, for example, you can declare calc-max as local function using letfn, for example. So your my-max will look like:
(defn my-max [ff & more]
(letfn [(calc-max [m x]
(cond (empty? x) m
(> (first x) m) (calc-max (first x)
(rest x))
:else (calc-max m (rest x))))]
(calc-max ff more)))
Although, I think, that you can write simpler code:
(defn my-max [& more] (reduce max more))
A: Your function doesn't work because first in fn treated as function and not as input value. So when you write
user=> (my-max 12 3 4 5 612 3)
it's talling that can't cast 12 to function. Simply, it can be rewrited as
(defn my-max1 [fst & more]
((fn calc-max [m x]
(cond (empty? x) m
(> (first x) m) (calc-max (first x) (rest x))
:else (calc-max m (rest x))))
fst more))
or even without fn
(defn my-max [x & xs]
(cond (empty? xs) x
(> (first xs) x) (recur (first xs) (rest xs))
:else (recur x (rest xs))))
A: Here is the function I used to solve it. The point is not to use max at all.
(fn [& args] (reduce (fn [x y] (if (> x y) x y) ) args ) )
A: To elaborate a little more on the exception that you are seeing: whenever Clojure throws something like
java.lang.Integer cannot be cast to clojure.lang.IFn
at you it means that it tried to call a function but the thing it tried to call was not a function but something else. This usually occurs when you have code like this
(smbl 1 2 3)
If smbl refers to a function, clojure will execute it with parameters 1 2 and 3. But if smbl doesn't refer to a function then you will see an error like the one above. This was my pointer in looking through your code and, as 4e6 pointed out, (first x) is the culprit here because you named your function argument first.
A: Not as good as the reduce but ok ba:
(fn [& args]
(loop [l args, maxno (first args)]
(if (empty? l)
maxno
(if (> maxno (first l) )
(recur (rest l) maxno)
(recur (rest l) (first l))))))
Can use cond I suppose
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Can we put a static image banner image at the top of every screen? Our customer decided their application did not have enough branding in it, and they want to put their logo in a banner at the top of every screen. The logo banner is about the same height as the navigation bar header, and can just be a static image.
Our app has many different screens, including many driven by a UINavigationController. We cannot put the logo into the "title" portion of the nav controller, because then we do not get to display the title for that view.
Looking at iOS apps, it's clear that this is not common. Has anyone had to do this before, and how did you accomplish it?
Thanks for any tips!
A: This is not an ideal approach, honestly, because as you mentioned, it isn't very common. Indeed, Apple might not accept apps that displace things such as the navigation bar.
In any case, if you must do this, you can add some sort of banner view directly to your window in the app delegate. After this, you must have sure to set the frame of the window's root view controller to be below the visible portion of the banner ad. From here, the rest of the views will be contained within the frame you specify, which is normally the size of the screen.
A: You can add the logo to your application's MainWindow and set transparency to all the viewControllers backgrounds. But note that this means that all your viewControllers will share the same background (the one from MainWindow).
A: You can do this - look at the XFactor UK app for an example ( http://itunes.apple.com/gb/app/the-x-factor-uk/id455682741?mt=8 ) - the navigation bar is branded throughout the app.
The bad news is it's pretty hard to do - we ended up applying a category to UINavigationBar to override drawRect and putting the background in there e.g.:
@implementation UINavigationBar (extras)
- (void)drawRect:(CGRect)rect {
UIImage *image;
if (self.frame.size.width>320) {
image = [UIImage imageNamed: @"NavigationBarWide.png"];
} else {
image = [UIImage imageNamed: @"NavigationBar.png"];
}
[image drawInRect:CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)];
}
A: You can keep the banner logo in AppDelegate file and set the frame for BannerLogo. This would be same as displaying ads with iAds or AdMobs. I have done this to display AdMob on all the screen. You need to add BannerLogo as a subView to display on all views.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503032",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: I need to carry forward the primary table's primary key to a foreign key field in dependent table I have 2 entities Customer and address please find the code below, I have omitted boiler plate code for simplicity.
public class Customer implements java.io.Serializable {
private static final long serialVersionUID = 3116894694769321104L;
private short customerId;
private Address address;
private String firstName;
private String lastName;
private String email;
private boolean active;
private Date createDate;
private Date lastUpdate;
// Property accessors
@Id
@Column(name="customer_id", unique=true, nullable=false, insertable=true, updatable=true)
public short getCustomerId() {
return this.customerId;
}
public void setCustomerId(short customerId) {
this.customerId = customerId;
}
@ManyToOne(cascade={CascadeType.ALL},
fetch=FetchType.LAZY)
@JoinColumn(name="address_id", unique=false, nullable=false, insertable=true, updatable=true)
public Address getAddress() {
return this.address;
}
public void setAddress(Address address) {
this.address = address;
}
and Address class is :
public class Address implements java.io.Serializable {
// Fields
private short addressId;
private short customerId;
private String address;
private String address2;
private String district;
private String postalCode;
private String phone;
private Date lastUpdate;
private Set<Customer> customers_1 = new HashSet<Customer>(0);
// Constructors
/** default constructor */
public Address() {
}
// Property accessors
@Id
@Column(name="address_id", unique=true, nullable=false, insertable=true, updatable=true)
public short getAddressId() {
return this.addressId;
}
public void setAddressId(short addressId) {
this.addressId = addressId;
}
/**
* ??????what goes here
*/
public short getCustomerId() {
return customerId;
}
/**
* @param customerId the customerId to set
*/
public void setCustomerId(short customerId) {
this.customerId = customerId;
}
I need to persist the customer id as a foreign key in address table.
A: Just use @ManyToOne relationship with Customer. So, instead of customerId in Java code you will be operates with Customer object, but at database level Hibernate will use foreign key to table with customer.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503035",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to search in not stricted HTML with java? I have a service that connects to remote site and searches for some elements in the HTML, the incomming data is abount 100-200kbytes but parsing it with strings is sooooooooo slow. I want some suggestions for fast framework... so any one???
A: 1) If you can afford about 1Mb memory usage to parse the html into DOM tree you can use tolerant html parsers (NekoHTML, for example).
2) Otherwise extract the data using regular expressions. This will be faster, less memory required. But you'll have to come up with some good expressions and you won't be able to extract some sophisticated structure information.
A: you can give a try to Tagsoup
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: problem running hello world with tornado web server (Python 2.5,Win 7) I am using Python 2.5 on Windows 7 (64bit).
I installed pycurl-7.15.5.1 (with win binaries) and tornado (using pip).
When I run the following hello world code:
import tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello World!")
if __name__=='__main__':
app = tornado.web.Application([(r"/",MainHandler),])
application.listen(8888)
tornado.ioloop.IOLoop.instance().start()
I get the following error:-
Traceback (most recent call last):
File "hello_tornado.py", line 11, in <module>
application.listen(8888)
File "c:\Python25\Lib\site-packages\tornado\web.py", line 1193, in listen
server.listen(port, address)
File "c:\Python25\Lib\site-packages\tornado\netutil.py", line 100, in listen
sockets = bind_sockets(port, address=address)
File "c:\Python25\Lib\site-packages\tornado\netutil.py", line 263, in bind_sockets
sock.setsockopt(socket.IPPROTO_IPV6, socket.IPV6_V6ONLY, 1)
AttributeError: 'module' object has no attribute 'IPV6_V6ONLY'
A: Tornado has some IPv6 confusion on windows apparently. You can fix it by specifiyig the IP you want it to listen on like this:
application.listen(8888,'127.0.0.1')
or maybe
application.listen(8888,'0.0.0.0')
A: from tornado web page (http://www.tornadoweb.org/)
Platforms: Tornado should run on any Unix-like platform, although for the best performance and scalability only Linux and BSD (including BSD derivatives like Mac OS X) are recommended.
I think it is not compatible with windows
Things similar with tornado can be achieve with twisted framework http://twistedmatrix.com which works under windows
interesting pointers are
http://twistedmatrix.com/documents/current/web/howto/web-in-60/index.html
and
http://twistedmatrix.com/documents/current/web/howto/web-in-60/dynamic-content.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: LINQ Case statement within Count Can you help me translate this sql into Linq please:
select
count(case when t.TypeID = 1 then t.TypeID end) as a,
count(case when t.TypeID = 2 then t.TypeID end) as b,
count(case when t.TypeID = 3 then t.TypeID end) as c
from myTable t
I've searched the internet and found some similar sql but nothing that fits this scenario. Is it possible?
Thanks
A: I think you want something like this
var query = new
{
a = (context.MyTable.Where(t => t.TypeID == 1).Count(),
b = (context.MyTable.Where(t => t.TypeID == 2).Count(),
c = (context.MyTable.Where(t => t.TypeID == 3).Count(),
}
Edit - If you want it all in one query you could do this:
var query = from x in context.MyTable
group x by 1 into xg
select new
{
a = xg.Where(t => t.TypeID == 1).Count(),
b = xg.Where(t => t.TypeID == 2).Count(),
c = xg.Where(t => t.TypeID == 3).Count(),
};
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503041",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to start two instances of the same app with different static values? Problem: I want to run my application with the different arguments, for example app.exe -param1 and a little bit later I need to start app.exe -param2. Parameters comes from arguments. Arguments I need to place to global static value, to be able to get it at any time from any where in code.
How to do that?
I have tried:
static QString gMyValues;
then from main.cpp I do something:
::gMyValues = QString( argv[ argc - 1 ] );
and then from any class I'm trying to get:
::gMyValues;
but no luck, gMyValues empty, but at the begging it was with arg value...
PS. Let it be only int's params.
Thanks!
A: My guess is you have more than one definition of the variable. Do you have this line in a header file?
static QString gMyValues;
If so, each and every source file that includes it will have its own copy of gMyValues. And only the one in main.cpp will be filled with correct value.
You should declare it in the header file like this:
extern QString gMyValues;
And define it in main.cpp:
QString gMyValues;
The static keyword in global level doesn't mean what you think it does. It means private linkage: http://thesmithfam.org/blog/2010/06/12/the-many-meanings-of-the-c-static-keyword/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Win Form Charting I may be asking the wrong question, but what I need is to add a "Guide Line" to my windows form chart. In other words I have a chart with a simple data series and I need to draw a line on the y axis at the passing score, or 80%. I don't want to add a second series as the first series has an undetermined number of data points. Is there a simple way to simply draw one line on the y axis?
The dashed line below is what I am shooting for(it does not need the arrows).
100|
|
90|
| o
80|<----------------------->
|
70| o o
|
60| o
| o o
50|o o
|_________________________
1 2 3 4 5 6 7 8 9
A: Apologies for repeating Don Kirkby's answer, but I don't have the rep to add a comment yet.
Using HorizontalLineAnnotation you can set the ClipToChartArea which will limit the extent of the line to within the chart, to solve the problem you mentioned.
ChartArea area = ...;
var line = new HorizontalLineAnnotation();
line.IsInfinitive = true; // make the line infinite
line.ClipToChartArea = area.Name;
line.LineDashStyle = ChartDashStyle.Dash;
Assuming your y-axis holds values on a scale of 0..1 then you can attach the line to the Y-Axis using line.AxisY = area.AxisY, which results in its position being interpreted as an axis value, then set line.Y = 0.8; to attach at the 80% position.
A: You can add a StripLine.
Use StripWidth property to set line position:
var series = chart1.Series[0]; //series object
var chartArea = chart1.ChartAreas[series.ChartArea];
chartArea.AxisY.StripLines.Add(new StripLine
{
BorderDashStyle = ChartDashStyle.Dash,
BorderColor = Color.DarkBlue,
StripWidth = 80//Here is your y value
});
UPDATE: Previous version of this answer used Interval instead of StripWidth. As @dthor correctly pointed out in the comments setting the Interval will draw a repeated strip line. In the example above, Interval is set to 0 by default.
A: I've never used charts, but HorizontalLineAnnotation sounds promising.
A: You can add dots to the frame with a loop that has for example 900 loop for 1 to 9 values. For each loop the compiler will calculate the value and left a dot for that perimeter and another for the next one so it will looks like a line of a equation :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Extract certain text from a string with regex I tried to extract a coded string from a string, for instance,
$string = 'Louise Bourgeois and Tracey Emin: Do Not Abandon Me [date]Until 31 August 2011[ /date ]';
$description = preg_replace('/\[(?: |\s)*([date]+)(?: |\s)*\](.*?)\[(?: |\s)*([\/date]+)(?: |\s)*\]/is', '',$string);
$date = preg_replace('/\[(?: |\s)*([date]+)(?: |\s)*\](.*?)\[(?: |\s)*([\/date]+)(?: |\s)*\]/is', '$3',$string);
echo $date;
result:
Louise Bourgeois and Tracey Emin: Do Not Abandon Me /date
intended result:
Until 31 August 2011
I got the $description right but I can't get the [date] right. Any ideas?
A: I think a rather simpler form would do:
#.*?\[\s*?date\s*?\](.*)\[\s*?/date\s*?\].*#
for instance?
A: ([date]+)
This is going to look for one-or-more sequences of letters containing d, a, t, and/or e. [] are regex metacharacters for character classes and will not treated as literal characters for matching purposes. You'd probably want:
(\[date\]) and (\[\/date\])
to properly match those opening/closing "tags".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503046",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Disable horizontal scroll with JavaScript Does anyone know if there is a way to disable the horizontal scrollbar using JavaScript?
I don't want to use overflow-x: hidden;.
A: A way to prevent elements from scrolling down in jQuery:
$(element).scroll(function () {
this.scrollTop = 0;
this.scrollLeft = 0;
});
Well, this does not actually prevent the scrolling, but it "scrolls back" to the top-left corner of an element, similar to Chris' solution which was created for the window instead of single elements. Remove the scrollTop or scrollLeft lines to suit your needs.
A: Without using the perfectly workable overflow-x CSS property, you could resize the content to not require a scroll bar, through javascript or through HTML/CSS design.
You could also do this:
window.onscroll = function () {
window.scrollTo(0,0);
}
... which will detect any scrolling and automatically return the scroll to the top/left. It bears mentioning that doing something like this is sure to frustrate your users.
You're best served by creating an environment where unwanted UI elements are not present at all (through the CSS, through design). The approach mentioned above shows unnecessary UI elements (scroll bars) and then causes them to not work in a way that the user expects (scroll the page). You've "broken a contract" with the user - how can they trust that the rest of your web site or application will do expected things when the user makes a familiar action?
A: A dirty trick would be overlapping the scrollbars: http://jsfiddle.net/dJqgf/.
var overlap = $('<div id=b>');
$("#a").wrap($('<div>'));
$("#a").parent().append(overlap);
with:
#a {
width: 100px;
height: 200px;
overflow-x: scroll;
}
#b {
position: relative;
left: 0;
bottom: 20px;
width: 100%;
height: 20px;
background-color: white;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: How to create list of nums on the start of the project I've have such code:
namespace _namespace
{
public enum Enums
{
Value1 = 1,
Value2 = 2,
Value13 = 3,
...
Valuen = n
}
}
All this datum are already in database. All what I need it's to create the list of enums on the start of the project.
P.S. It's web applicat
A: An Enum is not meant to be dynamic. This is not something that can/should be done in your application. You can create a Dictionary<int, string> to work with your database values.
A: You can use T4 to generate the enum from a lookup table
http://erraticdev.blogspot.com/2011/01/generate-enum-of-database-lookup-table.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: JQuery stop event bubbling from method call I am trying to get my head around the jquery plugin structure and wrote the following HTML code which forms the start of a slideshow:
<div id="bubble" style="width: 200px; height: 200px; background: #ccc;"></div>
<script type="text/javascript">
jQuery.noConflict();
(function($) {
$(function() {
$(document).ready(function() {
$("#bubble").bubble();
});
});
})(jQuery);
</script>
This is linked to the following jquery plugin code:
(function($){
var i = 0;
var methods = {
mouseup: function(e){
$(this).bubble('next');
e.stopPropagation();
},
mousedown: function(e){
$(this).bubble('next');
e.stopPropagation();
},
next: function(){
console.log(i++);
}
};
$.fn.bubble = function(method){
$(this).bind("mouseup", methods.mouseup)
.bind("mousedown", methods.mousedown);
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
}
};
})(jQuery);
I'm not sure why but clicking the bubble box calls multiple iterations of the next: method. Is there a way to limit the number of calls to the next: method?
A: You are binding mousedown and mouseup to the next function, this will send two next functions per click, I don't think you are meaning to do that.
In order to fix it, remove one of the binds, or just bind click.
A: Maybe you should use stopImmediatePropagation() so that you just log twice (because you call next() twice):
(function($){
var i = 0;
var methods = {
mouseup: function(e){
$(this).bubble('next');
e.stopImmediatePropagation();
},
mousedown: function(e){
$(this).bubble('next');
e.stopImmediatePropagation();
},
next: function(){
console.log(i++);
}
};
$.fn.bubble = function(method){
$(this).bind("mouseup", methods.mouseup)
.bind("mousedown", methods.mousedown);
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
}
};
})(jQuery);
fiddle: http://jsfiddle.net/k3FhM/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Is there a way to "set" Hadoop Counter instead of incrementing it? API only provides methods to increase a counter in Mapper or Reducer. Is there a way to just set it? or increment it's value only once irrespective of the number of times mappers and reducers are run.
A: What are you trying to achieve? This is inherently tricky, as what if multiple mappers try to set the counter? Who should win? The reason counters typically are only incremented is that this can be done very, very quickly and efficiently by the architecture.
A: You can't set the counter because the counters are summed from each of the tasks and aggregated into a top-level counter.
I have used ZooKeeper within MapReduce jobs for small communications or coordinations between tasks or flagging certain things that happened in a job or task.
A: This cannot be done from the Hadoop API at least as pointed out by @orangeoctupus as well.
The approach I used for achieve this was to set the value in Job's Context properties. In the end the properties can be read after the job is run. Non-elegant but a workaround!
A: The interface org.apache.hadoop.mapreduce.Counter defines a method setValue, but if it works globally like it seems to based upon the description, I would agree with other answers that there aren't many use cases for it that are also good ideas...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Import error ft2font from matplotlib (python, macosx) I was installing matplotlib to use basemap today when I had to install a lot of stuff to make it work. After installing matplotlib and be able to import it I installed basemap but I can't import basemap because of this error:
from mpl_toolkits.basemap import Basemap
Traceback (most recent call last):
File "", line 1, in
File "/usr/local/Cellar/python/2.7.2/lib/python2.7/site-packages/mpl_toolkits/basemap/init.py", line 36, in
from matplotlib.collections import LineCollection
File "/usr/local/Cellar/python/2.7.2/lib/python2.7/site-packages/matplotlib/collections.py", line 22, in
import matplotlib.backend_bases as backend_bases
File "/usr/local/Cellar/python/2.7.2/lib/python2.7/site-packages/matplotlib/backend_bases.py", line 38, in
import matplotlib.widgets as widgets
File "/usr/local/Cellar/python/2.7.2/lib/python2.7/site-packages/matplotlib/widgets.py", line 16, in
from lines import Line2D
File "/usr/local/Cellar/python/2.7.2/lib/python2.7/site-packages/matplotlib/lines.py", line 23, in
from matplotlib.font_manager import FontProperties
File "/usr/local/Cellar/python/2.7.2/lib/python2.7/site-packages/matplotlib/font_manager.py", line 52, in
from matplotlib import ft2font
ImportError: dlopen(/usr/local/Cellar/python/2.7.2/lib/python2.7/site-packages/matplotlib/ft2font.so, 2): Symbol not found: _FT_Attach_File
Referenced from: /usr/local/Cellar/python/2.7.2/lib/python2.7/site-packages/matplotlib/ft2font.so
Expected in: dynamic lookup
So when I tried to import ft2font in python by:
from matplotlib import ft2font
I got this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: dlopen(/usr/local/Cellar/python/2.7.2/lib/python2.7/site-packages/matplotlib/ft2font.so, 2): Symbol not found: _FT_Attach_File
Referenced from: /usr/local/Cellar/python/2.7.2/lib/python2.7/site-packages/matplotlib/ft2font.so
Expected in: dynamic lookup
Any idea what to do?
I'm using Mac OSX 10.6 and python 2.7.2 installed by homebrew.
A: I ran into the same issue. Even after running make.osx, it still complained about _FT_Attach_File being undefined when I imported ft2font from matplotlib. Here's how I tracked down the problem. Hopefully, it will help someone else.
Running otool -L ft2font.so yielded:
ft2font.so:
/Users/jbenuck/mpl_build/lib/libz.1.dylib (compatibility version 1.0.0, current version 1.2.5)
/usr/lib/libstdc++.6.dylib (compatibility version 7.0.0, current version 52.0.0)
/usr/lib/libSystem.B.dylib (compatibility version 1.0.0, current version 159.1.0)
Note the absence of any mention of libfreetype! How is ft2font.so supposed to locate the symbol if it isn't linked against it?
My next step was to capture the commands used during the build:
make -f make.osx PREFIX=/usr/local clean fetch deps mpl_build > output.txt
Searching this yielded the command that was used to compile the offending python module. I changed the value of the output file to be one in my local directory and ran it:
/Developer/usr/bin/llvm-g++-4.2 -bundle -undefined dynamic_lookup -isysroot / -L/opt/local/lib -arch i386 -arch x86_64 -L/usr/local/lib -syslibroot,/Developer/SDKs/MacOSX10.7.sdk -arch i386 -arch x86_64 -I/usr/local/include -I/usr/local/include/freetype2 -isysroot /Developer/SDKs/MacOSX10.7.sdk build/temp.macosx-10.7-x86_64-2.7/src/ft2font.o build/temp.macosx-10.7-x86_64-2.7/src/mplutils.o build/temp.macosx-10.7-x86_64-2.7/CXX/cxx_extensions.o build/temp.macosx-10.7-x86_64-2.7/CXX/cxxsupport.o build/temp.macosx-10.7-x86_64-2.7/CXX/IndirectPythonInterface.o build/temp.macosx-10.7-x86_64-2.7/CXX/cxxextensions.o -L/usr/local/lib -L/usr/local/lib -L/usr/lib -L/usr/X11/lib -lfreetype -lz -lstdc++ -lm -o ft2font.so
ld: warning: ignoring file /opt/local/lib/libfreetype.dylib, file was built for unsupported file format which is not the architecture being linked (x86_64)
Bingo! Problem found. I know I have both macports and homebrew installed. Apparently, one of them has a version of libfreetype in /opt/local/lib that isn't compiled for 64-bit.
I reran the command with "-L /opt/local/lib" removed which worked without a warning. Copying the resulting ft2font.so into my existing matplotlib installation now allows me to successfully import ft2font from matplotlib.
A: In my case, this was an architecture problem - I had a 64bit version of freetype installed (that matplotlib happily compiled against) but when I ran in a 32bit version of python I got that error. The easy solution is to uninstall everything (freetype, matplotlib), and then install both the 32 and 64bit versions using homebrew and the --universal flag:
brew install freetype --universal
Note, I also had to do this for libpng as well (brew install libpng --universal). Not all homebrew recipes support the universal flag, but it's a huge help for the ones that do. (You can see a formula's options with brew info <FORMULA>).
Also, compiling using the make.osx Makefile in conjunction with homebrew was a total failure; in my experience I'd recommend one or the other.
A: Okay, I figured it out.
I reinstalled matplotlib from source from github (https://github.com/matplotlib/) and then (instead of ordinary python setup.py install) I ran make.osx described in README.OSX:
make -f make.osx PREFIX=/devjunk PYVERSION=2.7 \
clean fetch deps mpl_install_std
And everything works properly now.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: iphone UIbutton with image click problem I have 3 UIbuttons in my with background image in my app...
for all those 3 buttons if images are assigned only lower half portion of button is clickable and upper half doesn't work at all..
any idea why ?
I tried to put color for buttons to check if they have right CGRect but it looks proper...
Here is some code
UIButton* segment=[[UIButton alloc] initWithFrame:CGRectMake(0+(i* segmentWidth) , 0,segmentWidth, 34)];
segment.backgroundColor = [UIColor redColor];
[segment addTarget:self action:@selector(segmentActionButton:) forControlEvents:UIControlEventTouchUpInside];
[segment setTag:i];
segment.titleLabel.font=[UIFont fontWithName:@"Arial" size:12.0];
segment.autoresizingMask=UIViewAutoresizingFlexibleWidth|UIViewAutoresizingFlexibleLeftMargin|UIViewAutoresizingFlexibleRightMargin;
[segment setTitle:[mItems objectAtIndex:i] forState:UIControlStateNormal];
[segment setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[segment setBackgroundImage:[UIImage imageNamed:SEGMENT_IMAGE_INACTIVE_MAP] forState:UIControlStateNormal];
[segment setBackgroundImage:[UIImage imageNamed:SEGMENT_IMAGE_ACTIVE_MAP] forState:UIControlStateHighlighted];
[self addSubview:segment];
[mButtonArray addObject:segment];
[segment release];
Hope it helps..
A: May be the error occurs because you are creating button in alloc+initWithFrame way. I'm not sure but try to create button in such way:
UIButton* segment = [UIButton buttonWithType:UIButtonTypeCustom];
segment.frame = CGRectMake(0+(i* segmentWidth) , 0,segmentWidth, 34);
And remove line [segment release]; as you will create autoreleased object.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Excel Filter with Macro I want to write one macro it should work like Excel filter. After getting all the data using this filter I want to paste in to the new worksheet.
A: This sub filter zero values in sheet1 and copy to sheet2 range A1
Sub FilterAndCopy()
'Developer by Bruno Leite
'http://officevb.com
Dim Sht As Worksheet
Dim FilterRange As Range
'Set your Sheet
Set Sht = ThisWorkbook.Sheets("Sheet1")
'Verify if is Filter
If Sht.FilterMode Then
Sht.ShowAllData
End If
'Filter Column A with 0 at parameter
Sht.Range("A:A").AutoFilter Field:=1, Criteria1:="0"
'Define Range Of Visible cells without row title
Set FilterRange = Sht.Range("A1").CurrentRegion.Offset(1, 0).SpecialCells(xlCellTypeVisible)
FilterRange.Copy Sheets("Sheet2").Range("A1")
Sht.ShowAllData
End Sub
[]´s
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Offline Web Application HTML5 on Android I want to develop a HTML5 Web App.
I read that in HTML5, you can use the new feature "Offline Web Applications"
With the *.manifest file
I read an article from november 2010, that this feature only works on the iOS platform.
Does it work on Android now?
A: Yes. It works on Android as well as iOS and most desktop browsers. You don't need PhoneGap unless you want to access native features or deploy to the App store.
UPDATE:
Check out this chapter from Jonathan Stark's book: Building Android Apps with HTML, CSS, and JavaScript.
A: In general, http://mobilehtml5.org/ provides nice mobile compatibility tables to answer this and other similar questions.
A: Yes it can. Here's an example for an offline game:
http://www.davidgranado.com/2010/11/make-a-set-mobile/
The one thing that sucks is that iOS generates a nice icon automatically. However, android doesn't. Also, I noticed that on random versions of android, it will display an error popup about the fact that it can't connect to the internet, but still runs fine after that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503080",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: HTML and CSS , position absolute question Is it good and desirable to put all the web site content in a div with the following styling?
<div style="position:absolute; top:0; left:0; width:100%;">
ALL site content come here
</div>
My problem is that i want to put in some places in the site divs that the width will be
100% without the spaces in the sides , so if i put all the site content in one absolutely div
and put a normal div with 100% width it will be from side to side without the spaces in the sides
example :
<div style="width:100%;background-color:yellow;"></div>
so , is that good to do that? and if it get some difficulties on the way?
A: I think what you are suggesting is safe, but you may accomplish what you want by adding style="margin:0" to your <body>. Or if you have a .css file, you can just add body{margin:0} to it. It would be simpler I think, but then, I am not sure whether I understand your question correctly.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503087",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: oracle - getting 1 or 0 records based on the number of occurrences of a non-unique field I have a table MYTABLE
N_REC | MYFIELD |
1 | foo |
2 | foo |
3 | bar |
where N_REC is the primary key and MYFIELD is a non-unique field.
I need to query this table on MYFIELD and extract the associated N_REC, but only if there is only one occurrence of MYFIELD; otherwise I need no records returned.
So if I go with MYFIELD='bar' I will get 3, if I go with MYFIELD='foo' I will get no records.
I went with the following query
select * from
(
select
n_rec,
( select count(*) from mytable where mycolumn=my.mycolumn ) as counter
from mytable my where mycolumn=?
)
where counter=1
While it gives me the desired result I feel like I'm running the same query twice.
Are there better ways to achieve what I'm doing?
A: I think that this should do what you want:
SELECT
my_field,
MAX(n_rec)
FROM
My_Table
GROUP BY
my_field
HAVING
COUNT(*) = 1
A: You might also try the analytic or windowing version of count(*) and compare plans to the other options:
select n_rec, my_field
from (select n_rec, my_field
, count(*) over (partition by my_field) as Counter
from myTable
where my_field = ?)
where Counter = 1
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Change Select value using jQuery Uniform.js I'm using uniform.js for jQuery and I need to change the values of the select item programmatically. It seems to change the actual <select> field, but the uniform element doesn't change. What is the proper way to do this, other than manually looking up the HTML for the option, then setting the uniform element to that value?
A: After setting the value as usual,
you need to tell uniform to update the element.
$.uniform.update("#myUpdatedSelect");
or as the documentation says, if you are lazy you can let it update ALL elements
$.uniform.update();
A: Try to use the update command in the complete function:
$('.selectbox').load('index.php?get=newoptions', function() {
$.uniform.update('selectbox');
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: Vim snipMate tab jump Vim snipMate doesn't work correctly
finf[Tab] generate
find(:first<+, :conditions => ['<+<+field+> = ?+>', <+true+>]+>)
but cursor set to end of the line and dont jump by placeholders with [Tab]
Update:
I try it with html - all works fine, maybe this doesn't work in *.rb files with Rails snipmates
A: I think there's something wrong with your snippet. I use snipMate for Python and all the placeholders looks like ${Number[:description]}. Take a look at ~/.vim/snippets/ for examples. Belows there is a simple example for a if statement in ruby :
snippet if
if ${1:condition}
${2}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: OpenCV hello world not compiling like it should I am setting up a new machine with OpenCV 2.3.1. The machine is a Windows 7 box, and I followed the installation instructions given by the OpenCV website (used CMake with MinGW to build).
Here is my code:
#include <iostream>
#include <opencv2/core/core.hpp>
#include <opencv2/highgui/highgui.hpp>
int main() {
char var;
cv::Mat img;
img = cv::imread("C:/test/img.jpg");
cv::namedWindow("Image");
cv::imshow("Image", img);
std::cin >> var;
return 1;
}
Here is my make command:
g++ -o main main.cpp -lopencv_core -lopencv_imgproc -lopencv_calib3d -lopencv_video -lopencv_features2d -lopencv_ml -lopencv_highgui -lopencv_objdetect -lopencv_contrib -lopencv_legacy
Here is my path:
C:\OpenCV-2.3.1\install\bin;C:\OpenCV-2.3.1\install\include;C:\QtSDK\QtCreator\bin;C:\Program Files (x86)\MiKTeX 2.9\miktex\bin;%SystemRoot%\system32;%SystemRoot%;%SystemRoot%\System32\Wbem;%SYSTEMROOT%\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\CMake 2.8\bin;C:\QtSDK\mingw\bin;
Here is my error:
main.cpp:2:33: error: opencv2/core/core.hpp: No such file or directory
main.cpp:3:39: error: opencv2/highgui/highgui.hpp: No such file or directory
main.cpp: In function 'int main()':
main.cpp:8: error: 'cv' has not been declared
main.cpp:8: error: expected ';' before 'img'
main.cpp:9: error: 'img' was not declared in this scope
main.cpp:9: error: 'cv' has not been declared
main.cpp:10: error: 'cv' has not been declared
main.cpp:11: error: 'cv' has not been declared
This is not making sense. Why won't this compile? Why can't it find opencv2/core/core.hpp?
A: g++ doesn't consider %PATH% ($PATH on Unix) when looking for include files.
Add the following to the compilation command: -IC:\OpenCV-2.3.1\install\include:
g++ -IC:\OpenCV-2.3.1\install\include -o main main.cpp -lopencv_core ...
A: You are not including the right OpenCV directories.
I made an installation of a previous version of OpenCV in C:\OpenCV2.3, and these are the paths I had to add for my compiler to find the headers:
C:\OpenCV2.3\build\include\opencv
C:\OpenCV2.3\build\include\opencv2
C:\OpenCV2.3\build\include
Traditionally, g++ takes headers directories with the -I flag, which you doesn't seem to be using at all.
A: on unix like os
g++ filename.cpp -o exec `pkg-config opencv cvblob --libs --cflags`
(cvblob optional if you are checking for blob)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Iframe with facebook friends list inside it Is there anyway with the Facebook C# API to create an iframe on my website which displays the friends of a facebook user (whos already logged in) using this API?
http://facebooksdk.codeplex.com/wikipage?title=Getting%20Started%20with%20an%20ASP.NET%20MVC%203%20Website
I'm confused as to whether I need to create a facebook app on facebook first to do this or whether I can just pull it directly using the API.
A: You will have to create Facebook application and then use that in your website together Facebook C# SDK.
Whenever new FB users visit to your website FB app will ask for necessary permission (in your case access to friends list), if FB user allows access to his friends list then you can read his friends list and display in your web site.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Is there a plugin like "mvn search"? I want to use VIM for Java programing, but I found it is very cumbersome to find and set a Maven dependence at command line.
Is there a plugin to search dependence like "apt-cache search"? and adding a dependence to pom.xml like "apt-get install"?
This should be a basic function, Why there is no such plugin ? Thank you :)
A: There is no plugin, and I can't answer why.
However in the IDE I use (IntelliJ) and probably others, there are help pop-ups that ask you if you want to add a dependency to a POM automatically (most likely only for things in your local repository). Also, when editing a POM, anything already in your local repository will autocomplete as you type out the dependency (and if there are multiple versions, the list of versions to choose from is displayed). Just letting you know in case switching to an IDE would help you.
I think the best you can do for search is use a browser off to the side with MVNRepository loaded up. You can search for libraries and when you see the one you want, you can copy-paste the example dependency into your POM. Note a small fraction of dependencies listed there are not in the most common public repositories and require you to customize your repository list.
A: maven dependency plugin could help you a little bit on listing/analyzing dependencies. But it cannot add a dependency for you.
in fact, if you prefer VI to edit files, why not just open pom.xml in your vim, and edit the file directly?
A: If you prefer working with Vim, you can still do it in Eclipse: try Vrapper on the free side. On the non-free side, you can try Viable or viPlugin.
Eclipse then has Sonatype's m2e plugin, which lets you add dependencies and plugins with a sleek search wizard (not to say a whole bunch of other helping features).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: SiteMinder SSO Custom Login page Has anyone got a bare bones custom login page, that will post to the default login.fcc. I'm unsure where to start with this. Presumably it would have javascript code to take a part the query string and then pass it on to the login.fcc
A: Custom login pages are simple- all you have to do is post with the correct variables to the FCC. This snippet is from login.fcc, so in this case the web agent fills in the $$ variables automatically, and then posts to itself. If you are going submit the variables from another source (non fcc) then you will have to make sure to include the agent name, username, password, and target in your post.
<form action="login.fcc" method="post">
<div class="formRow">
<table>
<tr>
<td><P><span>Username :</span></P></td>
<td><P><input name="username" type="text" value=""
style="width:150px" /></P></td>
</tr>
<tr>
<td><P><span>Password :</span></P></td>
<td><P><input name="password" type="password" value=""
style="width:150px" /></P></td>
</tr>
</table>
</div>
<INPUT TYPE=HIDDEN NAME="SMENC" VALUE="ISO-8859-1">
<INPUT type=HIDDEN name="SMLOCALE" value="US-EN">
<INPUT type=HIDDEN name="SMRETRIES" value="1">
<input type=hidden name=target value="$$target$$">
<input type=hidden name=smquerydata value="$$smquerydata$$">
<input type=hidden name=smauthreason value="$$smauthreason$$">
<input type=hidden name=smagentname value="$$smagentname$$">
<input type=hidden name=postpreservationdata value="$$postpreservationdata$$">
<div class="formRow">
<P><input name="submit" type="submit" value="Login" />
<input name="Reset" type="reset" /></P>
</div>
</form>
A: Based on whether the secureurls feature is enabled or not the paramater that is required to be passed/posted to login.fcc would change.
Here is the summary of the data that is required to be posted to Login.fcc
When SecureURLs=No
The post form data contains following :
Required:
target
smagentname
Optional:
smenc
smlocale
smquerydata
postpreservationdata
smauthreason
Post URL : /siteminderagent/forms/login.fcc
When SecureURLs=YES
The post form data contains following :
Required:
smquerydata
Optional:
smenc
smlocale
target
smauthreason
postpreservationdata
smagentname
Post URL : /siteminderagent/forms/login.fcc?SMQUERYDATA=******
Please refer : https://iamtechtips.com/custom-login-page/
A:
<html>
<body>
<form action="/verify.fcc" method="post">
<div class="formRow">
<table>
<tr>
<td><P><span>Username :</span></P></td>
<td><P><input name="USER" type="text" value="" style="width:150px" /></P></td>
</tr>
<tr>
<td><P><span>Password :</span></P></td>
<td><P><input name="PASSWORD" type="password" value="" style="width:150px" /></P></td>
</tr>
</table>
</div>
<INPUT TYPE=HIDDEN NAME="SMENC" VALUE="ISO-8859-1">
<INPUT type=HIDDEN name="SMLOCALE" value="US-EN">
<INPUT type=HIDDEN name="SMRETRIES" value="1">
<input type=hidden name=target value="/protected.html">
<div class="formRow">
<P>
<input name="submit" type="submit" value="Login" />
<input name="Reset" type="reset" />
</P>
</div>
</form>
</body>
</html>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: cannont find lGL Question: why can't it find -lGL?
Info: I wrote a program as guided by this site on my netbook this morning and it compiled and ran with no problem. I then proceeded to take the exact same code and try to run it on my desktop. the version my netbook compiled worked, but it yelled at me because my netbook doesn't have a graphics card and my desktop does so it wasn't quite compiled right. still ran though.
But when I tried to compile it on my desktop it failed. at first it was saying "Fatal error: GL/gl.h: no such file or directory" so i thought "wait, i thought opengl came with ubuntu, I mean my netbook worked, maybe I installed something and forgot about it" so i ran through apt and pulled down everything opengl I felt might help. but staring at 212 - 1278 packages (depending on what words i search with) that may or may not be opengl related, I don't know what else to try. I got past the first problem, but now it is complaining that it can't find -lGL, which seems really odd.
any tips, tricks, comments, quips? My end objective is to be able to compile c code from the command line, I've been using the command that I got from the afore mentioned site:
gcc -o gltest gltest.c -lX11 -lGL -lGLU
I run Ubuntu 11.04 desktop, 64-bit. Nvidia GTX465.
A: try to install the following packages:
apt-get install libgl1-mesa-dev libglu1-mesa-dev libglut3-dev
A: Your compiler was looking for a lib called libGL.so in /usr/lib, which was a symbolic link to /usr/lib/mesa/libGL.so, Mesa's libGL. You also have the libGL from your nVidia drivers (which are probably in 275.28 version, see the libGL name : libGL.so.275.28). Modifying the symlink to point to nVidia's one gives your compiler no longer the Mesa's one, but the nVidia's one.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503104",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Configuring ELMAH Filtering Declaratively I would like to filter the ELMAH results declaratively in my web.config. I'm not getting it to successfully filter out some of the exceptions I would like. HttpStatusCode is succesfully filtering, but I'm still getting ViewStateExceptions through. There are lots of posts about how to configure it, however I'm not sure how to put several filters into the configuration section and documentation seems to be a little thin on this point. Currently I have the below configuration in my web.config. I wondering, can someone point out:
*
*If I have things defined correctly to filter out ViewStateExceptions and
*How exactly to define the node structure to process all the filters correctly.
<errorFilter>
<test>
<equal binding="HttpStatusCode" value="404" type="Int32" />
<test>
<test>
<and>
<is-type binding="Exception" type="System.Web.HttpException" />
<regex binding='Exception.Message' pattern='invalid\s+viewstate' caseSensitive='false' />
</and>
</test>
<test>
<and>
<is-type binding="Exception" type="System.Web.UI.ViewStateException" />
<regex binding='Exception.Message' pattern='invalid\s+viewstate' caseSensitive='false' />
</and>
</test>
</errorFilter>
A: In your last test try binding to BaseException, not Exception.
Re your structure try something like:
<test>
<or>
<regex binding="BaseException.Message" pattern="Request timed out."/>
<and>
<equal binding="Context.Request.ServerVariables['REMOTE_ADDR']" value="::1" type="String"/>
<regex binding="Exception" pattern="hello"/>
</and>
<regex binding="BaseException.Message" pattern="The remote host closed the connection."/>
</or>
</test>
Should work. Wrap all the tests in an <or>, then any tests that must both be true, wrap in an <and>.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503109",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Preserving JSF messages after a redirect I have a JSF page (using MyFaces 2.0) that does a bit of data gathering the first time it is displayed. If it can't find some information, it is supposed to provide a message to that effect and redirect back to a different page. I've tried using the solution found here Preserving FacesMessage after redirect for presentation through <h:message> in JSF (setKeepMessages(true)) but the messages aren't displaying after the redirect. The only difference I can pick out is that I'm not using a navigation rule, I'm calling the redirect() call on the external context because this isn't occurring in a normal action.
Relevant code:
public void redirectToPageWithMessage(String inPage, String message, FacesMessage.Severity severity){
getFlash().setKeepMessages(true);
addMessage(message, severity);
try {
getFacesContext().getExternalContext().redirect(inPage);
} catch (IOException e) {
e.printStackTrace();
}
}
Unfortunately this doesn't seem to be working. The redirect happens just fine, but the < messages /> tag isn't displaying the message. Is there something different about the way redirect() happens that prevents this from working?
A: The code that saves the messages are executed after the phase ends (see Flash.doPostPhaseActions(FacesContext) ). So, it is expected it does not work, but maybe you can call Flash.doPostPhaseActions before the redirect. Note is not a "clean" solution, but it is possible.
A: I had the same problem and solve it not using ExternalContext.redirect() but to play with outcome for your actions.
That is to say, my action called by my buttons return a String (the outcome) which indicates the navigation rules to go to the next page. With that system, the messages are preserved.
A: JSFMessages are kept only for the processing of the actual request. A second request is made when using redirect, so the JSFMessages will be lost. The EL-Flash is a way to work around this. This example should work: http://ocpsoft.com/java/persist-and-pass-facesmessages-over-page-redirects/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: logic of color variance http://dribbble.com/colors/1a15a1?percent=5&variance=50
I understand the color minimum slider--you would count the color of each pixel, then create a ratio for a particular color based on the total pixels of the image (10 blue:100 total) = 10% blue.
But what's the logic behind the color variance slider? Looking at the RGB values of these colors http://en.wikipedia.org/wiki/Web_colors#X11_color_names some patterns are apparent, but imagining a sql table full of pictures and their pixel data, anyone have an idea on how to calculate variance?
A: I too think you are right for the color minimum. Color variance is easy too. If you select a small variance you will get images with a small count of colors used on it. Logically 0% variance must bring an image of a single color only.
I don't think you have to store pixels at all, logically for storing a new image it goes like this:
*
*Read image file
*Find how many different color there are in it
*Store image path and number of different colors on it.
Then on retriving the image would go like this:
*
*Ask the user what variance he likes
*Let's say variance = 60%
*Read distinct maximum numbers of colors for an image
*MaxColors = 100% (let's say max=18 colors per image)
*Turn 60% to integer
18 = 100%
x = 60% then
18*60=100*x then 100*x=1080 then x=10.8
*Make 10.8 round so it becomes x=11
*Retrieve from database all images that have 11 or more colors on them
*Display these images as the result
So no need to store any pixel at all, just a single integer that indicates how many colors consist of an image.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: CSS image pop up I have a html page with 12 thumbnails (spliced Photoshop) within a table (Table_01) within a div and when you hover over one of the thumbs a new image pops up.
At the moment when you hover over the "Ice white" thumb (this is the one I'm testing with at the moment) the new image pops up at the top of the page.
This is no good. It needs to pop up exactly to the right of the div which Table_01 is contained in (preferably top of pop up image flush with top of div and left side of pop up image touching right side of div if that makes sense). CSS is within head of source code near the end. It's not the best written webpage and is very messily coded but this bit should be easy to weed out and identify a solution hopefully. Any help greatly appreciated.
A: Late response obviously but I hope, it will help you out anyways.
As far as your comments above, those popping out new images needs to have absolute position with some right and top positions fixes. For example, considering that you are having a 3 divs in a row, each div is having an image, you should mention the parent div (containing the image) to have relative position; inside it the image (actually the popup image or thumb) should have position absolute and then it should have right and top adjustments in CSS as per your requirement.
I hope it will help you out...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Different keyboard layouts in Android I just took a look on different devices and their soft keyboards. They are all looking a bit different. I attach two screenshots. One is from my HTC Desire (Android 2.2), another one from Emulator (Android 2.3).
As you can see on the device the enter key is on device just a symbol, on emulator it is "send".
Can I change it somehow?
A: I had this problem a year ago, my problem was that the numeric keypad is very different from each provider (not only on style but on the buttons that are shown)
In my personal experience is a pain to try to change that, you would need to create your own SoftKeyboard class with your own images.
If it's not an important issue I recommend to just pass over it, or find a keyboard type that satisfies your needs.
However, I don't know if in the newest versions of Android you get an easier way to customize keyboards.
Good luck on there :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to configure a Swing JFrame as a Spring bean? I have a simple JFrame as the main window of my Java desktop application and I would like to configure it as a Spring bean. I would like to set properties, inject dependencies and launch it. Here's my frame class:
public class MainFrame extends JFrame {
public MainFrame() {
setTitle("Static Title");
setVisible(true);
}
}
My Spring application context:
<bean class="com.example.MainFrame">
<property name="title" value="Injected Title" />
</bean>
Then I fire it all up...
public static void main(String ... args) {
new ClassPathXmlApplicationContext("applicationContext.xml");
}
...which is followed by this java.beans.IntrospectionException:
type mismatch between indexed and non-indexed methods: location
The frame is actually displayed but there's that exception and the title remains "Static Title". So I have a few questions...
I've seen this being done by IBM in a 2005 tutorial but with Spring 1.2, and I don't even know what JRE. So how do I approach this exception? Is it possible to configure a JFrame as a Spring bean or do I need to proxy it or something?
I'm also wary of not launching the application from the event dispatching thread. So if there's a cleaner way of doing this I'd like to know about it. I can easily dispatch everything except that I don't know how to dispatch the construction itself.
Finally feel free to criticise the overall concept. I haven't come across many examples of Spring managed Swing applications. I'm using Spring-3.1 with Java-1.6.
Thanks.
A: I'm having the same problem, and it seems that's actually a bug on Spring:
https://jira.springsource.org/browse/SPR-8491
I think I'll wrap a FactoryBean around the panel and see if it works. I'll edit this post later, in case it works (or not)
-- edit --
Okay, instantiating it through a FactoryBean does get around the problem. The declaration becomes a little awkward, but that will have to do, at least until the aforementioned bug is fixed.
package com.ats.jnfe.swing;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.text.MessageFormat;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.BeanInstantiationException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.FactoryBean;
/**
* Contorna, em caráter temporário, o bug apontado em:
* https://jira.springsource.org/browse/SPR-8491
* Quando o erro acima for resolvido, esta classe estará obsoleta.
*
* @author HaroldoOliveira
*/
public class SwingFactoryBean<T> implements FactoryBean<T> {
private Class<T> beanClass;
private Map<String, Object> injection;
private String initMethod;
private Map<String, PropertyDescriptor> properties;
private BeanInfo beanInfo;
private Method initMethodRef;
public T getObject() throws Exception {
T t = this.getBeanClass().newInstance();
if (this.getInjection() != null) {
for (Map.Entry<String, Object> en : this.getInjection().entrySet()) {
try {
this.properties.get(en.getKey()).getWriteMethod()
.invoke(t, en.getValue());
} catch (Exception e) {
throw new BeanInitializationException(MessageFormat.format(
"Error initializing property {0} of class {1}",
en.getKey(), this.getBeanClass().getName()), e);
}
}
}
if (this.initMethodRef != null) {
this.initMethodRef.invoke(t);
}
return t;
}
public Class<?> getObjectType() {
return this.getBeanClass();
}
public boolean isSingleton() {
return false;
}
public void initialize() {
try {
this.beanInfo = Introspector.getBeanInfo(this.getBeanClass());
this.properties = new HashMap<String, PropertyDescriptor>();
PropertyDescriptor[] descriptors = this.beanInfo.getPropertyDescriptors();
for (PropertyDescriptor pd : descriptors) {
this.properties.put(pd.getName(), pd);
}
if (this.getInitMethod() != null) {
this.initMethodRef = this.getBeanClass()
.getMethod(this.getInitMethod());
}
} catch (Exception e) {
throw new BeanInitializationException(
"Error initializing SwingFactoryBean: " + e.getMessage(), e);
}
}
public Class<T> getBeanClass() {
if (this.beanClass == null) {
throw new BeanInitializationException("Class not informed.");
}
return this.beanClass;
}
public void setBeanClass(Class<T> beanClass) {
this.beanClass = beanClass;
}
public Map<String, Object> getInjection() {
return injection;
}
public void setInjection(Map<String, Object> injection) {
this.injection = injection;
}
public String getInitMethod() {
return initMethod;
}
public void setInitMethod(String initMethod) {
this.initMethod = initMethod;
}
}
Usage example:
<bean id="certificadoNFeConfiguracaoDialog" class="com.ats.jnfe.swing.SwingFactoryBean" init-method="initialize" scope="prototype" lazy-init="true">
<property name="beanClass" value="com.ats.ecf.view.swing.util.dialog.OKCancelDialog" />
<property name="initMethod" value="inicializa" />
<property name="injection">
<map>
<entry key="selector">
<bean class="com.ats.jnfe.swing.SwingFactoryBean" init-method="initialize">
<property name="beanClass" value="com.ats.jnfe.swing.CertificadoNFeConfigPanel" />
<property name="initMethod" value="inicializa" />
<property name="injection">
<map>
<entry key="fachada" value-ref="certificadoNFeConfiguracaoFacade" />
</map>
</property>
</bean>
</entry>
</map>
</property>
</bean>
A: Runs with Spring 3.0.7.RELEASE, 3.1.4.RELEASE und 3.2.3.RELEASE.
It seems it has been a bug as mentioned in another answer.
A: My thought would be to keep Swing out of Spring. Past anything trivial, wiring up a GUI using something else is going to be too tedious. Instead, I would change what you are doing and just use main() to create the Spring content and then create your GUI.
If all you are doing in Spring would be creating the MainFrame and starting it, maybe the easiest thing is to create a FactoryBean that creates the frame. The factory could also call setVisible() via a SwingUtilities.invokeLater() call.
A: Confirmed runs with Spring 4.0.2.RELEASE too.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503123",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Windows Forms graphics blink I have a Windows Forms application, borderstyle=none, own background image, when i start application window show partly and fill when every control will paint, how to do that form will showed when all controls will be painted?
Thanks!
A: Call the Invalidate method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503124",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: Relative path or url for html src and href attributes Using a framework makes it easy to list full url's for my html src and href attributes, and I feel I'm being more thorough by listing a full url instead of a relative path. But is this faster? Am I incurring an extra DNS lookup? What is the best practice when the content is on the same server?
<img src='http://site.com/images/img1.png' />
vs
<img src='/images/img1.png' />
Codeigniter's image helper img() works like this from the users' guide:
echo img('images/picture.jpg');
// gives <img src="http://site.com/images/picture.jpg" />
and Codeigniter's anchor helper anchor() works like this from the users guide:
echo anchor('news/local/123','My News');
// gives <a href="http://example.com/index.php/news/local/123" >My News</a>
A: As far as DNS goes, it really doesn't matter if you have relative or absolute URL. Your browser ends up pre-pending the server URI onto the front anyway. Also, your network stack does the lookup for the first time, and caches the IP. Unless something goes wrong, there should only be the one lookup per page. YMMV of course, but that should be how this all works.
A: 'Never' (alsmost never) use absolute paths.
It will bite you in the ass later.
For example when you switch / add another domain.
Go from your test to production server.
Basically the rule is internal URL's should be relative.
A: Oh you really don't want to use a full path. You'll have a lot of work ahead of you:
*
*If you want to develop the site locally
*You change / add domains (development, staging, etc)
*You switch to using a CDN
You also will break your dev environment, since most modern ones will perform local directory lookups. Can't do that with a domain.
Also, in a dev environment you will be pulling from the production site, which will make modifying and adding images extremely tricky.
Most importantly, other developers working with your code will try to kill you. And that's bad for your health.
A: Portability would be the issue for me. I would choose the second option based on that alone.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: problems passing an object i know c passes by reference and im sure thats where my problem lies, but for the life of me i cannot figure this out. (also there may be a framework or a more proper way of doing this, which im open to suggestions)
CrestronControllerValues is just a getter and setter class
i intialize and pass it in my app delegate:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray *keys = [NSArray arrayWithObjects:@"IPaddress", @"PortNumber", nil];
NSArray *objs = [NSArray arrayWithObjects:@"10.8.30.111", @"41794", nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:objs forKeys:keys];
[defaults registerDefaults:dict];
CrestronControllerValues *CCV = [[[CrestronControllerValues alloc]init]autorelease];
[CCV setIPID:3];
[CCV setIPaddress:[defaults stringForKey:@"IPaddress"]];
[CCV setPortNumber:[defaults stringForKey:@"PortNumber"]];
cClient = [[CrestronClient alloc] initWithCCV:CCV];
as you can see the last line passes it to another class
this is where my problem comes into play
if i try to use getipaddress or getportnumber i get bad access
- (id)initWithCCV:(CrestronControllerValues *)ccv
{
[super init];
CCV = [CrestronControllerValues alloc];
CCV = ccv;
port = [[ccv getPortNumber] intValue];
ip = [ccv getIPaddress];
NSLog(@"ip %@ ~ port %@", ip, port);
return self;
}
i have tried multiple ways, including
cClient.ccv = ccv (as opposed to sending it with the init)
tried adding a getter for self so that it would be cClient = [[CrestronClient alloc] initWithCCV:[CCV getSelf]];
A: Considering CCV in your last snippet of code is an ivar, try this instead:
CCV = [ccv retain];
You don't need to allocate space for an existing object. Also, be careful with your init method pattern, you may want to take a look in the documentation.
A: The correct way to store objects in NSUserdefaults is [defaults synchronize]. You're getting bad access because the objects you get from defaults are nil.
Check NSUserDefaults Class Reference
A: Have IPaddress and PortNumber been synthesized? If you want to access those variables from another class, you'll need to make sure that in CrestronControllerValues.h, you declare the @property for each object and in your CrestronControllerValues.m, you @synthesize IPaddress, PortNumber unless you're otherwise explicitly declaring your getter and setter methods.
A: here is the resulting code that works:
- (id)initWithCCV:(CrestronControllerValues *)ccv
{
self = [super init];
if (self)
{
socket = [[LXSocket alloc] init];
[DDLog addLogger:[DDASLLogger sharedInstance]];
[DDLog addLogger:[DDTTYLogger sharedInstance]];
sqliteLogger = [[FMDBLogger alloc] initWithLogDirectory:[self applicationFilesDirectory]];
sqliteLogger.saveThreshold = 500;
sqliteLogger.saveInterval = 60; // 60 seconds
sqliteLogger.maxAge = 60 * 60 * 24 * 7; // 7 days
sqliteLogger.deleteInterval = 60 * 5; // 5 minutes
sqliteLogger.deleteOnEverySave = NO;
[DDLog addLogger:sqliteLogger];
// CCV = [CrestronControllerValues alloc];
CCV = [ccv retain];
port = [CCV getPortNumber];
ip = [CCV getIPaddress];
NSLog(@"ip %@ ~ port %@", ip, port );
}
return self;
}
and the sender method:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
[self.window makeKeyAndVisible];
[ConnectCommand addTarget:self action:@selector(command1ButtonPressed)
forControlEvents:UIControlEventTouchUpInside];
[SendJoin addTarget:self action:@selector(command3ButtonPressed)
forControlEvents:UIControlEventTouchUpInside];
[UpdateLog addTarget:self action:@selector(updateLogButtonPressed)
forControlEvents:UIControlEventTouchUpInside];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSArray *keys = [NSArray arrayWithObjects:@"IPaddress", @"PortNumber", nil];
NSArray *objs = [NSArray arrayWithObjects:@"10.8.30.111", @"41794", nil];
NSDictionary *dict = [NSDictionary dictionaryWithObjects:objs forKeys:keys];
[defaults registerDefaults:dict];
CrestronControllerValues *CCV = [[CrestronControllerValues alloc]init];
[CCV setIPID:3];
[CCV setIPaddress:[defaults stringForKey:@"IPaddress"]];
[CCV setPortNumber:[defaults stringForKey:@"PortNumber"]];
// NSLog(@"ip from defaults %@ ~ ip from ccv %@",[defaults stringForKey:@"IPaddress"], [CCV getIPaddress] );
cClient = [[CrestronClient alloc] initWithCCV:CCV];
[CCV release];
return YES;
}
another part of the problem was that port was an int
and trying to pass a nsstring to it caused crashing
but that [ccv retain] needs to be there
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Japanese characters looking like Chinese on Android PREAMBLE: since API 17 (Android 4.2), there's a method TextView.setTextLocale() that explicitly solves this problem for TextViews and derived classes. Assign a Japanese locale (Locale.JAPAN), and Unihan characters will look Japanese.
I have an application on Android that displays Japanese text in WebViews and TextViews. There are some Chinese characters (kanji) that look, by convention, differently in China and in Japan, but share the same Unicode codepoint. Normally, the browser would rely upon the lang tag to choose the correct glyph. On Android, they all default to their Chinese shapes, and I want Japanese shapes.
The problem is well explained in this article. This article also serves as a perfect illustration of the problem - when watched on Android (up to 2.2), the characters in the "Examples of language-dependent characters" all look the same, and Chinese.
Using the lang="ja" attribute does not help. Switching the whole system locale to Japanese does not help either.
I'm wondering about Android phones that are sold in Japan. Do characters like 直, 今, 化 look Chinese-style on those, too? I'm assuming not.
So the questions are: are there official localized images of Android out there? Can I get one to run on the emulator? Is the DroidSansFallback font still the only CJK-enabled font on those? And if it is, is it the same as on the vanilla USA Android?
I'm kind of hoping that the Japanese glyphs are hidden somewhere deep in the font (Unicode private area or something). If so, I could leverage them...
EDIT: located DroidSansJapanese.ttf, installed it on the emulator by copying into /system/fonts, restarted. It made no difference on the look of the Unihan article. Even the hint area of the Japanese text input (which should know better) displays as if Chinese.
How do I know the typeface name of the DroidSansJapanese.ttf? I have a feeling it's still Droid Sans, same as in the built-in DroidSansFallback font. But if they contain the same typeface, what governs which one should take precedence? One would think - system locale, but apparently not. Fonts in Android are installed just by copying, right?
A: Found a somewhat cludgey solution.
The DroidSansJapanese.ttf font exists and is available for download, for example, here. I downloaded it, renamed it to DroidSansJapanese.mp3 to avoid the 1MB compressed asset limit, and placed it under assets/web. I then introduced the following CSS statement:
@font-face
{
font-family: "DroidJP";
src:url('DroidSansJapanese.mp3')
}
Then I added 'DroidJP' to the font-family of every relevant CSS style. The way I load my HTML, the assets/web folder is already designated as the base for loading linked content.
Upon careful examination, I found several places in the app where Japanese was in TextViews. For those, I've loaded the typeface like this:
Typeface s_JFont =
Typeface.createFromAsset(Ctxt.getAssets(), "web/DroidSansJapanese.mp3");
and called setTypeface() on every relevant TextView. Now for PROFIT!
This expanded my APK by about 1 MB. There was an alternative way, where I'd store the font in the assets in compressed form - that'd save me about 500 KB of APK size, but then I'd have to expand it to phone memory on the first run, worry about data folder path, and lose compatibility with Android 1.5.
Some credit is due: here and here. Does not work on Android 2.1 (the WebViews, not the TextViews) - that's a known bug.
Now, the question remains - how do I identify devices where the default font already contains the Japanese shapes?
EDIT re: the mp3 hack. I've implemented the chunked solution at first, but then decided to go with font in the assets. The chunked approach has one upside - smaller APK size - and the following downsides:
*
*Consumes more phone memory - you end up storing both compressed font in assets and uncompressed in the data directory
*Is incompatible with Android 1.5 on the TextView side - the method Typeface.createFromFile() was introduced in API level 4
*Complicates HTML generation - the CSS with the @font-face declaration needs to be parametrised, since the data path is a variable
*Slows down the first app startup - you spend time combining the chunks
Storing the font as a compressed asset is not an option either - the font then doesn't show up in WebView, and you can clearly see in LogCat the message about "Data exceeds UNCOMPRESS_DATA_MAX".
A: There are fonts with full Japanese support. I've heard some people talking about DroidSansJapanese.tff and TakaoPGothic.
A: Using the following in your onCreate/OnCreateView:
AssetManager am = getContext().getApplicationContext().getAssets();
mDroidSansJapaneseTypeface = Typeface.createFromAsset(am, String.format(Locale.JAPAN, "fonts/%s", "DroidSansJapanese.ttf")); //I put the font file in the assets/fonts/ folder
And then for your textviews:
myTextView.setTypeface(mDroidSansJapaneseTypeface);
myTextView.setTextLocale(Locale.JAPAN);
Be aware that not 100% of all fonts will be displayed in Android. I haven't seen too many problems for Japanese characters, but other CJK characters may appear as blank boxes, no matter what ttf file you use.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503133",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
} |
Q: How to underline words in a string that also appear in a dictionary. PHP Hi I have a a string containing multiple words (about 26) and some of them will be real words which appear in a dictionary, others will just be rubbish.
What I need is for the computer to go through this string that has been outputted to the user, and underline, or highlight the real words.
I am using PHP, and the string will be different every time, and I already have a dictionary in txt format, that I have imported into the PHP and split up into an array, this is where the real words should come from.
A: If there is punctuation, you may want to remove it first using a regular expression.
$sentence = 'ajhfd dog bba food!';
$clean_sentence = preg_replace ('/[^0-9a-z\s]/', '', $sentence);
You can use the explode function to split the words into an array.
$words = explode(' ', $clean_sentence);
And then you can go through the words and see if they are in your dictionary.
foreach ($words as $word) {
if (in_array($word, $dictionary)) {
// This is a dictionary word, lets highlight it
$sentence = preg_replace("/\b$word\b/", "<b>$word</b>", $sentence);
}
}
A: You break out each string into an array of words using explode() by space. You can do the same for the text file with new lines. Then loop through each value in the array you made from your string and use in_array() to check if the value is in the dictionary array. If it's true, you can assign an <span class="dict_word">$value</span> or something like that and just style for that that class.
This sounds like homework so I'm not going to write the code for you.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Transfer files from one ftp to another I need to transfer file/files from one ftp to another. (automatically, let's say at midnight, when is server is less busy).
My question what my options are?
At the moment I'm reading how to use CRON and looking for php function to transfer files to external, and at the moment I'm not getting very far, I hope it's temporary. Would be nice to hear some advices.
Thank you,
Max
A: The question as stated appears to be about transferring files from one server to another automatically. The fact that these are ftp servers is incidental, since it is a very bad idea to use the same public-facing ftp service that clients use to fetch files to manage replication of said files (i.e. uploading new files and/or overwriting existing ones) - unless you really don't care about your system being hacked six ways to Sunday. PHP is not actually relevant at all, unless you have requirements that we don't know about from reading your question.
I would start by learning how rdist works. The general problem of synchronizing files across servers is decades old, and rdist has benefitted from a boatload of bugfixes and optimizations during that time. If you have more stringent security requirements (which seems unlikely since you're using ftp servers) then you may need to build a custom solution.
A: I would personally add a command to execute a shell script that uploads the files to a Cron table.
I did a quick googlesearch and found a recursive script that does this.
http://bash.cyberciti.biz/backup/copy-all-local-files-to-remote-ftp-server-2/
I do not take credit for the script. Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503138",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Getting error: AttributeError: class has no attribute '' Here is the code:
1 #!/usr/bin/env python
2
3 import re, os, sys, jira, subprocess
4
5 class Check_jira:
6
7 def verify_commit_text(self, tags):
8 for line in tags:
9 if re.match('^NO-TIK',line):
10 return True
11 elif re.match('^NO-REVIEW', line):
12 return True
13 elif re.match(r'[a-zA-Z]+-\d+', line):
14 # Validate the JIRA ID
15 m = re.search("([a-zA-Z]+-\d+)",line)
16 if m:
17 my_args = m.group(1)
18 result = Check_jira.CheckForJiraIssueRecord(my_args)
19 if result == False:
20 util.warn("%s does not exist"%my_args)
21 else:
22 return True
23 return True
24 else:
25 return False
26 if __name__ == '__main__':
27 p = Check_jira()
28 commit_text_verified = p.verify_commit_text(os.popen('hg tip --template "{desc}"'))
29
30 if (commit_text_verified):
31 sys.exit(0)
32 else:
33 print >> sys.stderr, ('[obey the rules!]')
34 sys.exit(1);
35 def CheckForJiraIssueRecord(object):
36
37 sys.stdout = os.devnull
38 sys.stderr = os.devnull
39
40
41 try:
42 com = jira.Commands()
43 logger = jira.setupLogging()
44 jira_env = {'home':os.environ['HOME']}
45 command_cat= "cat"
46 command_logout= "logout"
47 #my_args = ["QA-656"]
48 server = "http://jira.myserver.com:8080/rpc/soap/jirasoapservice-v2?wsdl"
49 except Exception, e:
50 sys.exit('config error')
51
52 class Options:
53 pass
54 options = Options()
55
56 options.user = 'user'
57 options.password = 'password'
58
59 try:
60
61 jira.soap = jira.Client(server)
62 jira.start_login(options, jira_env, command_cat, com, logger)
63 issue = com.run(command_cat, logger, jira_env, my_args)
64 except Exception, e:
65 print sys.exit('data error')
so maybe:
1. if name == 'main': shoudl be at the bottom ?
2. So, i have 2 classes (Check_jira) and (Options)
3. Check_jira has 2 functions verify_commit_text() and CheckForJiraIssueRecord()
4. I pass object as an argument to CheckForJiraIssueRecord since i am passing my_args to it , on its usage.
5. Not sure how to call one function from another function in the same class
6. Error i am getting is :
Traceback (most recent call last):
File "/home/qa/hook-test/.hg/check_jira.py", line 31, in
commit_text_verified = p.verify_commit_text(os.popen('hg tip --template "{desc}"'))
File "/home/qa/hook-test/.hg/check_jira.py", line 21, in verify_commit_text
result = Check_jira.CheckForJiraIssueRecord(my_args)
AttributeError: class Check_jira has no attribute 'CheckForJiraIssueRecord'
transaction abort!
rollback completed
abort: pretxncommit.jira hook exited with status 1
A: class Check_jira ends on line 25 and has only one method. Then you have an if block, and CheckForJiraIssueRecord is just a function defined in this block (that is, the function is defined if __name__ == '__main__'.
Just put the if block outside after the whole class definition.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Using php to parse values from a mysql dump file? Is there a script or class for PHP to parse the insert values from a mysql dump file? I wrote a script that massages data from an export. I want to parse all the values to do some conformance testing, and I wonder if that problem's already been solved.
For instance, in the dump file, I have
INSERT INTO table ( field1, field2, ... ) VALUES ( "a", "B", ...);
and I want to extract
a
B
to test those values and see that they're what I think they should be.
I also need this to be able to handle the extended inserts format, which is VALUES ( "a", "B", ...), ( "c", "D", ...), ( "e", "F", ...),.
A: php-sql-parser should do what you want. Here's a link to its manual:
http://code.google.com/p/php-sql-parser/wiki/ParserManual
A: Given your comments, I'd like to offer a few tips on what I think is the best way to handle this.
*
*You shouldn't be storing serialized data in a relational database. Instead, you should normalize your data, allowing you to take full advantage of what relational databases offer. I don't know how deeply your project depends on this, but if possible, I highly recommend refactoring.
*If you must keep storing/using serialized data (strongly recommend against this), I would consider avoiding the dump altogether, and using something like the following:
Process data in PHP, then update directly:
$tables = $db->query("SHOW tables");
foreach ($tables as $table) {
$rows = $db->query("SELECT * FROM $table");
foreach ($rows as $row) {
$foo = unserialize($row['foo']);
$foo = massage($foo);
$db->query("UPDATE $table SET foo=$foo");
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503150",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: backbone.js - accessing a model from a click event I have a BoardView containing a CellCollection of CellModels. I fetch the collection from the db and then create the CellViews.
This all works swimmingly until I try to access a CellModel via a click event on the BoardView. I can't get to the underlying models at all... only the views. Is there a way to do this?
I've attempted to include the relevant code below:
CellModel = Backbone.Model.extend({});
CellCollection = Backbone.Collection.extend({
model : CellModel
});
CellView = Backbone.View.extend({
className : 'cell',
});
BoardView = Backbone.View.extend({
this.model.cells = new CellCollection();
render : function() {
this.cellList = this.$('.cells');
return this;
},
allCells : function(cells) {
this.cellList.html('');
this.model.cells.each(this.addCell);
return this;
},
addCell : function(cell) {
var view = new Views.CellView({
model : cell
}).render();
this.cellList.append(view.el);
},
events : {
'click .cell' : 'analyzeCellClick',
},
analyzeCellClick : function(e) {
// ?????????
}
});
I need the click to "happen" on the BoardView, not the CellView, because it involves board-specific logic.
A: I would let the CellView handle the click event, but it will just trigger a Backbone event:
var CellView = Backbone.View.extend({
className : 'cell',
initialize: function() {
_.bindAll(this, 'analyzeCellClick');
}
events : {
'click' : 'analyzeCellClick',
},
analyzeCellClick : function() {
this.trigger('cellClicked', this.model);
}
});
var BoardView = Backbone.View.extend({
// ...
addCell : function(cell) {
var view = new Views.CellView({
model : cell
}).render();
this.cellList.append(view.el);
view.bind('cellClicked', function(cell) {
this.analyzeCellClick(cell);
};
},
analyzeCellClick : function(cell) {
// do something with cell
}
});
A: Good question! I think the best solution would be to implement an
EventBus aka EventDispatcher
to coordinate all events among the different areas of your application.
Going that route seems clean, loosely coupled, easy to implement, extendable and it is actually suggested by the backbone documentation, see Backbone Docs
Please also read more on the topic here and here because (even though I tried hard) my own explanation seems kind of mediocre to me.
Five step explanation:
*
*Create an EventBus in your main or somewhere else as a util and include/require it
var dispatcher = _.clone(Backbone.Events); // or _.extends
*Add one or more callback hanlder(s) to it
dispatcher.CELL_CLICK = 'cellClicked'
*Add a trigger to the Eventlistener of your childView (here: the CellView)
dispatcher.trigger(dispatcher.CELL_CLICK , this.model);
*Add a Listener to the Initialize function of your parentView (here: the BoardView)
eventBus.on(eventBus.CARD_CLICK, this.cardClick);
*Define the corresponding Callback within of your parentView (and add it to your _.bindAll)
cellClicked: function(model) {
// do what you want with your data here
console.log(model.get('someFnOrAttribute')
}
A: I can think of at least two approaches you might use here:
*
*Pass the BoardView to the CellView at initialization, and then handle the event in the CellView:
var CellView = Backbone.View.extend({
className : 'cell',
initialize: function(opts) {
this.parent = opts.parent
},
events : {
'click' : 'analyzeCellClick',
},
analyzeCellClick : function() {
// pass the relevant CellModel to the BoardView
this.parent.analyzeCellClick(this.model);
}
});
var BoardView = Backbone.View.extend({
// ...
addCell : function(cell) {
var view = new Views.CellView({
model : cell,
parent : this
}).render();
this.cellList.append(view.el);
},
analyzeCellClick : function(cell) {
// do something with cell
}
});
This would work, but I prefer to not have views call each other's methods, as it makes them more tightly coupled.
*Attach the CellModel id to the DOM when you render it:
var CellView = Backbone.View.extend({
className : 'cell',
render: function() {
$(this.el).data('cellId', this.model.id)
// I assume you're doing other render stuff here as well
}
});
var BoardView = Backbone.View.extend({
// ...
analyzeCellClick : function(evt) {
var cellId = $(evt.target).data('cellId'),
cell = this.model.cells.get(cellId);
// do something with cell
}
});
This is probably a little cleaner, in that it avoids the tight coupling mentioned above, but I think either way would work.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503151",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Div with auto height doesn't resize when elements appended On this div where the height is specified with CSS to be auto, the div height only changes if the elements contained are shown with display block. If display is not specified for the contained elements, the div isn't resized. The elements are added in code with javascript.
Here is the CSS for the div and for the elements appended.
#page {
height: auto;
min-height: 83%;
padding-bottom: 20px;
}
.linkcard, .linkcard_init {
position: absolute;
padding: 0;
margin-top: 20px;
margin-left: 20px;
border: 1px solid DarkKhaki;
border-radius: 3px 3px 0px 0px;
box-shadow: inset 0px 0px 10px DarkKhaki;
z-index: 26;
}
Here is the HTML. The elements are added to the div container with this code $("#page").append(response);. This appends echo statements from a PHP script.
<div id="page"> <!-- Begin page div -->
<div id="buttons">
<a href="#" onclick="create_linkcard();"> Add LinkCard</a> <br/>
</div> <!-- End buttons -->
<script type="text/javascript">
$(document).ready(function() {
// Make ajax call to recreate linkcards from XML data
$.ajax({
url: "get_nodes.php",
type: "POST",
data: { },
cache: false,
success: function (response) {
if (response != '')
{
$("#page").append(response); /*** ADDING DIV ELEMENTS ***/
}
}
});
});
</script>
</div> <!-- End page div -->
The PHP script echoes the response that is appended to the div with code like this.
echo "<div id = '".$node['ID']."' class= 'linkcard ui-widget-content' style = 'top: ".$node->TOP."px; left: ".$node->LEFT."px; width: ".$node->WIDTH."px; height: ".$node->HEIGHT."px;'> \n";
echo " <p class = 'linkcard_header editableText'>".$node->NAME."</p>\n";
echo "</div> \n";
The elements appear to be floating on top of the div (#page). They don't seem appended to the div. I say this because, when I add more elements to #page they are placed under the contained elements at the top left of #page. What in the code above could explain that the elements float on top instead of being added to the page?
A: If you want the height to change based on the content, you need to remove position:absolute from the appended element.
A: They are position: absolute;, that's your problem, have them position relative or remove the absolute all together.
Absolute position means that it isn't effected by any elements less a parent absolutely positioned element. With that, the inverse is true, elements without absolute position are not effected by absolutely positioned elements.
Try setting the parent to position:relative;, and making the parent display:block;
A: Setting overflow: hidden on #page may well do the trick. It certainly works to extend the enclosing div when all its contents are floated.
As the others have said, it wouldn't hurt to set position: relative on page too. This will ensure that the absolute positions are relative to the #page div, rather than the actual page.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Javascript inheritance and privileged functions Is it possible to inherit privileged methods in Javascript? In the below, Widget successfully inherits the D function, but not subscribe. Changing the second line in inherit to f.prototype = new base(); seems to work, but I know that's bad for all sorts of reasons. Is there a clean way to do this, or do I have to make everything public? This answer seems to imply that I have to make the methods public (attach to prototype) but I'd like to ask directly.
function EventRaiser() {
var events = {};
this.subscribe = function(key, func) { /* elided */ };
}
EventRaiser.prototype.D = function() { alert("D"); };
function Widget() { }
function Inherit(sub, base) {
function f() { }
f.prototype = base.prototype;
sub.prototype = new f();
sub.prototype.constructor = sub;
}
Inherit(Widget, EventRaiser);
A: this.subscribe = function(key, func) { /* elided */ };
here your adding a method to the current thisContext.
Inherit(Widget, EventRaiser)
Here your saling the prototype Widget should consume the prototype EventRaiser.
The best you can do is to not mix this.x with prototype.y
Or you can call EventRaiser.call(this) inside function Widget() { } but that's bad style.
If your going to use an inheritance pattern I would recommend you use Object.create & pd :
// prototype
var EventRaiser = {
D: function() { alert("D"); },
subscribe: function(key, func) { ... }
};
// factory
var eventRaiser = function _eventRaiser(proto) {
proto = proto || EventRaiser;
return Object.create(proto, pd({
events: {}
}));
};
// prototype
var Widget = {
...
};
// factory
var widget = function _widget() {
var o = eventRaiser(pd.merge(Widget, EventRaiser));
Object.defineProperties(o, pd({
...
});
return o;
};
Or if you insist Widget should inherit from EventRaiser
var Widget = Object.create(EventRaiser, pd({
...
});
var widget = function _widget() {
var o = eventRaiser(Widget);
Object.defineProperties(o, pd({
...
});
return o;
}
The reasons for recommending this pattern is a clear seperation of the prototype and the factory. This allows you to interact with the prototype without handling the factory. With the use of the new keyword you muddy those waters (as shown in your code) and you also tend to hack this around.
The above code also doesn't look elegant. This means that your realy aught to look for a different pattern. For example EventEmitter from node.js has an explicit check for the this._events object which makes the factory code more elegant.
A: Your privileged method this.subscribe is only ever attached to an instance of EventRaiser.
This should be obvious when you consider that this line:
this.subscribe = function(...) { } ;
is only ever executed when EventRaiser() is called.
If you don't create an EventRaiser object that property is simply never there to be inherited from.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: C# Why are some bitmaps resized after copying using GDI+? I have a Bitmap variable and I copy smaller 32x32 png files (loaded as Bitmaps) onto the bitmap. However, some png's are scaled up (always the same ones) and appear as 36x36 for example after copying. Almost as if some png's have another DPI or something? How can I prevent this?
Graphics g = Graphics.FromImage(destinationImage);
g.DrawImage(sourceImage, location); // sourceImage is sometimes larger than it actually is. On disk it is 32x32 but after copying it might be bigger...
g.Dispose();
A: I guess you are right about DPI, as it's stated in the documentation:
This method draws an image using its physical size...
I'm too lazy to make a test project, but I think Graphics.DrawImage(Image, Rectangle) with rectangle size equals to source image size will fix your problem.
A: The Image.Horizontal/VerticalResolution property matters. If it doesn't match the dots-per-inch setting of your monitor then the image is going to be drawn proportionally larger or smaller. This tends to be undesirable, use the DragImage(Image, Rectangle) overload to force it to display at exact 32 x 32 pixels.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7503155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.