text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Adding Columns in SQL SELECT I have the following SQL sp and I would like to add a column 'NetSales' which is simply 'GrossSales' - 'Credits'. Is there a way to do this in the same SELECT statement?
SELECT p.PerceptionistID, p.BaseCommission, p.BonusCommission, h.WeekOf, h.WorkHours, h.PTOHours, h.HolidayHours,
ROUND(h.WorkHours, 0) AS HoursRounded,
(
SELECT COUNT(c.PerceptionistID)
FROM T_Call c
WHERE
c.PerceptionistID = p.PerceptionistID
AND c.OutcomeID = @OutcomeSale
AND EnteredOn BETWEEN @WeekOf AND DATEADD(dd, 7, @WeekOf)
) AS GrossSales,
(
SELECT COUNT (c.PerceptionistID)
FROM T_CallCredit cc
FULL JOIN T_Call c
ON cc.CallID = c.CallID
WHERE
c.PerceptionistID = p.PerceptionistID
AND cc.CallCreditStatusID NOT IN (17, 18) -- 17 - 'Error in Customer Account', 18 - 'Courtesy Credit'
AND cc.EnteredOn BETWEEN @WeekOf AND DATEADD(dd, 7, @WeekOf)
) AS Credits
--------------------------------------------------
-- would like to have something like the following
SUM(GrossSales - Credits) AS NetSales
FROM T_Perceptionist p
FULL JOIN T_PerceptionistHours h
ON p.PerceptionistID = h.PerceptionistID
WHERE h.WeekOf = @WeekOf
TIA, Brian
A: Wrap the whole query with another like this:
select *, a.GrossSales - a.Credits as NetSales
from (
--your query here
) a
A: If You don't want to nest queries and You want to have only one SELECT, you must add another column to your column list (note that it is actually copy & paste of GrossSales and Credits columns with substraction sign between them):
(
SELECT COUNT(c.PerceptionistID)
FROM T_Call c
WHERE
c.PerceptionistID = p.PerceptionistID
AND c.OutcomeID = @OutcomeSale
AND EnteredOn BETWEEN @WeekOf AND DATEADD(dd, 7, @WeekOf)
) -
(
SELECT COUNT (c.PerceptionistID)
FROM T_CallCredit cc
FULL JOIN T_Call c
ON cc.CallID = c.CallID
WHERE
c.PerceptionistID = p.PerceptionistID
AND cc.CallCreditStatusID NOT IN (17, 18) -- 17 - 'Error in Customer Account', 18 - 'Courtesy Credit'
AND cc.EnteredOn BETWEEN @WeekOf AND DATEADD(dd, 7, @WeekOf)
) AS Net
However I would prefer nested queries as RedFilter suggested.
A: Just a sidenote, unrelated to your question (comment space is too small).
Your two FULL JOIN are cancelled as the queries have conditions in the WHERE clause that remove any NULL produced by the OUTER joins.
This is actually an INNER JOIN:
(
SELECT COUNT (c.PerceptionistID)
FROM T_CallCredit cc
FULL JOIN T_Call c
ON cc.CallID = c.CallID
WHERE
c.PerceptionistID = p.PerceptionistID
AND cc.CallCreditStatusID NOT IN (17, 18) -- 17 - 'Error in Customer Account', 18 - 'Courtesy Credit'
AND cc.EnteredOn BETWEEN @WeekOf AND DATEADD(dd, 7, @WeekOf)
) AS Credits
and this is a RIGHT JOIN:
FROM T_Perceptionist p
FULL JOIN T_PerceptionistHours h
ON p.PerceptionistID = h.PerceptionistID
WHERE h.WeekOf = @WeekOf
A: Normally, you just write 'a - b'. Here, they are fairly horrid expressions, so you use a 'sub-query in the FROM clause':
SELECT PerceptionistID, BaseCommission, BonusCommission, WeekOf, WorkHours, PTOHours,
HolidayHours, HoursRounded, GrossSales, Credits, (GrossSales - Credits) AS NetSales
FROM (SELECT p.PerceptionistID, p.BaseCommission, p.BonusCommission, h.WeekOf, h.WorkHours,
h.PTOHours, h.HolidayHours, ROUND(h.WorkHours, 0) AS HoursRounded,
(SELECT COUNT(c.PerceptionistID)
FROM T_Call c
WHERE c.PerceptionistID = p.PerceptionistID
AND c.OutcomeID = @OutcomeSale
AND EnteredOn BETWEEN @WeekOf AND DATEADD(dd, 7, @WeekOf)
) AS GrossSales,
(SELECT COUNT (c.PerceptionistID)
FROM T_CallCredit AS cc
FULL JOIN T_Call AS c ON cc.CallID = c.CallID
WHERE c.PerceptionistID = p.PerceptionistID
AND cc.CallCreditStatusID NOT IN (17, 18)
AND cc.EnteredOn BETWEEN @WeekOf AND DATEADD(dd, 7, @WeekOf)
) AS Credits
FROM T_Perceptionist p
FULL JOIN T_PerceptionistHours h
ON p.PerceptionistID = h.PerceptionistID
WHERE h.WeekOf = @WeekOf
) AS X33;
If you need aggregates in there too, you supply the appropriate GROUP BY clause too.
Long delay while typing answer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575114",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I do set a variable in Windows command line to an IP? Is there an easy way to grab the IP address from my service provider and put it into a variable via command prompt? Something like the following:
SET hostIP = nslookup \address
ECHO %hostIP%
Or
SET hostIP = ipconfig \address
ECHO %hostIP%
A: for /f "skip=1 tokens=2 delims=: " %f in ('nslookup %COMPUTERNAME% ^| find /i "Address"') do echo %f
A: The answer by Arun is good but I found that using NSLOOKUP generates a rogue comma after the hostname when more than one IP is assigned/associated with a given host.
However, I did find another way that resolves the (first assigned) IP from a given host name and doesn't generate the rogue comma - it uses PING. Very fast, very reliable.
for /f "tokens=2 delims=[]" %f in ('ping -4 -n 1 %COMPUTERNAME% ^| find /i "pinging"') do echo IP=%f
It generates a simple IPv4 address for the hostname into the variable IP. If you then do an ECHO %IP% it will show you the IP like:
IP=192.168.1.2
Of course, in batch scripts, you're going to need to replace the single %f with %%f. Note the carat ("^") in front of the pipe ("|") symbol, which is required in batch scripts so they don't interpret the pipe, and instead pipes the results of the ping statement to the find statement.
A: If you could use bash, (as in cygwin) this would easily be done using back-ticks to execute anything you want in your SET hostIP line.
As in
export hostIP = `curl 'http://whatsmyip.net' | grep '<title' | awk '{print $8}' | sed -e 's:<.*::g'`
A: Try a batch like this to set environment variables:
ipconfig > ipconfig.out
setx IPADDR /f ipconfig.out /a 7,13
setx IPADDR /f ipconfig.out /a 7,14
setx IPMASK /f ipconfig.out /a 8,14
Exit the command prompt and open a new one. Use SET and look for IPADDR and IPMASK, which are now persistent. To update the variables, you would have to rerun the batch and exit the command prompt. The different coordinates shown account for differences in the IPCONFIG output for Windows 2003 vs Windows 2008 (should work on XP/7 in the same way). Only a found value is written, so the line that fails does no harm as long as nothing is found. Add the gateway with:
setx IPGATE /f ipconfig.out /a 9,12
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Move list box items from one listbox to another listbox? I am trying to move listbox items between two listboxes.Before that i created two arrraylists for each listbox.so before moving the listbox item i am trying to add the items to the arraylist. here is the code
foreach (string st in listbox1.Items)
{
arraylist1.Add(st1);
}
but i am getting an exeption Unable to cast object of type 'System.Web.UI.WebControls.ListItem' to type 'System.String'.
A: You're getting this error because listbox1.Items is a ListItemCollection.
foreach (ListItem li in listbox1.Items)
{
arraylist1.Add(li.Text);
}
A: foreach (string st in listbox1.Items) should be
foreach (ListItem st in listbox1.Items)
// your code
A: Try using
foreach (ListItem li in listbox1.Items)
{
arraylist1.Add(li.Text);
}
A: ListBox.Items is of ListItemCollection type. It consists of ListItem objects, not strings.
What You are trying to do is:
foreach (ListItem lstItem in ListBox1.Items)
{
arraylist1.Add(lstItem);
}
A: This is because a list item is an object in it's own right and not a string object. So change the string to ListItem in your code above and it should work fine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Error 422 when load testing Rails 3.1 application with JMeter I have a Rails 3.1 application that I am trying to use JMeter to load test.
Our site is targeted around collecting information so users sign-up and then walk through a question and answer workflow and after answering a few questions, they are rewarded with some useful information.
My JMeter test is configured to walk through sign-up and then the full Q&A workflow.
Environment details:
RedHat Enterprise 6
Rails 3.1
Ruby 1.9.2p290
DB: Postgres 9
I have run tests with 20 and 100 concurrent threads and a ramp-up time of 1 thread per second and the results are ok. However, as soon as I increase the rampup time so there are multiple threads spawned in a second (even as little as 2 per second), about half of the signup calls fail with an error 422. Once that happens, for those same threads, the Q&A workflow breaks because we are assuming that there is a valid user answering questions.
I'm trying to figure out if there is a problem with the application code, server configuration, or JMeter setup.
Any thoughts or suggestions on how to troubleshoot this further would be greatly appreciated.
A: It may be a cookie issue on the JMeter side wherein non-unique cookies are being assigned to multiple threads.
http://rfc-ref.org/RFC-TEXTS/4028/chapter6.html#d4e441904
This extension introduces the 422 (Session Interval Too Small)
response code. It is generated by a UAS or proxy when a request
contains a Session-Expires header field with a duration below the
minimum timer for the server. The 422 response MUST contain a Min-SE
header field with the minimum timer for that server.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can I programmatically force changes to a file to propagate to all NFS clients? I have a CMS built in PHP which stores the list of pages, page navigation structure, and the content of pages in files on disk. This application is hosted on a cluster of Apache/php-fpm servers which are behind a haproxy server. These servers mount the Apache DocumentRoot directory via NFS from a central file server, so all the changes made from the CMS get written to files on the NFS share.
I have found that, unless I mount the NFS share with the noac option, changes made may take up to 5-10 seconds to propagate to all servers in the cluster; meaning when multiple changes are made in rapid succession, the final change sometimes overwrites the earlier changes because the final change may go to a server which has not received the earlier changes yet.
However, when using the noac mount option, there's a 2-5 second delay in accessing the content on the visitor side, which is completely unacceptable.
Is there a way to programmatically force changes to a file on an NFS share to propigate to all clients, or to cause all clients to flush their cache of that file?
A: I don't know of any NFS-level option to achieve what you want BUT if the applications accessing those files are under your control then you can make every file open use the O_DIRECT option - this bypasses any local NFS cache for any file opened this way...
A remark:
You write that noac leads to a delay of 2-5 seconds.. this seems to point to a network- and/or storage-level problem or to "far to many files/directories within one directory"...
A: I solved the same issue with NFS parameter cto in combination with apache directives EnableMMAP Off and EnableSendFile Off. the noac parameter had the same symptoms you wrote about.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: how to change the text color using jquery or javascript I have a two items(rows) in the list box
I love to work with jquery
i love to work with javascript
I have textbox and button when I enter love in the text box when I click button i need to loopthrow this list box to find the text love and change that love text color? to yellow.
thanks
A: first of all, jQuery is javascript, it's a library written in javascript.
So, If I understand your problem, you have 3 interactive elements on your page:
*
*a list box containing a list of words
*a text field for the user to enter a word
*a button for the user to click when he has written the text.
And you want the option to change color when the user clicks the button.
the code for thsi would be something like this:
$("#mybutton").click(function(){
var text = document.getElementById("mytextinput").value
$("#lstCodelist option").each(function (){
if(this.text()===text)
this.css('color':'yellow');
});
});
this is what happens:
*
*line 1: I define a click handler when the button gets clicked.
*line 2: I get the text from inside the textbox, I use getElementById to avoid the overhead of using jQuery for something that simple
*line 3: I loop over each of the items in the list.
*line 4: if the string in the textbox equals the text inside the option:
*line 5, change the css property of the list option.
So no, this is not affecting the text, it only edits the css.
A: for changing text box color, you can add class to the element
addClass("myClass yourClass");
http://api.jquery.com/addClass/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android ActionBar and Cursor public class TaskDetailTabHome extends Activity implements ActionBar.TabListener{
String taskid, empid, ac;
private DbAdapter_Assignment assignment;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tasktab);
taskid = getIntent().getExtras().getString("TaskID");
empid = getIntent().getExtras().getString("EmpID");
ac = getIntent().getExtras().getString("AC");
ActionBar bar = getActionBar();
bar.addTab(bar.newTab().setText("TASK").setTabListener(this));
bar.addTab(bar.newTab().setText("COMMENT").setTabListener(this));
bar.addTab(bar.newTab().setText("FLIGHT").setTabListener(this));
bar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_USE_LOGO);
bar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
bar.setDisplayShowHomeEnabled(true);
bar.setDisplayShowTitleEnabled(false);
assignment = new DbAdapter_Assignment(getBaseContext());
assignment.open();
}
@Override
public void onTabReselected(Tab arg0, FragmentTransaction arg1) {
}
@Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
if(tab.getText()== "TASK")
{
setContentView(R.layout.tasktab);
Cursor c = assignment.taskDetails(taskid, empid); ??????????
}
}
I am trying to pupulate the view with SQLite data. But the cursor is throwing an error(NullPointerException). The same cursor is working when I am not using ActionBar(tabs). what am I doing wrong ?
A: I suppose the problem is here :
assignment = new DbAdapter_Assignment(getBaseContext());
assignment.open();
And more exactly here getBaseContext() I think it's the only line where you can have problems (thinking of course that taskid and empid are not null of course) . Search for the exact use of getBaseContext() .
A: You can try this. I guess you're working with tabs and not getting the right context. You should go up in the context until you get the last parent and try to get it done.
public static Context goUp(Activity current){
if(current.getParent()!=null){
current=current.getParent();
goUp(current);
}
return current.getBaseContext();
}
assignment = new DbAdapter_Assignment(goUp(TaskDetailTabHome.this));
assignment.open();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ASP:Labels not updating on button Click I know this is probably something so simple that I am just not able to see it. I have an aspx form that has a usercontrol in an updata panel. The user control is a people picker the searches on users from a corporate database.
What I want to see happen is:
*
*The user clicks on a pick user button
*The update panel with people picker becomes visible
*They search for a user and then select the one they want.
*When they make the selection and click Done, I get the user id of the user and look them up in our user table.
*The user information should show up in a the form in label fields.
I can step through the code and see that I am getting the user information and that the label text is being set to the values but the page never updates the labels. It is a postback so I would think they would update.
<tr>
<td colspan="4">
<asp:UpdatePanel ID="CollapseDelegate" runat="server">
<ContentTemplate>
<asp:Panel ID="pDelegateHeader" runat="server">
<div style="padding: 10px 0 10px 20px; height:10px; text-align: left; background-color:#ffffff; color:#000000; border: 2px solid #ccc;" >
<asp:Label ID="ShowDelegate" runat="server" /><br />
</div>
</asp:Panel>
<asp:Panel ID="pDelegateBody" runat="server">
<PP:PeoplePicker ID="PP" runat="server" />
<asp:Button ID="btnOk" runat="server" Text="Done" CssClass="Buttons" onclick="btnOk_Click" />
</asp:Panel>
<asp:CollapsiblePanelExtender ID="CollapsiblePanelExtender3" runat="server" TargetControlID="pDelegateBody" CollapseControlID="pDelegateHeader" ExpandControlID="pDelegateHeader" Collapsed="true" TextLabelID="ShowDelegate" CollapsedText="Pick User..." ExpandedText="Close..." CollapsedSize="0"></asp:CollapsiblePanelExtender>
</ContentTemplate>
</asp:UpdatePanel>
</td>
</tr>
<tr>
<td><asp:Label ID="DelegateNameLabel" runat="server" Text="Name:" CssClass="indentedText" /></td>
<td><asp:Label ID="DelegateNameValueLabel" runat="server" CssClass="indentedText" Visible="true"></asp:Label></td>
<td><asp:Label ID="DelegateEmailLabel" runat="server" Text="Email:" CssClass="indentedText" /></td>
<td><asp:Label ID="DelegateEmailValueLabel" runat="server" CssClass="indentedText" Visible="true"></asp:Label></td>
</tr>
<tr>
<td><asp:Label ID="DelegatePhoneLabel" runat="server" Text="Phone:" CssClass="indentedText" /></td>
<td><asp:Label ID="DelegatePhoneValueLabel" runat="server" CssClass="indentedText" Visible="true"></asp:Label></td>
<td><asp:Label ID="DelegateVerifiedLabel" runat="server" Text="Last Verified Date:" CssClass="indentedText" /></td>
<td><asp:Label ID="DelegateVerifiedValueLabel" runat="server" CssClass="indentedText" /></td>
</tr>
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
string PassedDelegateID = string.Empty;
string Mode = string.Empty;
int delegateId = 0;
if (Request.QueryString["Id"] != null)
{
PassedDelegateID = Request.QueryString["Id"].ToString();
}
else
{
PassedDelegateID = "0";
}
if (Request.QueryString["mode"] != null)
{
Mode = Request.QueryString["mode"].ToString();
}
else
{
Mode = "add";
}
if (Mode == "add")
{
pnlUdpateDelegateText.Text = UIConstants.ADDDELEGATETEXT.ToString();
}
else
{
pnlUdpateDelegateText.Text = UIConstants.UPDATEDELEGATETEXT.ToString();
if (int.TryParse(PassedDelegateID, out delegateId))
{
loadDelegateData(delegateId);
}
}
}
}
protected void btnOk_Click(object sender, EventArgs e)
{
TextBox txtSearchValue = (TextBox)PP.FindControl("txtSearchResults");
string LanId = txtSearchValue.Text;
User user = BusinessUtility.GetUser(LanId);
DelegateNameValueLabel.Text = user.Name;
DelegateEmailValueLabel.Text = user.Email;
DelegatePhoneValueLabel.Text = user.Phone;
DelegateVerifiedValueLabel.Text = DateTime.Now.ToShortDateString();
}
Thanks,
Rhonda
A: Because the labels are outside the update panel, only the content inside the update panel is updated from an ajax post-back, that's the whole point of an update panel.
You will need to either move the labels inside the update panel's content area, or have another update panel for the labels and make it's update mode "always"
A: Your lables are outside of the UpdatePanel.
Under the hood, ASP.Net performes a full postback, but only the part that pertains to your UpdatePanel is transfered back down to the client. Some JavaScript then takes this bit of HTML and replaces the existing <div> element that is your UpdatePanel.
Since your labels are outside of that <div> they never get updates.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575153",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Destruct Unmanaged object From .NET code I've wrote a C++ library that is exposed to my VB.NET application through a C++/CLI wrapper.
I'm worried about objects that I'm shuttling up to the VB.NET application through the wrapper. To use the classes in the library I've written wrappers for them and the wrapper classes contain pointers to an unmanaged instance of the class. In the destructor of the wrapper class I delete the memory that the unmanaged pointer is pointing to.
If the wrapped .NET library passes one of these class instances to the VB.NET application and the VB.NET application uses it and moves on (doesn't save a reference to it); will the .NET garbage collector come around and dispose this class instance causing the unmanaged memory to be deallocated in the destructor of the class? This would cause an error if I had a reference to this same memory that the wrapped class instance pointed to.
If this is the case then I'll just copy all the data in the wrapper to ensure that my wrappers don't share any data with the native portion of the library. If this isn't the case then do I have to call some sort of dispose method on the wrapped class instance in order to destruct the unmanaged object?
A: In CLI, you simply have to use the destructor syntax (~MyClass()) and the C++/CLI compiler will create an IDisposable implementation on the class for you.
This "destructor" (it's not really, it just has the syntax of one) will be called when the Dispose method is called in unmanaged code. It's here that you would put the calls you need to make in order to release resources.
If you want to implement a finalizer, then you would use the new destructor syntax (!MyClass()). This should release the same resources that you would in your "destructor".
Finally, in your managed code, you simply would reference the IDisposable implementation and then call Dispose on it, more than likely through the using statement.
A: You are mixing it up a bit. Yes, after the vb.net code stops referencing one of your C++/CLI classes then eventually the finalizer will be called after the object got collected. Note that this is the finalizer, it has nothing to do with dispose. Your C++/CLI object should provide both a destructor (called by Dispose()) and a finalizer.
There is otherwise no danger of memory corruption. The finalizer only gets called when the garbage collector cannot find any live references to the object. Since there is no reference left, there's no way that you can accidentally access the deleted native object. Check this answer for the standard pattern.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Bing maps and monotouch I'm wondering if there's any SDK/control to use bing maps with monotouch? or probably any solutions on how to use iOS bing SDK with monotouch
A: Chris Hardy has created MonoTouch bindings for Bing maps. Check it out here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575159",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to dynamically populate data from url to expandable listview categories in android? hiii,
I am working on a project where i am calling a url and fetching data as json . Now , this json object will be parsed.
Now i am getting a json tag like status= active or status = notActive.
Based on this response , i have to place some data tags which have a status "Active" under group title "Active" under listview and notActive data under "NOT-ACTIVE" group title.
*How to different data based on status value under two groups seperately so that when i click Active group , i will ge*t different data for Active only .
Any kind of help will be highly appreciated....
A: This way i solved it.
try{
jArray = new JSONArray(json);
for(int i=0;i<jArray.length() ;i++){
Map<String, String> childdata1 = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String status = e.getString("2");
// Log.e("log_tag","Status: "+status);
if (status.contains("active")){
// Log.e("log_tag","StatusActive: "+status);
//childdata1.put("child", String.valueOf(i));
childdata1.put("child", e.getString("mlsid"));
childdata1.put("child1", e.getString("status"));
childdata1.put("child2", e.getString("address"));
childdata1.put("child3", e.getString("city"));
child1.add(childdata1);
}else if(status.contains("pending")){
//Log.e("log_tag","StatusPending: "+status);
Map<String, String> childdata2= new HashMap<String, String> ();
// childdata2.put("0", String.valueOf(i));
childdata2.put("child", e.getString("mlsid"));
childdata2.put("child1", e.getString("status"));
childdata2.put("child2", e.getString("address"));
childdata2.put("child3", e.getString("city"));
child2.add(childdata2);
}
}
// Log.e("log_tag","ARRAY Length : "+jArray.length());
}catch(JSONException e) {
Log.e("log_tag", "Error parsing data "+e.toString());
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575161",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to use NSColor? Where does it belong? How to reference it? I want to use the keyboardFocusIndicatorColor inside my code but not sure where NSColor is. The documentation says AppKit.framework but when I try to link a library AppKit.framework does not exist.
NSColor *transBG = [[NSColor keyboardFocusIndicatorColor]
A: You tagged this question iOS so you should be using UIColor and the UIKit framework instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android Sqlite get last insert row id
Possible Duplicate:
Get generated id after insert
I want to get the last inserted row id in my android application using this code :
String query = "SELECT * from SQLITE_SEQUENCE";
int createdUserId = Integer.parseInt(dbHelper.executeSQLQuery(query).toString());
but the problem is that it's throws an exception that cannot convert dbHelper.executeSQLQuery(query).toString() to integer. I'm not really good at sqlite ,but i think that this should return the last row id which was inserted...which will definitely will be int (at least I think this way). So if this is not the right way, can someone please guide me how to get the last row id in android application.
Thanks!!!
A: Your SQL statrment will return all the row ids, not just the latest. Try something like this...
SELECT ROWID from SQL_LITE_SEQUENCE order by ROWID DESC limit 1
Also note that I believe selecting from SQL_LITE_SEQUENCE will get the latest ID from ANY table, you can also access the SQL_LITE_SEQUENCE by selecting ROWID on any table, and getting just the IDs for that table. IE
SELECT ROWID from MYTABLE order by ROWID DESC limit 1
And thanks to MisterSquonk for pointing out the next step in the comments, adding it here for ease of reference later...
The query statement will then return a Cursor object containing the results, so to access the integer value you would do something like this (I'll substitute more common methods for your helper method, just for others sake)
String query = "SELECT ROWID from MYTABLE order by ROWID DESC limit 1";
Cursor c = db.rawQuery(query);
if (c != null && c.moveToFirst()) {
lastId = c.getLong(0); //The 0 is the column index, we only have 1 column, so the index is 0
}
(Note that although the SQL Lite docs call ROWID and Integer, it is a 64 bit integer, so in Java it should be retrieved as a long.)
A: Care to use "selectlast_insert_rowid()"? :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: How to add a timestamp to OutputDebugString()? I am writing a C++ application, and I want to add a timestamp to OutputDebugString(). I already know that if I watch the application using DebugView, it automatically show timestamps. But for a particular reason I want to add TimeStamps to any string I pass to OutputDebugString().
What would some sample code be?
A: You could use QueryPerformanceCounter and QueryPerformanceFrequency to get a high-resolution timestamp. If you set a variable to the value returned by QueryPerformanceCounter before your program really starts executing, you can achieve the same effect as debug view by subtracting this initial value from the current performance counter value when printing to a debug string. GetTickCount is another API you can use, although the resolution isn't as good.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575172",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Calling ( triggering ) a link after the submit How could I call (trigger) a link after the form submits ? I'd like the function to call a link so that the new jQuery div is called on its own after the button submits an upload. The infoUp() function doesn't work..
HTML:
<a href="#" id="profile">Profile</a>
<form name="updatePicForm" action="page1.php" method="post" enctype="multipart/form-data">
<span style="font-size:12px"> Picture upload size 1 MB </span>
<input type="file" name="uploadPic" class="forms" id="picForm"/>
<input type="submit" name="submitPic" value="Go" id="submitPic" onClick="infoUp();"/>
<!--<span class="style3"> 2 MB max </span>-->
<input type="hidden" name="MAX_FILE_SIZE" value="1048576" />
</form>
//jQuery:
function infoUp() {
$(document).ready(function() {
$("#profile").trigger('click');
});
A: If you do a regular form submit, then the document will be replaced with the result of the form post, so no further JavaScript will execute. What you need to do is use "AJAX" techniques to send a post request without replacing the current page.
This is a pretty big redesign because you need to change the PHP handler for the URL you're posting to so it just processes the post and change your client-side code so it updates through JavaScript instead of through replacing the document.
A: You need to use Ajax to process both server (submit) and client(infoUp) action simultaneously. Else client action will become invalid.
A: You can do:
// when the form is submitted
$('form').submit(function(){
// run your infoUp function
infoUp()
// sends the form info off
return true
})
But this would not help much, because submitting the form would send you to another page.
You should probably submit the form via ajax like this:
// when the form is submitted
$('form').submit(function(){
// sends the form info off
// callback function executes after form data is sent
$.post('page1.php',$('form').serialize(),function(){
// run your infoUp function
infoUp()
})
// prevent form from submitting normal request
return false
})
This code is all untested, but should give enough insight into how to go about it
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Zend_Validate_Regex - allow only letters, numbers, and characters -_ So, I have a text field that can contain only letters, numbers, hyphens, dots and underscores. I would like to validate it using Zend_Validate_Regex but this pattern does not work. Why?
/[a-z][A-Z][0-9]-_./
Here is my text element:
$titleSlug = new Zend_Form_Element_Text('title_slug', array(
'label' => 'Title Slug',
'required' => FALSE,
'filters' => array(
'StringTrim',
'Null'
),
'validators' => array(
array('StringLength', FALSE, array(3, 255)),
array('Regex', FALSE, array('pattern' => '/[a-z][A-Z][0-9]-_./'))
)
));
A: Your regex matches a string that contains a lowercase letter, an uppercase letter, a digit, a dash, an underscore and any other character, in that order. You need this:
/^[\w.-]*$/
^ and $ anchor the match at the start and end of the string.
\w matches letters, digits and underscore; together with the dot and dash they form a character class ([...]) which is repeated zero or more times (*).
A: how about this:
/[a-zA-Z]*|\d*|-*|\.*|_*/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: What's exactly behind / inside iPhone memory management? This question is NOT about retain/release things in iphone memory management. I understand the routine quite well and there is no memory leak things in my app.
I pop up the question shown in the title, when I use Activity Instruments to monitor the overall memory activity of my app.
The instrument always shows that the amount of "real memory", which my app is using, keeps being between 21 MB and 30MB, never higher. I think this amount is relatively not big. However, sometimes, my app will give level 1 or 2 memory warning (never crash and I don't do anything for this warning in my code).
so I am wondering what's really behind iphone memory thing. I mean, does real memory the only things that triggers warnings? or there is anything else (such as virtual memory, as shown in the Instruments) inside the whole memory I should take care of?
Although my app never crash due to memory issues, this warning thing (especially level 2 warning) really annoys me and makes me fear of crashing once I release it to public in the future.
Any help?
Thanks
A: Memory warnings exist to tell your app you're nearing your limit. They are not necessarily a 'bad' thing - plenty of applications simply ignore them.
The actual implementation details about when a memory warning is triggered are not important, and in fact will vary considerably from device to device. An iPhone 4 might have 512MB of RAM to play with, but a 3GS will have half that.
That said, there are some things worth knowing about memory warnings:
*
*A memory warning is triggered when the overall amount of available free memory reaches a certain level
*These levels are undocumented. So you don't know what the difference is between a level 1 warning and a level 2 warning, other than the fact 2 is worse (more urgent) than 1
*Memory warnings are not application specific. A memory warning is delivered to all applications currently running and not suspended. So you may not be directly responsible for triggering one.
*When memory warnings are received the system will try and free up memory on your behalf
Again, the exact implementation details are undocumented, and you shouldn't need to care about them. A memory warning is an opportunity for you to help the system by freeing up any objects you don't need.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Android - search based on property of AutoCompleteTextView suggestion, or value of AutoCompleteTextView I have a MyObj class with a name and an id. I have an AutoCompleteTextView that is currently letting you type MyObj names and it auto-completes them for you. There's a button next to the AutoCompleteTextView that, when pressed, I want to:
*
*initiate a search based on the id of the selected MyObj, if one of the auto-complete suggestions was used, OR
*initiate a search based on the value in the AutoCompleteTextView if none of the auto-complete suggestions was used (so a partial name string).
How should I go about this? I'm new to Android, so suggestions for other ways to do this are very welcome. Here's some of my current code:
AutoCompleteTextView actv = (AutoCompleteTextView)findViewById(R.id.searchText);
ArrayAdapter<MyObj> adapter = new ArrayAdapter<MyObj>(this,
android.R.layout.simple_dropdown_item_1line, myObjectsList);
actv.setAdapter(adapter);
And also:
public void searchButtonOnClick(View view) {
// Don't know how to get id of selected MyObj here, or just the value in the
// AutoCompleteTextView otherwise
}
A: I ended up creating a search instead of using an AutoCompleteTextView, since the search gives suggestions as you type also. I was able to pass the id along via the URI in an Intent to display another Activity with the MyObj details.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575186",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Windows Identity Foundation System.Xml.XmlException: Unexpected end of file We have a custom STS along our website both running in Windows Azure. The STS is ASP.NET 4.0 and the site is MVC3. In the past few days I've started seeing quite a few of the following exceptions showing up in our diagnostics logs:
System.Xml.XmlException: Unexpected end of file.
at System.Xml.EncodingStreamWrapper.ProcessBuffer(Byte[] buffer, Int32 offset, Int32 count, Encoding encoding)
at System.Xml.XmlUTF8TextReader.SetInput(Byte[] buffer, Int32 offset, Int32 count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
at System.Xml.XmlDictionaryReader.CreateTextReader(Byte[] buffer, Int32 offset, Int32 count, Encoding encoding, XmlDictionaryReaderQuotas quotas, OnXmlDictionaryReaderClose onClose)
at System.Xml.XmlDictionaryReader.CreateTextReader(Byte[] buffer, Int32 offset, Int32 count, XmlDictionaryReaderQuotas quotas)
at Microsoft.IdentityModel.Web.SessionAuthenticationModule.GetKeyId(Byte[] sessionCookie)
at Microsoft.IdentityModel.Web.SessionAuthenticationModule.ReadSessionTokenFromCookie(Byte[] sessionCookie)
at Microsoft.IdentityModel.Web.SessionAuthenticationModule.TryReadSessionTokenFromCookie(SessionSecurityToken& sessionToken)
at Microsoft.IdentityModel.Web.SessionAuthenticationModule.OnAuthenticateRequest(Object sender, EventArgs eventArgs)
at System.Web.HttpApplication.SyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously
I don't know if there is any impact to the end user or what problems this may be causing. Would love it if someone could shed some light on this exception and what I might be able to do to prevent it in the future.
A: When you use Wif, Wif transforms the user information to a Fed cookie so that the user don't need to authenticate again and again. This Fed cookie, session cookie, is for each request interpretted by the Session Authentication Module which sets the User for the HttpContext and Thread.
Since the user information can be substantial, usually this cookie is chunked into smaller pieces.
In your case what is happening is SAM is failing to read the data represented in the cookies.
The error you are seeing might be end result of a browser limiting the number/size of cookies submitted.
The impact to the user is failed authentication or 500 depending on how this error is handled, which I haven't investigated.
I would recommend trying to see how many cookies your site hands out. I have seen in some posts that Opera and Safari can have trouble with these:
http://social.msdn.microsoft.com/Forums/eu/Geneva/thread/dc1e178f-46ab-4567-88b8-1f2541744908
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: undefined method `to_key' for -- NOT USING MONGO I found a gazillion answers for my issue if I was using Mongo, but none of the ones I see work out here since I am not using mongo.
Basically I have a report_controller.rb that has a very simple method defined:
def donations_by_season
@donations = Donation
end
and a very simple report/donations_by_season.html.erb as follows:
<%= form_for @donations do |f| %>
Stuff Will go here... such as fields to select a date for the season we wish to view.
<% end %>
There is no report model, just a controller and views.
But when I attempt to view /reports/donations_by_season
I immediately get:
undefined method to_key' for #<Class:0x00000114d85918>
What should I do to fix that? Am I doing my form incorrectly since there is no model associated with reports?
A: You should never be assigning an instance variable to point to a class object like this. You probably want this:
def donations_by_season
@donations = Donation.all
end
Note the .all versus just leaving it blank. You could also do .new or a litany of other methods, depending on what you're trying to do.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to Transfer app ids from one account to another Is it possible to transfer app ids owned by one FB account to another?
A: Yes this works perfectly.
*
*Go to your FB app -> goto Roles, assign a Facebook friend as an administrator.
*Ask him to accept the request and become an admin. (He has to add his account as a developer account, if not already a dev).
*Now he goes to the App Dashboard and can see the app there. Can access the entire app. Good to go!!!
The primary administrator of the app can even delete the app from his account. Nothing happens to the transferred app
A: I didn't do this before, but try to add a friend as administrator and then delete the original administrator from the app.
Maybe your friend has to have the right to be an administrator, that is he has to be uniquely identified by Facebook as it works in your country.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: How to create my own preference screen? Please have a look on the image:
There is an item rounded with red color on the right pane. This is a PreferenceScreen item. I need to show another my own view after clicking on this item. See next screen please:
A: You can make really minimal subclasses of the neccessary Preference classes where you set your own layout via setLayoutResource() in the constructor and bind anything you need to pass in with xml parameters by overriding the onBindView(View) method.
These can then be used inside a PreferenceScreen in xml by using the fully qualified <com.mypackage.mypreference/> tag
If you find yourself making a lot of different views you might want to reconsider, because although settings can reasonably stand some theming. It probably shouldn't get too "widget-y".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575195",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Optional parameter with setParameterList in HQL I have a query with optional parameter
"SELECT ClinicId,Name from Clinic where :ClinicIds is NULL OR ClinicId IN :ClinicIds"
List<int> ClinicIds = null;
I'm passing the parameter as following
q.SetParameterList("ClinicIds", ClinicIds);
Because ClinicId is an optional parameter. If I pass null to SetParameterList I'm getting exception. Any idea how I can pass an optional parameter(null value) to SetParameterList.
Thanks
A: Rather than using HQL, use a Criteria query. Its designed to be more programmatic than HQL, in that you use straight Java code to assemble your query, which enables you to use if-then logic. So, instead of either concatenating HQL, or having two different HQL queries which you need to independently maintain, you have one Criteria query which accounts for both situations. Example:
//SELECT ClinicId,Name from Clinic where :ClinicIds is NULL OR ClinicId IN :ClinicIds
Criteria criteria = getSession().createCriteria(Clinic.class);
if(ClinicIds == null) {
criteria.add(Restrictions.eq("ClinicId", null));
} else {
criteria.add(Restrictions.or(
Restrictions.eq("ClinicId", null),
criteria.add(Restrictions.in("ClinicId", ClinicIds));
)
);
}
return criteria.list();
A: You can't. That would generate invalid SQL.
You need to change the HQL depending on whether there are ClinicIds.
A: I did it like:
"SELECT ClinicId,Name from Clinic where -1 in (:ClinicIds) OR ClinicId IN :ClinicIds"
and
if(ClinicIds == null or ClinicIds.isEmpty()){
ClinicIds = new List<int>();
ClinicIds.add(-1);
}
q.SetParameterList("ClinicIds", ClinicIds);
just a trick
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575205",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: simple SUM in T-sql This should be really simple. I am using SSMS 2008, trying to get a sum of just one column. Problem is that I currently group on this one column and also use a HAVING statement. How do I get sum of total # of records > 1? This is my T-SQL logic currently:
select count(*) as consumer_count from #consumer_initiations
group by consumer
having count(1) > 1
But this data looks like:
consumer_count
----------------
2
2
4
3
...
A: Wrap it?
SELECT SUM(consumer_count)
FROM (
select count(*) as consumer_count from #consumer_initiations
group by consumer
having count(1) > 1
) AS whatever
A: With a nested query:
select sum(consumer_count)
FROM (
select count(*) as consumer_count from #consumer_initiations
group by consumer
having count(1) > 1
) as child
A: select sum(t.consumer_count)
from (select count(*) as consumer_count
from #consumer_initiations
group by consumer
having count(1) > 1) t
A: Try:
select sum(t.consumer_count) from
(
select count(*) as consumer_count from #consumer_initiations
group by consumer
having count(1) > 1
) t
This will give you the sum of records that your original query returns. These type of queries are called nested queries.
A: Besides the wrapping in another query, you could use this:
SELECT COUNT(*) AS consumer_count
FROM #consumer_initiations AS a
WHERE EXISTS
( SELECT *
FROM #consumer_initiations AS b
WHERE b.consumer = a.consumer
AND b.PK <> a.PK -- the Primary Key of the table
)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Create/Read/Update & Delete views are not being generated I have a Race class and RaceController class. The Create/Read/Update & Delete views are not being generated when i run the app even thougn i have "def scaffold = true" in the controller class. How can I generate the Create/Read/Update & Delete files
class Race {
static hasMany = [registrations:Registration]
String name
Date startDate
String city
String state
BigDecimal distance
BigDecimal cost
Integer maxRunners = 100000
static constraints = {
name()
startDate()
city()
state()
distance()
cost()
maxRunners()
}
}
class RaceController {
def scaffold = true
}
A: That should be:
static scaffold = true
not
def scaffold = true
A: grails generate-views some.package.DomainObject
will created the physical files
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Namespace Prefixes with IXmlSerializable Bit confused on the proper decorators to use, or whatever design might be necessary. When serializing a class which is implementing IXmlSerializable is there a way to include the namespace and its prefix in the XmlRoot element?
Class definition for example.
using System;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
[XmlRoot("Classy", Namespace = XML_NS)]
public class TestClass : IXmlSerializable
{
private const string XML_PREFIX = ""; // default namespace
private const string XML_NS = "www.123.com";
private const string XML_MEMBER_PREFIX = "me";
private const string XML_MEMBER_NS = "member.com";
[XmlNamespaceDeclarations]
public XmlSerializerNamespaces xmlsn {
get {
XmlSerializerNamespaces xsn = new XmlSerializerNamespaces();
xsn.Add(XML_PREFIX, XML_NS);
xsn.Add(XML_MEMBER_PREFIX, XML_MEMBER_NS);
return xsn;
}
}
void IXmlSerializable.WriteXml(XmlWriter writer) {
writer.WriteElementString(XML_MEMBER_PREFIX, "Member1.5",
XML_MEMBER_NS, Member1);
writer.WriteElementString(XML_MEMBER_PREFIX, "Member2.5",
XML_MEMBER_NS, Member2.ToString());
writer.WriteElementString(XML_PREFIX, "Member3.5", XML_NS, Member3);
}
//[XmlElement(ElementName = "Member1.5", Namespace = XML_MEMBER_NS)]
public string Member1 {
get { return "init"; }
set { ; }
}
//[XmlElement(ElementName = "Member2.5", Namespace = XML_MEMBER_NS)]
public int Member2 {
get { return 3; }
set { ; }
}
//[XmlElement(ElementName = "Member3.5", Namespace = XML_NS)]
public string Member3 {
get { return "default namespace"; }
set { ; }
}
// ignore ReadXml/GetSchema
XmlSchema IXmlSerializable.GetSchema() { return null; }
void IXmlSerializable.ReadXml(XmlReader reader) { return; }
}
When serialized via:
TestClass tc = new TestClass();
XmlSerializer ser = new XmlSerializer(typeof(TestClass));
ser(writer, tc, tc.xmlsn); // just a plain XmlWriter to Console.Out
the output is
<?xml version="1.0" encoding="utf-8"?>
<Classy xmlns="www.123.com">
<me:Member1.5 xmlns:me="member.com">init</me:Member1.5>
<me:Member2.5 xmlns:me="member.com">3</me:Member2.5>
<Member3.5>default namespace</Member3.5>
</Classy>
The output I was expecting was:
<?xml version="1.0" encoding="utf-8"?>
<Classy xmlns:me="member.com" xmlns="www.123.com">
<me:Member1.5>init</me:Member1.5>
<me:Member2.5>3</me:Member2.5>
<Member3.5>default namespace</Member3.5>
</Classy>
The second is the output of XmlSerializer if the class's implementation of IXmlSerializable is removed and you uncomment the XmlElement decorators. I know both of the Xml documents returned are valid, but it would be nice to try and remove the redundant namespace declarations. I would assume such a thing is possible, since IXmlSerializable is meant to give greater control over how your class is serialized/deserialized.
Update: A very interesting answer suggested modifying the XmlWriterSettings! It looked like this would clear everything up by modifying the NamespaceHandling property. However this still results in the namespaces being rewritten for each member. Full serialization code below:
XmlSerializer ser = new XmlSerializer(typeof(TestClass));
TestClass tc = new TestClass();
XmlWriterSettings xmlSet = new XmlWriterSettings();
xmlSet.Encoding = System.Text.Encoding.UTF8;
xmlSet.Indent = true;
xmlSet.NamespaceHandling = NamespaceHandling.OmitDuplicates;
XmlWriter writer = XmlWriter.Create(Console.Out, xmlSet);
ser.Serialize(writer, tc); // with/without tc.xmlsn same result
writer.Flush();
writer.Close();
A: I simply added an String Attribute to WriteXml. It worked!
void IXmlSerializable.WriteXml(XmlWriter writer) {
writer.WriteAttributeString("xmlns:me", "member.com");
writer.WriteAttributeString("xmlns", "www.123.com");
writer.WriteElementString(XML_MEMBER_PREFIX, "Member1.5",
XML_MEMBER_NS, Member1);
writer.WriteElementString(XML_MEMBER_PREFIX, "Member2.5",
XML_MEMBER_NS, Member2.ToString());
writer.WriteElementString(XML_PREFIX, "Member3.5", XML_NS, Member3);
}
and remove [XmlRoot("Classy", Namespace = XML_NS)] and the xmlsn property from the class.
A: Using the WriteAttributeString as suggested is not completely correct. Here is an example on how to use it correctly:
In the WriteXml method at the beginning add something like this:
public void WriteXml(System.Xml.XmlWriter writer)
{
writer.WriteAttributeString("xmlns", "xsi", null, "http://www.w3.org/2001/XMLSchema-instance");
writer.WriteAttributeString("xmlns", "xsd", null, "http://www.w3.org/2001/XMLSchema");
}
A: You need to set XmlWriterSetting for it to work. see below pls
http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.aspx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575218",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Error while installing RVM on ubuntu 11.04. Seems to be git clone's error When I try to install RVM the following error shows up:
$ bash < <(curl -s https://rvm.beginrescueend.com/install/rvm)
Cloning into rvm...
fatal: The remote end hung up unexpectedly
Cloning into rvm...
error: RPC failed; result=56, HTTP code = 100
fatal: The remote end hung up unexpectedly
ERROR: Unable to clone the RVM repository, attempted both git:// and https://
This is a git clone error I'm getting recently. e.g When I try to clone nodejs.
error: RPC failed; result=56, HTTP code = 100
fatal: The remote end hung up unexpectedly
What is the problem?
A: It would seem you're having some sort of network issue that is preventing you
from retrieving the Git repository. The RVM script attempts to
clone the repository first using
git clone --depth 1 git://github.com/wayneeseguin/rvm.git, and if that fails,
using git clone https://github.com/wayneeseguin/rvm.git. Git uses
libcurl. The result=56 part of the RPC failed error is the
libcurl error code; 56 means Failure with receiving network data..
The HTTP code = 100 part is the HTTP server status code that
was returned to you; 100 means The client SHOULD continue with its request..
Your best bet is probably to start a network traffic sniffer
(on Ubuntu, you can use Wireshark) to see exactly what packets are
being transmitted/received on your workstation. Try installing RVM on different workstations in your network and on different networks. I did not have any issues on my machine.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How best to implement a login system in VB.NET using LINQ to compare information with an Access table? I have been requested to implement a login form into a friend's Visual Basic .NET application. He specifically requested that I should do this using LINQ to compare the input to a table in an Access database. I don't really know why he imposed these restrictions, but who am I to judge?
However, the problem is I am not overly familiar with VB .NET, or LINQ. Could anyone tell me what the most efficient way would be to implement this?
Thank you.
A: If you Google for tutorials on VB.NET and LINQ, there is lot's of information out there. Your login chec is going to work something like this with VB.Net/LINQ:
' create a re-usable helper function to validate login information
Function Shared ValidateLogin(ByVal username As String, ByVal password as String) _
As Boolean
' create LINQ context to the access database
Dim ctx As New MyDataContext
' check credentials against User table
Dim usr As User = ctx.Users.SingleOrDefault(Function(u) _
u.UserName = username AndAlso u.Password = password)
Return (usr IsNot Nothing)
End Function
*
*MyDataContext is a DataContext connected to the Access database. This can be created in Visual Studio by creating New Item -> Datacontext, then using the Server Explorer to connect to your Access database and drag/drop the tables into the DataContext.
*ctx.Users would be replaced with whatever the name of the User table is in the Access database.
*u.UserName and u.Password would be replaced with whatever the field names are in your users table for the user's login and password information
*This function could be called then from your application once you've collected the credentials, and you want to validate them. Then it's up to you to perform the appropriate response logic based on whether the login was successful or not.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575230",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I sort a column that contains two divs with jQuery Tablesorter? I'm using jQuery Tablesorter to sort a table. One of my columns looks like this:
<td>
<div>
<span class="green">Yes</span> <a href="##">(unverify)</a>
</div>
<div class="hidden">
<span class="red">No<>/a> <a href="##">(verify)</a>
</div>
</td>
In other words, there's two divs, one to show Yes in green with a link, and the other to show No in red with a link. One of the divs is always hidden, and the two are toggled whenever the user clicks on the link.
jQuery Tablesorter cannot sort on this column. Is there a way to get it to do so, or do I have to modify the HTML to get it to work?
A: You could use the textExtraction callback:
$(document).ready(function() {
// call the tablesorter plugin
$("table").tablesorter({
// define a custom text extraction function
textExtraction: function(node) {
// check you're at the right column
if ($(node).find('.green').length == 1) {
// extract data from markup and return it
return $(node).find('div:not(.hidden)').find('span').text();;
}
else {
return $(node).text();
}
}
});
});
I haven't tested that but it should work in theory
A: you'll want to look into creating a custom parser. its pretty simple, you just specify how to interpret the value in the cell by passing in a function to the format field.
A: A generic way to sort any type of column, no matter how the content is complex:
add 'sorted' attribute to the , fill 'sorted' value in the server side according to the preffered order, (which is easier than in javascript).
e.g.
<td sorter='1'>
<div>
<span class="green">Yes</span> <a href="##">(unverify)</a>
</div>
<div class="hidden">
<span class="red">No<>/a> <a href="##">(verify)</a>
</div>
</td>
<td sorter='2'>
<div class="hidden"> >
<span class="green">Yes</span> <a href="##">(unverify)</a>
</div>
<div>
<span class="red">No<>/a> <a href="##">(verify)</a>
</div>
</td>
then add the following code in $(function ()
$("table.tablesorter").tablesorter({
textExtraction: function(node){
return $(node).attr("sorter");
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: bugzilla | perl module installation nightmare: no cc, is gcc OK? I am trying to install Bugzilla. I don't recall it being so difficult. We have a ubuntu server on the cloud, and at first I attempted to install through the rackspace UI. This didn't work, so I ssh'ed in and actually downloaded the tarball to do it the old-fashioned way.
However, it appears there are three perl modules having install problems. I have tried everything I know to get them to install, and am at a loss. I've tried googling for some answers, but I am either not using the correct terminology or this is truly unique to my situation.
The three offending perl modules failing the checksetup.pl:
/usr/bin/perl install-module.pl DateTime
/usr/bin/perl install-module.pl DateTime::TimeZone
/usr/bin/perl install-module.pl Template
When I attempt to install any of them, they fail miserably, apparently because the cc compiler is not installed (see below). When I checked for a cc package under APT, I could only find gcc. Will that be sufficient, and will I need to alias gcc to cc in order for these installs to work?
/usr/bin/perl /usr/local/share/perl/5.10.1/ExtUtils/xsubpp -typemap /usr/share/perl/5.10/ExtUtils/typemap Stash.xs > Stash.xsc && mv Stash.xsc Stash.c
cc -c -D_REENTRANT -D_GNU_SOURCE -DDEBIAN -fno-strict-aliasing -pipe -fstack-protector -I/usr/local/include -D_LARGEFILE_SOURCE -D_FILE_OFFSET_BITS=64 -O2 -g -DVERSION=\"2.22\" -DXS_VERSION=\"2.22\" -fPIC "-I/usr/lib/perl/5.10/CORE" Stash.c
/bin/sh: cc: not found
make[1]: *** [Stash.o] Error 127
make[1]: Leaving directory `/root/.cpan/build/Template-Toolkit-2.22-xzQg_q/xs'
make: *** [subdirs] Error 2
ABW/Template-Toolkit-2.22.tar.gz
/usr/bin/make -- NOT OK
Skipping test because of notest pragma
Running make install
Make had returned bad status, install seems impossible
A: You shouldn't compile Perl with one compiler (cc) and then compile modules with another compiler or compiler build (gcc) unless you happen to know their compatible. I find it very hard to believe that Ubuntu provided a Perl built with a compiler they don't provide.
Then there's the issue that you're installing unmanaged modules into a distro-managed Perl. That's... less than ideal.
The simplest solution is probably:
apt-get install \
libdatetime-perl \
libdatetime-timezone-perl \
libtemplate-perl
Another solution is to install a local build of Perl, perhaps using perlbrew.
Personally, I never use the system Perl. It's there for the system's needs first (not mine), and that causes problems. In this case, since the distro does provide the packages you need, it should be fine to just install those packages.
A: I went ahead and installed the gcc package, and the installs completed. Whew. It has been a long time...
A: Just Install GCC and then Perl.To install the gcc package in the Debian/Ubuntu Linux distribution, enter the following command in a terminal:
> apt-get install gcc make linux-headers-$(uname -r)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Remote call ASP.Net Web Service from jQuery Ajax I have the following problem, there is one ASP. NET Web Service project (*. asmx), with several function and is the second project, also ASP .NET, which should call a service using jQuery Ajax (no service reference).
Web Service project:
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class MathService : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod]
public int Add(int x, int y)
{
return x + y;
}
}
and
<script type="text/javascript" src="Scripts/jquery-1.6.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "http://localhost:47204/Services/MathService.asmx/Add",
data: "{'x': '5', 'y': '10'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
$("#divMathService").text(res.d);
},
error: function () {
alert("ALARM!");
}
});
});
</script>
This - localhost:47204 - host web service project, when i debug project.
I specifically pointed out the full URL, something to use it in the client project.
Project works, everything all right.
The project client looks as follows:
<script type="text/javascript" src="Scripts/jquery-1.6.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "http://localhost:47204/Services/MathService.asmx/Add",
data: "{'x': '5', 'y': '10'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (res) {
$("#divMathService").text(res.d);
},
error: function () {
alert("ALARM!");
}
});
});
</script>
But this project don't show any result, only alert, I don't understand why. Maybe problem with permission for remote call?
I can't attach project, but can send to email if someone wants to look at the project.
A: try formatting your data as valid json first:
'{"x": 5, "y": 10}'
also, your method needs to know to send the response as json:
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public int Add(int x, int y)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575239",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Removing default.aspx from the url in ASP.NET 2005 I have a app that is setup on IIS 6.0. We are having trouble with Search Engine optimization with the default.aspx page.
For Example when I type www.xxxxxx.com/default.aspx it should redirect to www.xxxxxx.com.
Can anyone please help me with this problem?
A: public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
if (HttpContext.Current.Request.RawUrl == "/default.aspx")
{
Response.StatusCode = 301;
Response.Status = "301 Moved Permanently";
Response.RedirectLocation = "/";
Response.End();
}
}
}
}
A: Set the default document in IIS under the Documents tab. Once in the Documents tab, check "Enable default content page" and set Default.aspx as the first item (or only) in the list.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Getting random contact numbers in Android I'm trying to use the following code to grab a random mobile phone number from the contacts:
ContentResolver cr = getContentResolver();
Cursor cursor = cr.query(ContactsContract.Contacts.CONTENT_URI, null, "DISPLAY_NAME = '" + "NAME" + "'", null, null);
cursor.moveToFirst();
String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
Cursor phones = cr.query(Phone.CONTENT_URI, null, Phone.CONTACT_ID + " = " + contactId, null, null);
List numbers = new ArrayList();
while (phones.moveToNext()) {
String number = phones.getString(phones.getColumnIndex(Phone.NUMBER));
int type = phones.getInt(phones.getColumnIndex(Phone.TYPE));
switch (type) {
case Phone.TYPE_MOBILE:
numbers.add(number);
break;
}
}
Random randGen = new Random();
return (String) numbers.get(randGen.nextInt(numbers.size()));
However, running this code produces a crash on line 4, with a message saying "CursorIndexOutOfBoundsException: Index 0 requested, with a size of 0". The crash seems to be caused by the cursor.getString() method. Does anyone know where I'm going wrong? This is using the ContactsContract in Android 2.1. Eclipse gives no errors.
Thanks!
A: The moveToFirst() method returns a boolean. It returns true if it was able to move to the first row and false otherwise, indicating that the query returned an empty set.
When using a cursor, you should follow something like:
if (cursor.moveToFirst()) {
do {
// do some stuff
} while (cursor.moveToNext());
}
cursor.close();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575245",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Variables not expanded in Maven plugin In my maven plugin I have the following:
<dependencySets>
<dependencySet>
<scope>runtime</scope>
<outputDirectory>/dir/${project.parent.artifactId}-${project.version}/${project.artifactId}/lib</outputDirectory>
</dependencySet>
</dependencySets>
When mvn clean package is run, the outputDirectory is literally dir/${project.parent.artifactId}-${project.version}/... That is, the variables aren't being expanded. I am not getting any kind of variable not found message (nor should I). What could cause variables not to be expanded?
A: Can you check if the following works? Essentially, removing the project prefix from the variable names, since maven2 is not strict about this.
<outputDirectory>/dir/${parent.artifactId}-${version}/${artifactId}/lib</outputDirectory>
You may also want to check if you are using the last maven assembly plugin
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575249",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Resize panel to fit contained elements in windows forms I am creating a collapsible panel element, which would essentially be a panel element with a button element and a panel element below the button. Clicking the button causes the neighboring panel to have Visible = false. I would like to resize the containing panel when the child panel is set to invisible.
I have done this manually, by setting the Size property to be the sum of the widths and heights of the visible elements (either the button or the button and the child panel.)
I am curious to know though if there was a way to force the resize of the containing panel without manually calling Size.
I guess I'm looking for the inverse of the property Dock=Fill, which automatically resizes elements based on the size of their containing element.
Thanks in advance.
A: I just tried the answer given by ispiro. You dont need to remove and add the control. Setting Visible can work. It depends on when you perform the layout. If panel2 performs the layout before panel1, panel2 will not resize. To make it easier, use the parents PerformLayout instead.
It's used like this:
panel1.ResumeLayout(false);
panel2.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
A: How about doing:
panel1.Size = new Size(0, 0);
panel1.AutoSize = true;
and then instead of changing the visibility, do this:
panel1.Controls.Remove(panel2);
and when you want to bring it back:
panel1.Controls.Add(panel2);
(panel1 is the back-panel)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575252",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: SISS Variables - I have created user defined SSIS variables at the package level.
Example: Here are the varibales
v1 = 10
v2 = 20
v3
The result should be V3 = V1 +V2 Where should i give this expression in the control flow and will i get the result
Please help
Thanks
A: Am I missing something or is there a reason an expression won't suffice?
Given variables defined as described above
Set "Evaluate as Expression" to True on the variable v3 and for the Expression, use @[User::v1] + @[User::v2] (or click the ellipses and build the expression with the WYSIWYG editor)
If you notice the pink corner of v3, that is due to me running an add-in called BIDSHelper which can assist in your SSIS development tasks but in no way affects the workings of my solution.
A: You can manipulate variables within a Script Component. If you're using SQL-Server 2005 you get to use VB.Net, if you're using 2008, you have the choice of that or C#.net.
Here are some (VB.net) examples of code I've used to get variables (strings in my case), manipulate them, and send them back to the variable storage area:
Dim logFilename As String
Dim logFilePath As String
' create filename
logFilePath = Dts.Variables("LogFilePath").Value.ToString()
curDate = Now().ToString("yyyyMMdd")
logFilename = "test-" & curDate & ".Log"
Dts.Variables("LogFileName").Value = logFilename
To do the same with your numbers, in the guts of the Script Component (I'm a bit rusty with VB)
Dim v1 as Int
Dim v2 as Int
Dim v3 as Int
// get your variables from the package
v1 = Dts.Variables("v1").Value
v2 = Dts.Varuables("V2").Value
v3 = v1 + v2
// set your result back to the package
Dts.Variables ("v3").Value = v3
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575259",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Google Analytics Data Feed API Error 414 URI Too Large When using the google analytics data API with the python gdata library, we are assembling a GET request per the instructions in the documentation here: http://code.google.com/apis/analytics/docs/gdata/gdataReferenceDataFeed.html
We are running into problems however. As our requests get longer, we're occasionally getting a 414 error URI Too Large when we have a lot of filters.
Is there any way to use a POST request with the gdata API or otherwise get around the 414?
EDIT: Just tried using a POST request and get 403 Target feed is read-only. Is there any way around this restriction?
A: There is a 128 character limit on filters regardless of whether you're using GET or POST. Anything longer than that will result in a 400 error. The only way around that length limit is to use AND/OR boolean logic.
Here's the full explanation from Google:
Rules for Filter Expressions
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575263",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: SWT needs to much lines of code I wondering why swt is so inconvenient to use. We as programmers have to produce tons of unnecessary source code. Here an example.
Label label = new Label(parent, SWT.NONE);
label.setText("labelname");
The minimum would be like this:
createLabel(parent, "labelname");
I build up a convenients library and I would like to know if there is something similar or why SWT or JFace don't go this simple way. Is there any drawback in having some more constructors that cover 80% of the programming task.
Have a more detailed look what I have done.
SWT: More Convenients Please
A: I suggest trying Google Window Builder Pro. It is a plugin for Eclipse that allows for the graphical development of GUI's in SWT, Swing, RCP, JFace and others. GWB writes the code which specifies the GUI layout and all you must do is write code to handle events.
A: As far as I know there is no such generic library. The one instance which provides some basic factory support for swt control creation is JFace Form Widget. Also have a look at this org.eclipse.ui.forms.widgets.FormToolkit.
From your implementation it appears that you are assuming the GridLayout as the default layouting style. Apart from that a control may have many layout related data like, its indentation (horizontal and vertical), span etc. Which is not easy to cover with factory methods.
If you don't want to put in the extra effort of writing the code for layouting the widgets and all then have a look at the Visual editor at http://www.eclipse.org/archived/.
Also, eclipse itself is moving towards the the Model Driven Generation (http://www.eclipse.org/e4/). It won't be a wonder if we will see a Netbeans like UI designer for SWT (by the way i have written a version for our tool using eclipse modelling framework and GEF).
Still I would suggest you to write the mundane layouting code by hand because it will improve your SWT understanding.
A: Bytes are very cheap to produce, and I'd debate that SWT "is so inconvenient to use" - well if it's automatically producing it, how is that inconvenient ?
Our computers are so fast that we couldn't even perceive the difference... and time saved is huge.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Extract data from log file in specified range of time I want to extract information from a log file using a shell script (bash) based on time range. A line in the log file looks like this:
172.16.0.3 - - [31/Mar/2002:19:30:41 +0200] "GET / HTTP/1.1" 200 123 "" "Mozilla/5.0 (compatible; Konqueror/2.2.2-2; Linux)"
i want to extract data specific intervals. For example I need to look only at the events which happened during the last X minutes or X days ago from the last recorded data. I'm new in shell scripting but i have tried to use grep command.
A: well, I have spent some time on your date format.....
however, finally i worked it out..
let's take an example file (named logFile), i made it a bit short.
say, you want to get last 5 mins' log in this file:
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:20:41 +0200] "GET
### lines below are what you want (5 mins till the last record)
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:27:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:30:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:30:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:30:41 +0200] "GET
172.16.0.3 - - [31/Mar/2002:19:30:41 +0200] "GET
here is the solution:
# this variable you could customize, important is convert to seconds.
# e.g 5days=$((5*24*3600))
x=$((5*60)) #here we take 5 mins as example
# this line get the timestamp in seconds of last line of your logfile
last=$(tail -n1 logFile|awk -F'[][]' '{ gsub(/\//," ",$2); sub(/:/," ",$2); "date +%s -d \""$2"\""|getline d; print d;}' )
#this awk will give you lines you needs:
awk -F'[][]' -v last=$last -v x=$x '{ gsub(/\//," ",$2); sub(/:/," ",$2); "date +%s -d \""$2"\""|getline d; if (last-d<=x)print $0 }' logFile
output:
172.16.0.3 - - 31 Mar 2002 19:27:41 +0200 "GET
172.16.0.3 - - 31 Mar 2002 19:27:41 +0200 "GET
172.16.0.3 - - 31 Mar 2002 19:27:41 +0200 "GET
172.16.0.3 - - 31 Mar 2002 19:27:41 +0200 "GET
172.16.0.3 - - 31 Mar 2002 19:27:41 +0200 "GET
172.16.0.3 - - 31 Mar 2002 19:27:41 +0200 "GET
172.16.0.3 - - 31 Mar 2002 19:27:41 +0200 "GET
172.16.0.3 - - 31 Mar 2002 19:27:41 +0200 "GET
172.16.0.3 - - 31 Mar 2002 19:27:41 +0200 "GET
172.16.0.3 - - 31 Mar 2002 19:27:41 +0200 "GET
172.16.0.3 - - 31 Mar 2002 19:27:41 +0200 "GET
172.16.0.3 - - 31 Mar 2002 19:27:41 +0200 "GET
172.16.0.3 - - 31 Mar 2002 19:27:41 +0200 "GET
172.16.0.3 - - 31 Mar 2002 19:27:41 +0200 "GET
172.16.0.3 - - 31 Mar 2002 19:30:41 +0200 "GET
172.16.0.3 - - 31 Mar 2002 19:30:41 +0200 "GET
172.16.0.3 - - 31 Mar 2002 19:30:41 +0200 "GET
172.16.0.3 - - 31 Mar 2002 19:30:41 +0200 "GET
EDIT
you may notice that in the output the [ and ] are disappeared. If you do want them back, you can change the last awk line print $0 -> print $1 "[" $2 "]" $3
A: You can use sed for this. For example:
$ sed -n '/Feb 23 13:55/,/Feb 23 14:00/p' /var/log/mail.log
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: connect from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: lost connection after CONNECT from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie postfix/smtpd[20964]: disconnect from localhost[127.0.0.1]
Feb 23 13:55:01 messagerie pop3d: Connection, ip=[::ffff:127.0.0.1]
...
How it works
The -n switch tells sed to not output each line of the file it reads (default behaviour).
The last p after the regular expressions tells it to print lines that match the preceding expression.
The expression '/pattern1/,/pattern2/' will print everything that is between first pattern and second pattern. In this case it will print every line it finds between the string Feb 23 13:55 and the string Feb 23 14:00.
More info here
A: I used this command to find last 5 minutes logs for particular event "DHCPACK", try below:
$ grep "DHCPACK" /var/log/messages | grep "$(date +%h\ %d) [$(date --date='5 min ago' %H)-$(date +%H)]:*:*"
A: Use grep and regular expressions, for example if you want 4 minutes interval of logs:
grep "31/Mar/2002:19:3[1-5]" logfile
will return all logs lines between 19:31 and 19:35 on 31/Mar/2002.
Supposing you need the last 5 days starting from today 27/Sep/2011 you may use the following:
grep "2[3-7]/Sep/2011" logfile
A: You can use this for getting current and log times:
#!/bin/bash
log="log_file_name"
while read line
do
current_hours=`date | awk 'BEGIN{FS="[ :]+"}; {print $4}'`
current_minutes=`date | awk 'BEGIN{FS="[ :]+"}; {print $5}'`
current_seconds=`date | awk 'BEGIN{FS="[ :]+"}; {print $6}'`
log_file_hours=`echo $line | awk 'BEGIN{FS="[ [/:]+"}; {print $7}'`
log_file_minutes=`echo $line | awk 'BEGIN{FS="[ [/:]+"}; {print $8}'`
log_file_seconds=`echo $line | awk 'BEGIN{FS="[ [/:]+"}; {print $9}'`
done < $log
And compare log_file_* and current_* variables.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "39"
}
|
Q: Absolutely bizarre appendTo problem in IE 8 The following code works great in almost everything (variable names changed):
this.$something.appendTo($container);
But in IE8, it was just... not doing the append. No error. No warning. Not a whimper. Through sheer luck, we found something that worked for no discernable reason:
$('<div class="hideme">ihateIE</div>').appendTo($('body')).remove();
this.$something.appendTo($container);
It's not a timing issue - there's no setTimeout involved and all the variables are either created right then or have been around for a while. And it works no matter what you append, no matter where you append it to, as long as you append SOMETHING to SOMETHING.
Why, why, why, why, why? I hate leaving this hack in my code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575273",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: find url in html code I want tu find url in html code with PHP or JS
e.g i have this text
<description>
<![CDATA[<p>
<img" src="http://2010.pcnews.am/images/stories/2011/internet/chinese-computer-user-smoke.jpg" border="0" align="left" "/>
Երեկ Պեկինի ինտերնետ-սրճարաններից մեկում մահացել է 33-ամյա մի չինացի, ով 27 օր շարունակ անցկացրել էր համակարգչի առաջ: Հաղորդում է չինական «Ցյանլունվան» պարբերականը:</p>
<p>Աշխատանք չունեցող չինացին մեկ ամիս շարունակ չի լքել ինտերնետ-սրճարանը ՝ այդ ամբողջ ընթացքում սնվելով արագ պատրաստվող մակարոնով:</p>
<p />
Նույնիսկ ամանորյա տոները նա անցկացրել է համակարգչի առաջ. Պեկինի բնակիչները նշում են Նոր տարին Լուսնային օրացույցով՝ փետրվարի 3-8-ը: Մահվան պատճառները չեն հաղորդվում:
]]>
</description>
i want take only "http://2010.pcnews.am/images/stories/2011/internet/chinese-computer-user-smoke.jpg" ,
Thank in advance
A: This is a rather complicated task and while regex may seem easier, it is far too problematic. The following code will go through an XML file (called some.xml, but you’ll obviously need to change that) and gather the image sources into an array, $images.
$images = array();
$doc = new DOMDocument();
$doc->load('some.xml');
$descriptions = $doc->getElementsByTagName("description");
foreach ($descriptions as $description) {
foreach($description->childNodes as $child) {
if ($child->nodeType == XML_CDATA_SECTION_NODE) {
$html = new DOMDocument();
@$html->loadHTML($child->textContent);
$imgs = $html->getElementsByTagName('img');
foreach($imgs as $img) {
$images[] = $img->getAttribute('src');
}
}
}
}
I tested it against the XML you supplied an got the following result:
Array
(
[0] => http://2010.pcnews.am/images/stories/2011/internet/chinese-computer-user-smoke.jpg
)
I put it into an array in case there is more than one description with images.
A: You can use javascript or jQuery to get the image's src attribute.
document.getElementsByTag("img")[x].src
A: Use regex to find content between src=" and preceding "
A: In php could be done like this:
<?php
$txt = 'text here <img src="http://domain.com/something.png" border="0" align="left" "/> more
test and <em>html</em> around here
<p> thats it </p>';
preg_match('/src="([^"]*)"/', $txt, $matches);
var_dump($matches[1]);
?>
A: Regular expressions are brittle for text parsing and do not take advantage of the document's inherent structure. Using RegEx to find stuff in a marked up document is generally a poor practice.
Use PHP's built in DOMNode and DOMXPath instead.
|
{
"language": "hy",
"url": "https://stackoverflow.com/questions/7575274",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Ant xslt task output to stdout Using the <xslt> task in ant, how do I get the output to generate to stdout?
My XSLT is generating multiple files through xsl:result-document and the normal output is just status information that I'd like to show up with normal Ant output. Ant seems to force me to supply a destdir= or an out= parameter.
Ant 1.8.2 with Saxon 9
A: Yes ant does this. However XSLT has the element which you can use to get output on the stdout :)
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform" version="1.0">
<xsl:output method="xml" indent="yes"/>
<xsl:key name="types" match="a" use="text()"/>
<xsl:template match="/">
<result>
<xsl:message terminate="no">I am a message from xslt!</xsl:message>
</result>
</xsl:template>
</xsl:stylesheet>
Output :
build:
[xslt] Processing C:\Users\Stefanos\Documents\Visual Studio 2010\Projects\stackOverflow\stackOverflow\test.xml to C:\Users\Stefanos\Documents\Vis
ual Studio 2010\Projects\stackOverflow\stackOverflow\out.xml
[xslt] Loading stylesheet C:\Users\Stefanos\Documents\Visual Studio 2010\Projects\stackOverflow\stackOverflow\test.xslt
[xslt] I am a message from xslt!
BUILD SUCCESSFUL
Total time: 0 seconds
Hope it helps!
A: I recently had a similar scenario; an Ant script with an XSLT task where the style sheet transform generated multiple files using <xsl:result-document>. Since the Ant XSLT task requires the destdir attribute (unless the out attribute has been specified), I used known temp file(s) for the out destination and then implemented a “cleanup” task which deleted the temp file(s).
<target name="removeTemporaryFiles" description="remove temporary files">
<delete file="${workspace}/temp.xhtml"></delete>
…
</target>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575283",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: check output from CalledProcessError I am using subprocess.check_output from pythons subprocess module to execute a ping command. Here is how I am doing it:
output = subprocess.check_output(["ping","-c 2 -W 2","1.1.1.1")
It is raising a CalledProcessError and says the output is one of the arguments of the function. Can anyone help me how to read that output. I would like to read the output into a string and parse it. So say for example if the ping returns
100% packet loss
I need to capture that. If there is any other better way..please suggest. Thanks.
A: If you want to get stdout and stderr back (including extracting it from the CalledProcessError in the event that one occurs), use the following:
import subprocess
def call_with_output(command):
success = False
try:
output = subprocess.check_output(command, stderr=subprocess.STDOUT).decode()
success = True
except subprocess.CalledProcessError as e:
output = e.output.decode()
except Exception as e:
# check_call can raise other exceptions, such as FileNotFoundError
output = str(e)
return(success, output)
call_with_output(["ls", "-l"])
This is Python 2 and 3 compatible.
If your command is a string rather than an array, prefix this with:
import shlex
call_with_output(shlex.split(command))
A: In the list of arguments, each entry must be on its own. Using
output = subprocess.check_output(["ping", "-c","2", "-W","2", "1.1.1.1"])
should fix your problem.
A: I ran into the same problem and found that the documentation has example for this type of scenario (where we write STDERR TO STDOUT and always exit successfully with return code 0) without causing/catching an exception.
output = subprocess.check_output("ping -c 2 -W 2 1.1.1.1; exit 0", stderr=subprocess.STDOUT, shell=True)
Now, you can use standard string function find to check the output string output.
A: According to the Python os module documentation os.popen has been deprecated since Python 2.6.
I think the solution for modern Python is to use check_output() from the subprocess module.
From the subprocess Python documentation:
subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)
Run command with arguments and return its output as a byte string.
If the return code was non-zero it raises a CalledProcessError. The CalledProcessError object will have the return code in the returncode attribute and any output in the output attribute.
If you run through the following code in Python 2.7 (or later):
import subprocess
try:
print subprocess.check_output(["ping", "-n", "2", "-w", "2", "1.1.1.1"])
except subprocess.CalledProcessError, e:
print "Ping stdout output:\n", e.output
You should see an output that looks something like this:
Ping stdout output:
Pinging 1.1.1.1 with 32 bytes of data:
Request timed out.
Request timed out.
Ping statistics for 1.1.1.1:
Packets: Sent = 2, Received = 0, Lost = 2 (100% loss),
The e.output string can be parsed to suit the OPs needs.
If you want the returncode or other attributes, they are in CalledProccessError as can be seen by stepping through with pdb
(Pdb)!dir(e)
['__class__', '__delattr__', '__dict__', '__doc__', '__format__',
'__getattribute__', '__getitem__', '__getslice__', '__hash__', '__init__',
'__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__',
'__setattr__', '__setstate__', '__sizeof__', '__str__', '__subclasshook__',
'__unicode__', '__weakref__', 'args', 'cmd', 'message', 'output', 'returncode']
A: Thanx @krd, I am using your error catch process, but had to update the print and except statements. I am using Python 2.7.6 on Linux Mint 17.2.
Also, it was unclear where the output string was coming from.
My update:
import subprocess
# Output returned in error handler
try:
print("Ping stdout output on success:\n" +
subprocess.check_output(["ping", "-c", "2", "-w", "2", "1.1.1.1"]))
except subprocess.CalledProcessError as e:
print("Ping stdout output on error:\n" + e.output)
# Output returned normally
try:
print("Ping stdout output on success:\n" +
subprocess.check_output(["ping", "-c", "2", "-w", "2", "8.8.8.8"]))
except subprocess.CalledProcessError as e:
print("Ping stdout output on error:\n" + e.output)
I see an output like this:
Ping stdout output on error:
PING 1.1.1.1 (1.1.1.1) 56(84) bytes of data.
--- 1.1.1.1 ping statistics ---
2 packets transmitted, 0 received, 100% packet loss, time 1007ms
Ping stdout output on success:
PING 8.8.8.8 (8.8.8.8) 56(84) bytes of data.
64 bytes from 8.8.8.8: icmp_seq=1 ttl=59 time=37.8 ms
64 bytes from 8.8.8.8: icmp_seq=2 ttl=59 time=38.8 ms
--- 8.8.8.8 ping statistics ---
2 packets transmitted, 2 received, 0% packet loss, time 1001ms
rtt min/avg/max/mdev = 37.840/38.321/38.802/0.481 ms
A: This will return true only if host responds to ping. Works on windows and linux
def ping(host):
"""
Returns True if host (str) responds to a ping request.
NB on windows ping returns true for success and host unreachable
"""
param = '-n' if platform.system().lower()=='windows' else '-c'
result = False
try:
out = subprocess.check_output(['ping', param, '1', host])
#ping exit code 0
if 'Reply from {}'.format(host) in str(out):
result = True
except subprocess.CalledProcessError:
#ping exit code not 0
result = False
#print(str(out))
return result
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575284",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "55"
}
|
Q: Numeric text box with MVVM Pattern I have seen implementations of numeric TextBox with code behind in WPF. How do we do this in MVVM pattern?
A: In WPF if you bind the TextBox to a Decimal or a Int Property it will accept only that int or decimal otherwise it will show a red border that it does not have proper value in the binding. And if you are talking about the numeric updown textbox then it is readily available with WPF toolkit over here
A: honestly - what does MVVM and numeric textbox have in common?
if you want a numeric textbox you create a new TextBox or AttachedProperty or a Behaviour.
Here is an example for a MaskedTextbox behaviour to see what i mean.
now to your MVVM part. i assume that you want to validate your input to be just numeric. if your viewmodel has an Property of type int, then your binding just works if your view got input which is convertable to int. otherwise your viewmodel will never be informed. there are 2 ways now:
first: you make sure that your view just can take numeric input (with your numeric textbox) and the viewmodel property can be int.
or second: your viewmodel property type is typeof string and you use IDataErrorInfo to let the view know when the input is not numeric.
A: By the standard definition of MVVM you would not want a ViewModel behind a custom control. All you should do is extend the TextBox control and ensure only numeric input is entered. You should also add a DependencyProperty that returns the numeric input.
The ViewModel would come in when that control is used in a window or a composite control. You would bind the Text or Numeric DependencyProperty to a public property in your ViewModel.
A: Well... if you want to be notified in your viewmodel when the text property of the numeric textbox changes just bind to it. If the .Text property of the numeric textbox is not a dependency property slap the coder!
this one: http://wpftoolkit.codeplex.com/wikipage?title=DecimalUpDown&referringTitle=Home
I can recommend and you can bind to it from the viewmodel via:
<!-- View: -->
<NumericTextBox Text="{Binding MyViewModelTextStringProperty}" />
//ViewModel:
public string MyViewModelTextStringProperty
{
get/set with NotifyPropertyChanged....
}
A: If you really wanted to do this in the ViewModel, you'd have to make your bound property a string. Ensure that the binding updates at each keystroke (using the UpdateSourceTrigger).
In your setter, reject non-numeric values by either raising an exception or trimming out non-numerical characters. The latter approach has the benefit of working for copy/paste operations where the pasted text may contain a mix of digits and letters, but only the digits must be retained.
That being said, I would agree with other suggestions that having a specialized control that only exposes a numeric property is a cleaner approach.
Regards,
Eric.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575286",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Dynamic background image change possible? Hey lets say i got two links on my page and i have some sub links(show up when main link clicked). Those two links have different background image.
*link1
-link1underlinkone
-link1underlinktwo
*link2
-link2underlinkone
-link2underlinktwo
-link2underlinkthree
I can easily change background image on those two main links, but how should i pass same background style to my under-links? And underunder-links if i would have any?
edit: woops forgot to tell i want change background image of BODY not the link/links ;)
A: You should try putting both the main links in seperate div's with their sub-links. Set the background on the div (set display to none so it is invisible), and then set the background on all the links to inherit, so they take the background from their parent div.
Edit: Use the code I made below
<head>
<style type="text/css">
#link1wrapper {
background-image: url(background1.jpg);
visiblity:hidden;
}
#link2wrapper {
background-image: url(background2.jpg);
visiblity:hidden;
}
.linkmenu a{
background-image: inherit;
visibility: visible;
}
</style>
</head>
<body>
<div id="link1wrapper" class="linkmenu">
*link1
-link1underlinkone
-link1underlinktwo
</div>
<div id="link2wrapper" class="linkmenu">
*link2
-link2underlinkone
-link2underlinktwo
-link2underlinkthree
</div>
</body>
Edit: I fixed the code. Now, it puts a background on the div's and hides the div's, then I set the links in the div's to visible and voila, all the links have inherited it's background. The things you should be aware of are not to put anything else in the div's. If you do, you have to style them to set them to visible and set their background to none.
That's all I could come up with based on the very limited information you have given me. You didn't use any code, any examples, or any references, so it's very hard to answer your question accurately.
I better get an upvote for this one =p
A: Guessing you want to make a proper menu structure here is a little demo I made.
http://jsfiddle.net/sg3s/fPu9S/
The two key properties used are background-image: inherit and visibility: hidden.
background-image: inherit will make the element inherit properties from its direct parent, if no image is specified this means no properties will be inherited. Due to this we need to make the ul for the sublinks / menu inherit the properties from its parent too... Then we mask this image on the ul using visibility: hidden and since visibility default setting is inherit we need to make the lis visible again with visibility:visible.
So thats the explanation of what is actually going on. inheriting the styles can't be used together with the anchor tags unless you nest the sub links inside the main anchors and I don't think that is even valid or accepted code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575291",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Running heroku rake db:migrate from a Jenkins build fails In my Jenkins build, the last step is to push to heroku and run a db migration. The git push works fine, and the app gets deployed, but I'm having trouble running a db migration. Below is the console output from Jenkins.
+ heroku run rake db:migrate --app myapp
Running rake db:migrate attached to terminal... stty: standard input: Invalid argument
up, run.6
stty: standard input: Invalid argument
If I run the same command from the server as the jenkins user, it works fine. I only get the error during the automated build process.
As background, this is a Rails 3.1 app running on Heroku Cedar.
A: I was able to work around this by redirecting the output.
heroku run rake db:migrate --app myapp > rake.log
cat rake.log
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575295",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Where is the JobScape preference file located? Is there a configuration file for JobScape where I can specify which jobs to load on startup, the refresh interval etc?
A: Apparently JobScape that comes with AutoSys 4.5 has no user preference file. You can not specify default values for job specific parameters that you see from the View menu (like what jobs to load on startup, the view levels etc). But there is a preference file for X-Windows resources that you can manually edit to specify default values for X-Windows parameters that you see from the Options menu (like auto reload, refresh interval etc.) In Solaris this file is /usr/openwin/lib/app-defaults/Xpert
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Static library debug symbols In VS2010 there is an option to generate debug info for exes/dlls under linker but no such option under librarian for libs. Is the debug info embedded in the static library?
There is an option in the C/C++ properties for Program Database File Name for libs, exes, and dlls. By default it goes into my intermediate directory and is named the project name for libs, but is named vc$(PlatformToolsetVersion).pdb for exes/dlls. What's the pdb from this option and how does it differ from the pdb in the linker option?
If I am supplying a library with libs and headers how do I supply debug symbols to a user of my library?
A: If you use /ZI or /Zi (C/C++ -> General -> Debug Information Format), then the vc$(PlatformToolsetVersion).pdb is created, which contains the debug info for all of the .obj files created. If alternately you use /Z7, the debug info will be embedded into the .obj file, and then embedded into the .lib. This is probably the easiest way to distribute the debug info for a static library.
I wouldn't advise distributing a static library, however, since it's generally tied to a specific version of the compiler.
A: Static libraries are implemented into the programs that use them.
If the program that uses them is using debug symbols, the compiled library code in that program will have symbols too.
PDB info from wikipedia:
When debug symbols are embedded in the binary itself, the file can
then grow significantly larger (sometimes by several megabytes). To
avoid this extra size, modern compilers and early mainframe debugging
systems output the symbolic information into a separate file; for
Microsoft compilers, this file is called a PDB file.
A: Expanding upon previous answers, for those who need the full how-to (VS 2013 minimum).
Note that this should address comments ^^above regarding VS2013 issues.
Method 1: The Program Database (.pdb) Way (/Zi or /ZI)
*
*Static Lib Project: Generate a pdb with same name as your static lib:
*
*Open Solution Explorer from the View menu.
*Right click your static lib project, select Properties
*Edit Configuration Properties->C/C++->General->Debug Information to /Zi or /ZI
*
*Note that /ZI allows "Edit and Continue" editing during debugging
*Edit Configuration Properties->C/C++->Output Files->Program Database File Name to $(OutDir)$(TargetName).pdb
*Now compile it, and note where YourLib.lib and YourLib.pdb are.
*Application Project: Link your executable with the static lib, and new PDB file:
*
*Again, navigate to project properties, but this time, for your Application project
*Again, edit Debug Information property as needed.
*Edit Configuration Properties->Linker->General->Additional Library Directories, adding your own "libs" directory, or whatever directory you plan to keep/copy your YourLib.lib and YourLib.pdb files.
*Edit Configuration Properties->Linker->Input->Additional Dependencies, adding YourLib.lib (no path in front)
*Now copy both YourLib.lib and YourLib.pdb to the directory you specified above.
Method 2: The Embedded Symbols (no .pdb) Way (/Z7)
*
*Static Lib Project: Generate a static lib with embedded debug symbols
*
*As in Method 1, navigate to project properties
*As in Method 1, modify your Debug Information, but this time to/Z7
*As in Method 1, compile and note where YourLib.lib is generated.
*Application Project: Link you executable with the static lib
*
*As in Method 1, navigate to project properties
*As in Method 1, modify your Debug Information property as needed
*As in Method 1, edit Additional Library Directories
*As in Method 1, edit Additional Dependencies
*Now copy YourLib.lib to the directory specified in Additional Library Directories
Discussion:
*
*Advantages of Z7? It's simpler, and the "Single-file" way of doing it. All the debug info is in the lib file.
*Disadvantages of Z7? File size on-disk, link times, incompatible with "Minimal rebuild" (/Gm) feature, does not allow "Edit and Continue", older format (e.g. older paradigm)
*Why don't I specify Debug Information Setting for Application Project? This post is concerned with how to get debug working in static lib code. The same "Method 1 vs Method 2" choice applies for the Application project as well.
A: I notice in VS2013 it is possible to set the program database file name in the C/C++ Output Files tab. Changing it from the default to something like $(OutDir)$(TargetName).pdb resolves the issue
A: Weird behavior in VS2012. Building from scratch (or with /A option in nmake) will produce a .pdb file. Now delete the .lib and .pdb and rerun nmake (without /A of course, to run only link) and no .pdb file is output.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575298",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "74"
}
|
Q: Changing stylesheet causes qlabel to move I have a few labels in a horizontal layout, and I want to enable/disable a border around the labels at certain times. I can do this using stylesheets, but the problem is that every time I enable/disable a border this way, the label shifts left or right in the layout by a few pixels.
This is an annoying artifact that takes away from the look of the UI. Does anyone know how to prevent this from happening?
Thanks!
Marlon
A: If your labels are on a plain background, then don't enable/disable the borders, just change the border colour to match the background.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575299",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Practical: deployment of application with .sql files I am developing an application that will make heavy use of .sql files. While I am just at the beginning of development, I want to make sure I am going in the right direction to avoid re-coding later. Much like java source code is not meant for the end user to be seen, neither are .sql files and commands. My main goal is to hide them from the end user. My approach is as follows, and I am seeking alternative approaches and suggestions:
Write a small program that loops through all .sql files in a directory and stores the contents into a java.util.map using bufferedInputStream. The Map will be constructed with = new HashMap(, ). (I believe this is correct syntax). The key will be the .sql file name and value will be the .sql file contents. Then, serialize the Map object into a single file (say "SQLBin.bin") using ObjectOutputStream. Place the SQLBin.bin file into the resources folder of the main project and then use .getResourceAsStream() to access it and recreate a Map object in the main application. This will then allow me to access the SQL commands by simply referring to the .sql file by name in the Map object.
PS: I am relatively new to java. So please be extra clear.
A: You have an interesting technique; however, it is not clear what problem you intend to solve.
If you want to hide the SQL from the end user, you don't need to do all of this; just embed the SQL into a statement "string array" in a class and be done with it. But even such a solution might not be desirable depending on the true problem you are attempting to solve.
Also, some places really want to look at your SQL, because a database server isn't like a JVM. Your SQL can impact the correct operation of other mission critical programs. SQL servers may require manual configuration to grant you access. SQL servers may be monitored 24 / 7 for conditions that lead to excessive memory consumption or excessive use of CPU cycles. Professionals might rewrite your statements or tune the server to better accommodate unforeseen issues.
With a JVM the resource is less of a shared resource, and thus there's less potential for damage, in the worst case, you kill the offending JVM process, which rarely impacts the other processes that weren't explicitly written to integrate with yours.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MySql table with not sequential id Is there a way to create a table in MySql that it has an automatic ID field, but the ID is not sequential. For example, a random or pseudo random ID.
I have found solutions that suggest generating an ID and try to insert it until an unused ID is found (generating an sequential five digit alphanumerical ID).
but nothing that can be done directly in the table definition, or a simpler trick.
A: Since you asked for a trick, you could use a common auto_incremented id and "fake" it by multiplying with a big prime (and then modulo 2^32):
CREATE TABLE AutoIncPrime
(id int unsigned auto_increment primary key
) ;
Insert values, from 1 to 10:
INSERT INTO AutoIncPrime
VALUES (),(),(),(),(),(),(),(),(),() ;
SELECT * FROM AutoIncPrime ;
Output:
id
---
1
2
3
4
5
6
7
8
9
10
Fake the id, with a View:
CREATE VIEW AutoIncPrime_v AS
SELECT
((id*1798672429 ) & 0xFFFFFFFF)
AS FakeUUID
FROM AutoIncPrime ;
Lets see our "UUIDs":
SELECT * FROM AutoIncPrime_v ;
Output:
FakeUUID
----------
1798672429
3597344858
1101049991
2899722420
403427553
2202099982
4000772411
1504477544
3303149973
806855106
You could even make it look more random with (more complicated bit mixing):
CREATE VIEW AutoIncPrime_v2 AS
SELECT
( (((id*1798672429 ) & 0x55555555) << 1)
| (((id*1798672429 ) & 0xAAAAAAAA) >> 1)
)
AS FakeUUID
FROM AutoIncPrime ;
SELECT * FROM AutoIncPrime_v2 ;
FakeUUID
----------
2537185310
3918991525
2186309707
1558806648
604496082
1132630541
3719950903
2791064212
3369149034
808145601
The trick is that you still have a sequential id in the table - which you can use to join to other tables. You just don't show it to the users - but only show the fake one.
If the table is to get big and the calculations slow, you can add another column in the table and store the FakeUUID value there with an INSERT trigger.
A: Would a composite key work? A regular standard auto_increment field. You insert your new record, retrieve its new ID, then hash that ID with a salt, and update the record with that hash value.
If you do this all within a transaction, the in-progress version of the record without the hash will never be visible until the hash is generated. And assuming you've done proper salting, the resulting hash value will be for all intents and purposes 'random'.
Note that you can't do this in a single step, as the value of last_insert_id() in mysql is not updated with the new id until the record is actually written. The value retrieved during the actual insert parseing stage would be whatever id was inserted BEFORE this one.
A: MySQL has a native function UUID() which will generate a globally unique identifier:
mysql> SELECT UUID();
-> '6ccd780c-baba-1026-9564-0040f4311e29'
You can store its output in a CHAR(36) column.
INSERT INTO table (`uuid`, `col1`, `col2`) VALUES (UUID(), 'someval', 'someval');
According to the documentation though,
Although UUID() values are intended to be unique, they are not necessarily unguessable or unpredictable. If unpredictability is required, UUID values should be generated some other way.
Addendum Another option is UUID_SHORT() for a 64-bit unsigned INT rather than a character field.
mysql> SELECT UUID_SHORT();
-> 92395783831158784
A: The only automatically generated default in the table definition allowed would be autoincrement (MySQL Guide).
You should be able to write a trigger to automate this process though, maybe through the UUID function as Michael suggested.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575302",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to analyze Rails's page performance in my rails app on product for one of our pages I see this:
Started GET "/bobbb1" for 127.0.0.1 at 2011-09-27 13:31:47 -0700
Processing by PagessController#show as HTML
....lots of queries
Rendered modules/_edit.html.erb (5.6ms)
Rendered modules/_show.html.erb (9.6ms)
Rendered feeds/_feed_items_tmpl.html.erb (2.3ms)
Rendered members/_edit.html.erb (1.1ms)
Rendered layouts/_header.html.erb (64.4ms)
Rendered layouts/_footer.html.erb (0.1ms)
Rendered pages/show.html.erb within layouts/application (105.1ms)
Completed 200 OK in 230ms (Views: 100.6ms | ActiveRecord: 11.4ms)
Why does rails show:
Completed 200 OK in 230ms
Yes then show: (Views: 100.6ms | ActiveRecord: 11.4ms)
This doesn't add up? What's the lag here. How can I diagnose where the performance bottlenecks are?
Thanks
A: Rails includes built-in options for detailed profiling and benchmarking beyond basic logging. Some metrics are not available in all Ruby stacks (I understand 1.9.x includes more options.)
See http://guides.rubyonrails.org/v3.2.13/performance_testing.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575303",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I fill a new array with split pieces from an existing one? (Java) I'm trying to split paragraphs of information from an array into a new one which is broken into individual words. I know that I need to use the String[] split(String regex), but I can't get this to output right.
What am I doing wrong?
(assume that sentences[i] is the existing array)
String phrase = sentences[i];
String[] sentencesArray = phrase.split("");
System.out.println(sentencesArray[i]);
Thanks!
A: It might be just the console output going wrong. Try replacing the last line by
System.out.println(java.util.Arrays.toString(sentencesArray));
The empty-string argument to phrase.split("") is suspect too. Try passing a word boundary:
phrase.split("\\b");
A: You are using an empty expression for splitting, try phrase.split(" ") and work from there.
A: String[] sentencesArray = phrase.split("");
The regex based on which the phrase needs to be split up is nothing here. If you wish to split it based on a space character, use:
String[] sentencesArray = phrase.split(" ");
// ^ Give this space
A: This does nothing useful:
String[] sentencesArray = phrase.split("");
you're splitting on empty string and it will return an array of the individual characters in the string, starting with an empty string.
It's hard to tell from your question/code what you're trying to do but if you want to split on words you need something like:
private static final Pattern SPC = Pattern.compile("\\s+");
.
.
String[] words = SPC.split(phrase);
The regex will split on one or more spaces which is probably what you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: in-app A|B Testing for Mobile Is there a good solution for A|B Testing in mobile apps like online? I know with iOS it's against the TOS to have different user experiences with identical actions, but what about Android? And what about firms like Apsalar which claim to offer A|B Testing in their analytics for apps? How would one implement that?
A: Artisan mobile makes an A/B testing solution for iOS and Android.
The basic idea is that you drop the SDK in your app and then put it out in the app store. You can use the service to create A/B tests and optimize your application without having to touch the code or go back through the app store for each test.
A: For mobile apps, A/B testing basically works by replacing static, hard-coded objects with dynamic objects that can be controlled from a remote server.
This methodology raises a potential performance issue: What if the end user's device is not connected to pull configuration data for an object being tested? We've built Splitforce (http://splitforce.com) to seamlessly setup and manage A/B testing in mobile apps while controlling for performance risk.
Los details
Once the SDK and experiment has been integrated, non-technical product or marketing folks can setup new tests or tweak existing tests on-the-fly - without having to resubmit to the app stores or hassle engineers.
On first app launch, the mobile app requests configuration data from the server and then caches that data locally on the device. This is to both ensure a consistent user experience on subsequent app launches, and prevent corrupt test results by guaranteeing accurate attribution of conversion events to variations.
If the end user's connection fails or is timed-out on first app launch, the library displays a hard-coded 'default' variation. And to make sure that everything is looking good before you go live, we've built a 'shake to preview' functionality in debug mode that does just that :-)
Once the app is deployed with Splitforce event data are stored locally and sent back to the website to be displayed for each variation alongside measurements of observed improvement and statistical confidence.
Instructions on integration of the SDKs and new tests can be found at https://splitforce.com/documentation.
And how is it used?
We've seen Splitforce used to A/B test:
UI elements + layouts (color, text, images, ad/menu placements)
UX workflows
Game dynamics + rules
Prices + promotions
We've also seen the tool used to control mobile apps remotely, by essentially setting one variation of a test subject to 100%.
A: *
*Yes there is: E.g. the company Leanplum offers a Visual Interface Editor for iOS and Android: This requires no coding, and Leanplum will automatically detect the elements and allow you to change them. No engineers or app store resubmissions required.
*Apple must have updated their TOS (https://developer.apple.com/app-store/review/guidelines/#user-interface) - At least I am not aware of anything that prohibits altering the UI in a way that the Leanplum Visual Editor is doing it.
*Generally that is achieved by method swizzling (iOS) and reflection (Android).
To learn more about the Leanplum Visual Interface Editor, check out leanplum.com. They offer a free 30-day trial.
(Disclaimer: I am an Engineer at Leanplum.)
A: The new kid around the block is Arise.io. They provide an A/B testing service for iOS and Android.
A: I wrote a small open source project called Switchboard.
It let's you A/B test, remote configure and stage rollout things in your native mobile app. It contains a server component that specifies what information the application should have and 2 native clients for android and iOS.
You can find the codebase at github.com/keepsafe/switchboard and a blog post about how you can use it HERE
A: I wrote MSActiveConfig, an extremely flexible framework to do remote configuration + A/B testing on iOS, with a portable format to be able to implement clients on other platforms: https://github.com/mindsnacks/MSActiveConfig.
This framework is being used in applications with more than 5 million users.
A: There have been a spate of new entrants in this field...you could check out Swerve, Appiterate, leanplum...all of them seem to be having SDKs for iOS as well, not really sure whether and how Apple TOS allows for that, but since there are some many of them doing it, there must be a way.
A: Yes, new entrants are showing up in app A/B testing practically every week! But, I think Appiterate has gone two steps ahead of other competitors by creating a visual interface, without any need to re-write code. I have seen their platform (you can ask for an invite. I got a demo within 12 hours) and believe me, it is actual WYSIWYG that they are providing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575306",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Basic indentation settings in Xcode The default settings in Xcode 3.2.6 do some automatic indentation: typing if (something) and pressing return (when the cursor is to the right of the closing paren) automatically indents the cursor by one tab. How can I turn this feature off?
I tried turning off "syntax-aware indenting" however this doesn't solve the problem. Pressing return in the above example still indents the cursor (it's aligned with if in this case).
My ultimate goal is to avoid "stray tabs" (blank lines that have tabs).
A: You could hook in a code beautifier to clean up the tabs afterwards: http://robertjpayne.com/post/9092159751/using-uncrustify-directly-in-xcode-4
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: PHP explode text to multidimensional array I wanna explode this text to three dimensional array:
Q 11 21 21 ( 40 44 23 ! 24 ! ! Q ! 32 22 48 18 23 49 ! ! ! ! 24 23 Q ! 19 23 06 49 29 15 22 ! ! ! Q ! 20 ( 23 23 ( 40 ! ! ! ! Q ! 21 06 ! 22 22 22 02 ! ! !
Q ! ( 40 05 33 ! 05 ! ! ! ! Q ! 49 49 05 20 20 49 ! ! ! Q ! ! 05 34 ( 40 ( ( 1 Q ! ! 46 46 46 46 46 46 ! ! ! Q ( 46 07 20 12 05 33 ! ! ! !
This is timetable is in text form. The following are the conditions that determine each value in the array:
*
*new row = next time table;
*Q = new day;
*space = next hour
*! = free hour,
*( = duplicit hour
And I want it like this:
array[timetable][day][hour]
How can I do that? Is there choice do it by PHP explode function?
A: What a nice format! I think I still don't get it, but I'll try answering anyway...
*
*use explode with "\n" and you'll get an array of timetables
*for each element of this array, replace it with an explode of itself with 'Q' and you'll have a 2-dimensional array
*for each element of each element of this array, replace the element with an explode of itself with ' '
Try to do this and if you're having trouble, edit your question with the code you'd come up with.
A: Without really understanding how your strings work; This code should do the job.
$timetables = explode("\n", $source);
foreach($timetables as $tablekey => $days)
{
$timetables[$tablekey] = explode('Q', $days);
foreach($timetables[$tablekey] as $daykey => $hours)
$timetables[$tablekey][$daykey] = explode(' ', $hours)
}
print_r($timetables, true);
A: $x = //...
$x = explode("\n", $x);
foreach($x as $k => $v) {
$x[$k] = explode("Q", $x[$k]);
foreach($x[$k] as $kk => $vv) {
$x[$k][$kk] = explode(" ", $x[$k][$kk]);
}
}
With array_map I think you wiil get somewhat nicer code.
A: Here is a recursive function that takes an array of delimiters:
function multi_explode($delimiters, $val) {
$delimiter = array_shift($delimiters);
if (!empty($delimiter)) {
$val = explode($delimiter, $val);
foreach($val as $key => $valval) {
$val[$key] = multi_explode($delimiters, $valval);
}
}
return $val;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575311",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Windows equivalent to sync() I do most of my programming on embedded processors, or on linux. When i need to sync data to my persistant store, i usually use the sync(2) system call. Is there an equivelent for Windows?
A: http://msdn.microsoft.com/en-us/library/aa364439(VS.85).aspx
http://www.codeproject.com/KB/system/EjectMediaByLetter.aspx
FlushFileBuffers with a handle to a volume. You have to do this for every volume :(
A: Use FlushFileBuffers, but you need a handle to the file you need flushed.
A: If you are using posix file functions (fopen() etc.), you can use _flushall:
http://msdn.microsoft.com/en-us/library/s9xk9ehd%28v=vs.80%29.aspx
A: See here: https://jeffpar.github.io/kbarchive/kb/066/Q66052/
When you initially open your file using fopen, include the "c" mode option as the LAST OPTION:
fopen( path, "wc") // w - write mode, c - allow immediate commit to disk
Then when you want to force a flush to disk, call
_flushall()
We made this call before calling
fclose()
Note that this approach does NOT required Administrative rights, which FlushFileBuffers does require.
From that above site:
"Microsoft C/C++ version 7.0 introduces the "c" mode option for the fopen()
function. When an application opens a file and specifies the "c" mode, the
run-time library writes the contents of the file buffer to disk when the
application calls the fflush() or _flushall() function. "
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575313",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Objective-c simple memory question If I have a variable in my view controler
viewcontroller.m
@interface MemoryTestViewController : UIViewController
{
NSMutableArray *array;
}
@end
in my implementation
- (void)viewDidLoad
{
[super viewDidLoad];
NSMutableArray *aux = [[NSMutableArray alloc] initWithCapacity:1];
array = aux;
[aux release];
// Do i have to do array release?
}
Do i have to release my variable array somewhere? Theoricaly i havent allocated that variable...
I testes the memory leaks and even if i dont release anything the instruments doesn't detect any leak.
A: No, you don't need to release. All you do is assign the pointer of aux to your array variable.
array is invalid at the moment where you release aux.
This is probably not as intended. If you want to work with array, you'll have to retain it.
A: You've already released the array with [aux release]; -- you in fact have the opposite problem to a leak: an over-release.
Assignments in Objective-C are just assignments of pointers; there's no copying or automatic memory management. When you say array = aux;, array now points to the exact same object as aux. If you then get rid of aux by releasing it (and therefore letting it be deallocated), array doesn't point to anything anymore.*
You have a couple of options for fixing this:
*
*(Simplest) Assign the newly-created array directly to array:
array = [[NSMutableArray alloc] initWithCapacity:1];
This gives you ownership of the new array, under the name array. Don't release it until you are done with it (possibly in dealloc; certainly not in this method).
*(Best) Create a declared property for array and let that mechanism handle the memory management for you:
@interface MemoryTestViewController : UIViewController
{
NSMutableArray *array;
}
@property (copy, nonatomic, setter=setArrayByMutableCopy) NSMutableArray * array;
@end
@implementation MemoryTestViewController
@synthesize array;
// Properties can't automatically make mutable copies, so you need to create
// your own setter method.
- (void) setArrayByMutableCopy: (NSMutableArray *)newArray {
NSMutableArray * tmp = [newArray mutableCopy];
[array release];
array = tmp;
}
...
*Or, rather, it points to a place where there used to be a valid object, which is a great way to make your program crash.
A: You should add a property:
@property (nonatomic, retain) NSMutableArray *array;
and later in your viewDidLoad:
// wrong, leaks: self.array = [[NSMutableArray alloc] initWithCapacity:1];
array = [[NSMutableArray alloc] initWithCapacity:1];
and yes, somewhat later release it, probably in dealloc..
A: No. Assigning an object to a variable does not retain it. However if you plan to use that variable for a while, you should retain it and release it when you are done with it.
alloc raised the retain counter to 1 and [aux release] set it to 0
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575319",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Caml Query to fetch the items where the Lookup Column value is not null I have a list of employees in sharepoint. One of the columns in the Employee list is a lookup Column called Organization.
I am trying to write a CAML query to fetch all the employees where the Organization value is not empty. But, I receive all the items even if the value of Organization is empty.
This is what I am trying
string querystring = string.empty;
querystring = "<Where><IsNotNull><Field RefName='EmployeeOrganization_x0020_Organization' /></IsNotNull></Where>";
This query is returning all the items in the list.
SPQuery query = new SPQuery();
query.Query = "<Where><IsNotNull><FieldRef Name='EmployeeOrganization_x0020_Organization'/></IsNotNull></Where>";
DataTable dtemp = emplist.GetItems(query).GetDataTable();
if (dtemp != null)
{
GridView1.DataSource = dtemp ;
GridView1.DataBind();
}
A: <Query>
<Where>
<IsNotNull>
<FieldRef Name='Project'/>
</IsNotNull>
</Where>
</Query>
Is working for me.You should use U2U CAML Query Builder to build the Query by using the Designer.. It automatically generates the required CAML expression for you.
Can you provide more from your context. What are your settings on the SPQuery instance?
Edit:
<Field RefName='Project'/>
to
<FieldRef Name='Project'/>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575322",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: python precautions to economize on size of text file of purely numerical characters I am tabulating a lot of output from some network analysis, listing an edge per line, which results in dozens of gigabytes, stretching the limits of my resources (understatement). As I only deal with numerical values, it occurred to me that I might be smarter than using the Py3k defaults. I.e. some other character encoding might save me quite some space if I only have digits (and space and the occasional decimal dot). As constrained I am, I might even save on the line endings (Not to have the Windows standard CRLF duplicate). What is the best practice on this?
An example line would read like this:
62233 242344 0.42442423
(Where actually the last number is pointlessly precise, I will cut it back to three nonzero digits.)
As I will need to read in the text file with other software (Stata, actually), I cannot keep the data in arbitrary binary, though I see no reason why Stata would only read UTF-8 text. Or you simply say that avoiding UTF-8 barely saves me anything?
I think compression would not work for me, as I write the text line by line and it would be great to limit the output size even during this. I might easily be mistaken how compression works, but I thought it could save me space after the file is generated, but my issue is that my code crashes already as I am tabulating the text file (line by line).
Thanks for all the ideas and clarifying questions!
A: You can use zlib or gzip to compress the data as you generate it. You won't need to change your format at all, the compression will adjust to the characters and sequences that you use the most to create an optimal file size.
A: Avoid the character encodings entirely and save your data in a binary format. See Python's struct. Ascii-encoded a value like 4-billion takes 10 bytes, but fits in a 4-byte integer. There are a lot of downsides to a custom binary format (its hard to manually debug, or inspect with other tools, etc)
A: I have done some study on this. Clever encoding does not matter once you apply compression. Even if you use some binary encoding, they seems to contain the same entropy and end up in similar size after compression.
The Power of Gzip
Yes there are Python library allow you to stream output and automatically compress it.
Lossy encoding does save space. Cutting down the precision helps.
A: I don't know the capabilities of data input in Stata, and a quick search reveals that said capabilities are described in the User's Guide, which seems to be available only on dead-tree copies. So I don't know if my suggestion is feasible.
An instant saving of half the size would be if you used 4-bits per character. You have an alphabet of 0 to 9, period, (possibly) minus sign, space and newline, which are 14 characters fitting perfectly in 2**4==16 slots.
If this can be used in Stata, I can help more with suggestions for quick conversions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575329",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how do I convert textbox value to string? I know this is simple but i am lost as to how to approach it. Iam a new newbie. Please have it on me as i am new here.
I have a textbox field called ClientsBalance.
This balance can is usually in money order with a set amount. The client is also allowed to pay by Debit Cards.
Here goes:
Dim paymentType As TextBox
otherPyment As String = "Debit Card"
If paymentType.Text <> "1250" Then
paymentType = "OtherPayment"
else
paymentType = gridview1.FindControl("paymentType" & CStr(1))
end if
Everything was working before the validation.
Now, I get the following error:
Value of type 'String' cannot be converted to 'System.Web.UI.WebControls.TextBox'
Is there a way I can cast this line:
paymentType = "OtherPayment"
??
Thank you so much experts.
A: you need to say
paymentType.Text = "OtherPayment".
You just left out the ".Text"
A: Try changing this:
paymentType = "OtherPayment"
To this:
paymentType.Text = "OtherPayment"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Problem sending data in hybi-10 WebSockets server I'm trying to implement the new hybi-10 protocol in a python server and for now I succeeded in the handshake and receiving data from the client (JavaScript) but now I'm having problems with sending the data to the client.
I'm using a bit of a code from websockify (encode_hybi function) to encode the frames according to this protocol. But unfortunately the client doesn't seem to receive the data, as the on message event never fires.
So the code I have is this:
def encode_hybi(self, buf, opcode = 0x01):
buf = b64encode(buf)
b1 = 0x80 | (opcode & 0x0f)
payload_len = len(buf)
if payload_len <= 125:
header = struct.pack('>BB', b1, payload_len)
elif payload_len > 125 and payload_len < 65536:
header = struct.pack('>BBH', b1, 126, payload_len)
elif payload_len >= 65536:
header = struct.pack('>BBQ', b1, 127, payload_len)
print repr(header + buf)
return header + buf
def send(self, data):
logging.info("Message Sent: %s" % data)
if (self.protocol == 'hixie-76'):
self.client.send("\x00%s\xff" % data)
elif (self.protocol =='hybi-10'):
msg = self.encode_hybi(data)
self.client.send(msg)
I'm sending a simple 'OK' through the socket. So after the encode_hybi function I get:
'\x81\x04T0s=' which is sent to JavaScript. I have no response from it, nor errors.
I tried to send other data, for example 'OKKK'. After the encode_hybi function I get: '\x81\x08T0tLSw=='. Don't know if it helps, but with this data sent, the JavaScript presents an error:
Unrecognized frame opcode: 13.
This error appears every time the length of the data sent is bigger than 3 characters.
I really can't understand the problem. Is something wrong in the encoding?
A: You used \n\r\n\r\n at the end of the handshake format, but it should be \r\n\r\n. Currently the \n is part of the key.
Although I don't understand how you were still able to open a connection, it looks like removing the first \n solves the problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Disk space for downloaded files in ios app My app downloads files. How much space I can use for downloaded files? App size is 3-4 mbytes. I save files to documents folder.
A: There is no capacity limit except the available storage (except for the fact that the app may see a bit less storage then what is actually available on the device - some may be saved for the OS).
To get the free storage available on the device (as your app is concerned):
NSString* docsDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfFileSystemForPath:docsDir error:NULL];
unsigned long long freeSpaceInBytes = [[fileAttributes objectForKey:NSFileSystemFreeSize] unsignedLongLongValue];
NSLog(@"Memory Capacity of %llu MiB.", ((freeSpaceInBytes/1024ll)/1024ll));
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: INotifyPropertyChanged in subclass I want to bind a TextBox in the window to a property contained within a class that is a variable of the viewmodel and ensure that INotifyPropertyChanged's PropertyChanged event propagates from the class to the parent.
Let me illustrate with an example:
(Window's DataContext is set to an instance of ViewModel)
public class ViewModel {
private OtherClass classInstance = new OtherClass();
public int Attribute {
get { return classInstance.Attribute; }
}
}
public class OtherClass : INotifyPropertyChanged {
private int _attribute;
public int Attribute {
get { return _attribute; }
set {
_attribute = value;
PropertyChanged("Attribute");
}
}
...
}
The problem in this example is that, when Attribute changes, the bound Textbox does not update the binding since I assume it's listening to the ViewModel's PropertyChanged event and not that of the instance of OtherClass.
Any ideas on how to remedy this situation? I was thinking about chaining OtherClass's INotifyPropertyChanged to that of its parent, but there has to be a better way.
A: Why not bind directly to the class property instead of using a proxy?
public class ViewModel {
private OtherClass classInstance = new OtherClass();
public OtherClass MyOtherClass {
get { return classInstance; }
}
}
Then in your binding you can simply reference the property via the SubClass
{Binding MyOtherClass.Attribute}
A drop dead simple example, but it works!
The Code Behind:
public partial class MainWindow : Window {
private readonly SomeClass _someClass = new SomeClass();
public MainWindow() {
InitializeComponent();
DataContext = _someClass;
}
}
public class SomeClass: INotifyPropertyChanged {
private readonly SomeSubClass _mySubClass = new SomeSubClass();
public SomeSubClass MySubClass {
get { return _mySubClass; }
}
private String _name;
public String Name {
get { return _name; }
set {
_name = value;
OnPropertyChanged("Name");
}
}
//Property Change Stuff
}
public class SomeSubClass : INotifyPropertyChanged {
private String _name;
public String Name {
get {
return _name;
}
set {
_name = value;
OnPropertyChanged("Name");
}
}
//Property Change Stuff
}
The XAML:
<Window x:Class="JWC.Examples.WPF.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow">
<StackPanel>
<Label Content="Name" VerticalAlignment="Top" />
<TextBox Text="{Binding Name}" />
<Label Content="SubClass.Name" />
<TextBox Text="{Binding MySubClass.Name}" />
<Label Content="Bound to Name" />
<TextBlock Text="{Binding Name}" />
<Label Content="Bound to MySubClass.Name" />
<TextBlock Text="{Binding MySubClass.Name}" />
</StackPanel>
</Window>
A: You will need to do something like this:
public class ViewModel {
public ViewModel() {
classInstance = new OtherClass();
classInstance.PropertyChanged += HandleAttributeChanged;
}
private void HandleAttributeChanged(object Sender, NotifyPropertyChangedEventArgs args) {
PropertyChanged("Attribute");
}
}
I don't show it here, but you should also implement IDisposable and unsubscribe from the PropertyChanged event on your child, otherwise you will leak memory.
Alternatively you can expose the classInstance as a public property and set your binding to: ViewModel.classInstance. Note this needs to be a property and not the field itself.
A: I think the parent class should subscribe to the child propertyCahnged event..something like:
public class ViewModel
{
private OtherClass classInstance = new OtherClass();
public ViewModel()
{
classInstance.PropertyChanged += NotifyChildAttributeChanged;
}
public int Attribute
{
get { return classInstance.Attribute; }
}
}
NotifyChildAttributeChanged is basically a method that listens only to the "Attribute" property and fires a PropertyChanged notification of its own..
Of course our parent class must implement INotifyPropertyChanged as well as will all ViewModels (preferably) and your DataContext will detect the change.
A: To get around this you need to implement INotifyPropertyChanged on your view model as well. Just add the interface and the event and the rest will take care of itself - no need to chain the events / calls together.
Check out this for using reflection to get the property as well.
http://tsells.wordpress.com/2011/02/08/using-reflection-with-wpf-and-the-inotifypropertychanged-interface/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Java class with unicode code range specifications Is there a class where the code ranges of unicode is defined as an enumeration or as constants? It's a very simple class where the code range specification (can be found anywhere like this for example: http://www.ssec.wisc.edu/~tomw/java/unicode.html) is put into a class, but this is a lot of boring work and I wish someone else has done it before!
A: See java.lang.Character.UnicodeBlock.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575348",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Release object after return? Say I have an object initialized right before a method's return statement...
MyObj* myObj = [[MyObj alloc] initWithOpt1:opt1 withOpt2:opt2];
return myObj;
Is it possible to release it after the return statement? Doing so before defeats the purpose of init'ing it to begin with, right? Otherwise, what's the best way to handle this?
A: Autorelease was created precisely to solve this problem.
MyObj* myObj = [[MyObj alloc] initWithOpt1:opt1 withOpt2:opt2];
return [myObj autorelease];
http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/MemoryMgmt/Articles/mmAutoreleasePools.html
A: Just do
return [myObj autorelease];
that's it!
A: While
return [myObj autorelease];
works it is better coding educate to simply
return myObj;
and then when you create the object do it with an autorelease on it.
MyObj *my_obj = [[[MyObj alloc] initWithOpt1:opt1 withOpt2:op2] autorelease];
and the reason for this is because autorelease is saying that when this function is over I want to release this object. So using
return [myObj autorelease];
is not the only way.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575360",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Proper Way To Use Git/GitHub - PHP System with Dev/Testing/Production servers I apologize if this is obvious or easy, I have looked at a good number of git/github tutorials and read other articles, but I want to make sure what I'm doing is right.
I want to incorporate VC (for obvious reasons) into my development team and process.
Current development process (using Dreamweaver):
* Receive a ticket (or work order)
* Download file on Development server
* Make changes to the file
* Upload file back to development server
* Changes tested/verified
* Send to production server
I'm trying to figure out how to make our new development process with using Git.
I am switching over to PHPStorm (which is an actual PHP IDE with direct integration with Git).
Would it be something like
*
*Receive a ticket (or work order)
*Checkout/Update/Download file(s)
*Change Files
*Upload file (which I assume is also the current working directory...?)
*At the end of the day, do a commit
*Have build script send data to testing server (nightly build)
Or would it be better to do something like
*
*Receive a ticket (or work order)
*Checkout/Update/Download file(s)
*Change Files
*Upload file/commit
*Have build script send data to testing server (nightly build)
Or is there another way? Having a bit of trouble understanding what would be the optimal flow?
Any help would be greatly appreciated.
Edit
I'm trying see if it is best to have a version of the server locally (every developer), and if so, how does that work if you have 7 or so branches?
If not, how do you deal with 7 or so branches with them on the web? Do you FTP files up or use Git Hooks to make them auto update?
Update 07/26/2012
After working successfully with Git for quite a while now I've been following this branching model with great success:
A Successful Git Branching Model
The answer to the above was yes -- should definitely have a local version of the server.
A: Assuming you have a live server and a development server I would do something along these lines.
Before even starting with a development cycle I would at least have two branches:
*
*Master - the development server runs on this branch
*Stable - the live server runs on this branch.
So if a developer gets a ticket or a work order he/she will perform the following actions:
*
*git pull origin master
*git branch featureBranch (named as the ticket id or as a good description for the work order)
*git checkout featureBranch
*Make changes which will accomplish the desired change. Commit as often as is necessary. Do this because you will create valuable history. For instance you can try an approach to a problem and if it doesn't work, abandon it. If a day later you see the light and want to re-apply the solution, it is in your history!
*When the feature is fully developed and tested locally, checkout master.
*git merge featureBranch
*git push origin master
*Test the pushed changes on your development server. This is the moment to run every test you can think of.
*If all is working out, merge the feature or fix into the stable branch. Now the change is live for your customers.
Getting the code on the server
The updating of servers shouldn't be a problem. Basically I would set them up as users just like you're developers are. At my company we've setup the servers as read-only users. Basically that means the servers can never push anything but can always pull. Setting this up isn't trivial though, so you could just as well build a simple webinterface which simply only allows a git pull. If you can keep your developers from doing stuff on live implementations you're safe :)
[EDIT]
In response to the last questions asked in the comments of this reaction:
I don't know if I understand your question correctly, but basically (simplified a bit) this is how I would do this, were I in you shoes.
The testing machine (or the webroot which acts as testing implementation) has it source code based in a git repository with the master branch checked out. While creating this repository you could even remove all other references to all other branches so you'll be sure no can checkout a wrong branch in this repository. So basically the testing machine has a Git repository with only a master branch which is checked out.
For the live servers I would do exactly the same, but this time with the stable branch checked out. Developer should have a local repository cloned in which all branches exist. And a local implementation of the software you guys build. This software gets its source from a the local git repository. In other words: from the currently checked out branch in this repository.
Actual coding
When a new feature is wanted, a local feature branch can be made based on the current master. When the branch is checked out the changes can be made and checked locally by the developer (since the software is now running on the source of the feature branch).
If everything seems to be in order, the changes get merged from feature branch to master and pushed to your "git machine". "your github" so to speak. Testing can now pull the changes in so every test necessary can be done by QA. If they decide everything is ok, the developer can merge the changes from master to stable and push again.
All thats left now is pulling form your live machines.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "47"
}
|
Q: Red underline that I cant figure out how to fix I'm brand new to iPhone programming. I've tried some tutorials and such and now I'm trying to do a simple project to get my feet wet. And of course I have having issues getting it to do what I want. I started it by using a Navigation project. I didn't want the UITableView though I just want normal buttons that lead to the next page. Although when I tried to get rid of the UITableView I think I did it wrong so now it isn't working when I am setting up the next view.
Here is the .h (the red underline is under the MPHViewController in both places) Oh and what it wants to do is make both those UIViewController.
#import <UIKit/UIKit.h>
#import "MPHViewController.h"
@interface RootViewController : UIViewController {
MPHViewController *mphViewController;
}
@property(nonatomic,retain) MPHViewController *mphViewController;
@end
I'm thinking where I mainly messed up was in the .m (I think) I took out all the code that had to do with the UITableView and simply put this in (wasn't sure what else should be placed there).
- (UIViewController *)viewControl:(UIView *)view
{
}
Sorry for being a pain I just don't know any better way of learning how to do this other then just trial and error.
A: Make sure you synthesize it in the .m
@synthesize mphViewController;
A: It might not be able to find the definition for your custom class.
In xcode under the project setting -> build phases, make sure the MPHViewController.m is included in the list of source files to be compiled.
Also, make sure in your MPHViewController.h that your subclassing UIViewController properly:
@interface MPHViewController : UIViewController
{
// ....
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: combining unrelated git repositories retaining history/branches we're having 3 separate git repositories (each with some branches) which we'd like to combine into one keeping full history and the ability to access the branches, like so:
so this is what we have. 3 repos:
/A/.git
/B/.git
/C/.git
and we'd like to have one super-repo with 3 subdirectories:
super/.git
super/A
super/B
super/C
and say when switching to branch feature1 (which was originally in repo B, introduced at a time that repo C didn't exist yet) we'd expect the result to be:
super/.git
super/A
super/B
we've read Combining multiple git repositories but had troubles using git-stitch-repo which basically worked as advertised only that quite a large number of commits were missing in the super-repo (without any error messages that would point to a problem).
any idea what we could be doing wrong here?
EDIT
we are aware of submodules and subtree-merging, but both are not an option. this is supposed to be a one time operation. we need the repos joined once and forever.
EDIT
probably a simpler way to put basically the same question: say we have one repo with 3 totally unrelated branches. we can merge them without a conflict to one branch (since they share no files). now when looking at the history we see 3 unrelated branches of commits and the one point where they come together. but what we'd like to see is one branch made up of the interleaved (by date/time) commits of all 3 branches.
A: You don't want submodules as you will pull your hair out with all the git submodule update commands you will be issuing. You will also have to issue 3 git log commands instead of one to see what has happened in a certain amount of time.
Bring all of the histories into one repo. Use filter-branch to reset the directories that each repos history resides in. There is no need to stitch. You can simply merge at any point once you do the filter branch.
Essentially repoA/master, repoB/master and repoC/master will exist in the new repo you make (although you can just start with one of them). After you apply filter branch, each tree in each commit will have a new root node that will be a directory (A for repoA branches, B for repoB branches, etc).
OR
git checkout -b newbranch --root
git log --all --format=%ad%H | sort | cut -c10- | xargs -n 1 git cherry-pick
adjust the cut so it only takes the hash. Haven't tried this but let me know how it works. You may need to flatten out history first with rebase. You can't interleave the different branches and merges from the 3 different histories.
hope this helps.
A: splice_repos is a tool I wrote that interleaves commits from different repositories into a new repository, so that same-named branches get merged histories (as though they were committed to in historical order), rather than just being merged at the end with separate histories on different branches. There's a blog entry describing the rationale behind it.
A: Probably the easiest way to do this is to use submodules. It doesn't exactly speak to the case you're looking to achieve, but it's darn close and not very headache prone.
Just create a new directory and git init it as your "super" repo. Then add in your A,B and C repos using the commands given on the link above.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575367",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Open a word document and save it to another folder with vbscript I have working code that opens up a word document programmatically using vbscript, makes a change, then saves that same document and closes that same document.
Is it possible to do the same thing, but save the document to another folder and close out both instances of word? I slightly modified my original code, but it only closed out the second instance of the word document that was saved.
Apparently, word thinks if I'm saving to another folder it needs 2 instances of the document. This is some of my original code:
Set objDoc = objWord.Documents.Open(objFile.Path)
'modify the document.
etc...
objDoc.SaveAs objFSO.BuildPath(strDirectory, objFSO.GetFileName(objFile.Path))
objDoc.Close
this works fine for one document. Then all I changed was this, adding another directory to write to instead of the original:
objDoc.SaveAs objFSO.BuildPath(strDirectory & saveDir, objFSO.GetFileName(objFile.Path))
and I ended up with two identical word documents opened and when I closed the one I was saving, the other stayed open.
Is there a simple way to do this?
Thanks,
James
A: It may be better to save the word document in the original folder and then write further code to move it into another location, perhaps using FileSystemObject.MoveFile. Don't rely on Word's "Save-as" functionality to do this - as you have observed you get a nasty side-effect.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575373",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android Multiple insert data to sqlite I try to insert multiple data to sqlite in android but I can't.
I want to create and insert like the code bolow, please help me.
here is my bad code,
package com.pepakbahasajawa.database;
import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;
public class PepakDatabaseHelper extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "pepakdb";
private static final int DATABASE_VERSION = 1;
//Pembuatan Database
private static final String DATABASE_CREATE_1 = "create table pepak (_id integer primary key autoincrement, "
+ "name text not null);";
private static final String DATABASE_CREATE_2 = "create table category (_id integer primary key autoincrement, "
+ "id_pepak integer(11) not null, cat_name varchar(255) not null);";
private static final String DATABASE_CREATE_3 = "create table subcategory (_id integer primary key autoincrement, "
+ "id_category integer(11) not null, subcat_name varchar(255) not null);";
private static final String DATABASE_CREATE_4 = "create table posts (_id integer primary key autoincrement, "
+ "id_subcategory integer(11) not null, post_name_1 varchar(255) not null, post_name_2 varchar(255));";
public PepakDatabaseHelper(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase database) {
// TODO Auto-generated method stub
database.execSQL(DATABASE_CREATE_1);
database.execSQL(DATABASE_CREATE_2);
database.execSQL(DATABASE_CREATE_3);
database.execSQL(DATABASE_CREATE_4);
String sql = "INSERT INTO pepak (name), category (name), subcategory (id_category)," +
"(subcat_name), posts (id_subcategory), (post_name_1), (post_name_2)" +
"VALUES (Kawruh Rupa), VALUES (1), VALUES (Tetawuhan), VALUES (1), VALUES (Arane Kembang), VALUES (1)," +
"VALUES (Kembang aren - Arane Dangu), VALUES (Bunga Aren - Disebut Dangu)";
Log.v("simapn oke", sql);
database.execSQL(sql);
}
@Override
public void onUpgrade(SQLiteDatabase database, int oldVersion,
int newVersion) {
Log.w(PepakDatabaseHelper.class.getName(),
"Upgrading database from version " + oldVersion + " to "
+ newVersion + ", which will destroy all old data");
database.execSQL("DROP TABLE IF EXISTS pepak");
database.execSQL("DROP TABLE IF EXISTS category");
database.execSQL("DROP TABLE IF EXISTS subcategory");
database.execSQL("DROP TABLE IF EXISTS posts");
onCreate(database);
}
}
Please help.
Thanks
A: Your insert SQL is totally wrong. Try to add one entry and do it again if the first one worked.
String sql = "INSERT INTO pepak (name) VALUES (\"SampleText\");";
database.execSQL(sql);
If that works, you can simply create a new insert SQL statement and finally you will have something like that:
String sql = "INSERT INTO pepak (name) VALUES (\"SampleText\");";
database.execSQL(sql);
sql = "INSERT INTO category (name) VALUES (\"CategoryText\");";
database.execSQL(sql);
If you insert more than 20, you should think about a custom transaction handling to speed the inserts up.
// pseudocode
database.startTransaction();
doAllInserts(); // method/loop for all inserts - depending on your needs
database.setTransactionSuccessfull();
database.commit();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to get the address value of a function in assembly In gcc assembly code listed below, I want to store the address of function foo to var, how do i do it? Thanks.
.text
.globl foo
foo:
/* do something */
.data
.globl var
var:
.long /* the address of foo */
A: Have you tried this?
.long foo
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to paint a WPF-Shape mathematically? I want to paint an WPF-Element like a colorwheel, you know from the HSV color space.
i dont know how to do this, i havnt found a possibility based on the standard brushes (SolidColorBrush, GradientBrush, etc)
How is a (mathematical) painting possible on wpf-shapes?
A: when you talk about Brushes and Pens you are talking about GDI+ and in GDI+ you have full control on anything since you are basically deciding which pixel to turn on, not so low of course but using lines, polygons and paths.
for a comparison between GDI+ and WPF or simply for some info regarding how to move from the first to the second, check this one: C# Transition between GDI+ and WPF there are some answers with lots of details
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: SQL Server rows with latest date I have a table :
EventLog (
EventID (INT),
UserID (VARCHAR(50),
Event (NTEXT),
EventDate(DateTime),
DocuvmentID(INT)
)
I need to write a query to get the latest event, datetime for a bunch of userId which will be
WHERE UserID IN ( 'john','tom'...etc)
How can I do that?
A: SELECT y.UserID, y.Event, y.EventDate
FROM (SELECT UserId, MAX(EventDate) AS MaxDate
FROM YourTable
WHERE UserId IN ('john','tom',...)
GROUP BY UserId) t
INNER JOIN YourTable y
ON t.UserId = y.UserId
AND t.MaxDate = y.EventDate
A: With a simple CTE:
;WITH LatestDates AS
(SELECT
EventID, UserID,
Event, EventDate,
DocumentID,
ROW_NUMBER() OVER(PARTITION BY UserID ORDER BY EventDate DESC) AS 'RowNum'
)
SELECT *
FROM LatestDates
WHERE RowNum = 1 AND UserID IN (........)
This partitions your data by some criteria (I picked UserID as an option - might be something else for you), then numbers each group sequentially starting at 1, ordered by another criteria (here: EventDate DESC) - so the most recent event for each "partition" has RowNum = 1 which is what I select from that CTE
A: select
UserID,
MAX(EventDate) AS LatestEventDate
from
EventLog
where
UserID in ('john','tom')
group by
UserID
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575381",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: HTML Multiple Heads
NOTE: I am in no way advocating multiple heads within a page
I'm using Apache Tiles and I have a few tiles that include their own heads. The result of the Tiles renders into an HTML page with multiple heads.
My questions:
*
*How is the resulting page handled in IE and Chrome? [It renders and appears successful]
*WITH APACHE TILES What is the best practice for dealing with/avoiding multiple heads [for CSS/Javascript] without having to demand all pages use the same JS and CSS files.
For Example with Question Two:
Lets say you have the following pages: home, profile, and gallery listing. Gallery listing has fancy JQuery+YUI+... and more styles. For most users, they would only be interested in the home and profile pages, so why slow them down with loading the JS and CSS files associated with Gallery.
This is what is generated
<html>
<head>
<title>The Template's Title</title>
</head>
<body>
<head> <script src="javascriptfile.js"/></head> Tile One Content
<head> <script src="javascriptfile2.js"/></head> Title Two Content
</body>
</html>
The generated contents is running the script in javascriptfile.js, and javascriptfile2. What I'm asking in the first question: is the extra heads ignored, and the contents considers? are they combined into the html/head level? Is it possible to include CSS files in the second or later head? Will this create an error with a stricter DTD?
A: Well, in modern Chrome, it's at least possible to know what happens. Chrome uses the HTML5 parser algorithm which describes exactly how invalid mark-up is processed. The gory details are at http://dev.w3.org/html5/spec/tree-construction.html#parsing-main-inbody
What happens in your example is that the first <head> in <body> is discarded. Then the <script src="javascriptfile.js"/> tag is processed, which is a start tag, not a self-closing tag, so everything that follows, including everything that looks like a tag, becomes a text child of the script element. Nothing is displayed and no script is run. If <script src="javascriptfile.js"/> is replaced by <script src="javascriptfile.js"></script>, and ditto for <script src="javascriptfile2.js"/>, the head start and end tags are silent discarded, and the script elements are not moved. "Tile One Content Title Two Content" is displayed and the scripts are run. The DTD makes no difference at all.
IE is somewhat trickier to know, as before IE10, it doesn't use the HTML5 parser algorithm and therefore it's exact behaviour is a mystery. However, a cursory experiment appears to show that it has the same behaviour as described above.
Although some legacy browsers move elements that can only appear in the head - such as <link> - into the head, other browsers do not, and no such behaviour can be relied upon.
All in all, best steer well clear of such constructs.
I don't know about practices for Apache Tiles.
A: What is the purpose of doing something so egregiously invalid? And why you're asking this seems very unclear.
Not only should you only have ONE <head></head> section on a page, under no circumstances is the <head></head> to be nested anywhere inside the <body></body> section.
This practice makes absolutely no sense whatsoever....
(Side-note: Certain browsers ignore or move invalid tags when the DOM is constructed which will defeat your entire purpose of doing this.)
EDIT (based on comments):
For anyone interested in including <script> tags within the <body>, you can read more about the specific details in my answer here...
Will linking javascript files in the body rather than in the header cause a problem?
A: You don't really need extra heads to include additional css/js. You can 'inline' the whole <style type="text/css">...</style> part and it will render fine. Will it validate? No. But will run fine.
A:
How is the resulting page handled in IE and Chrome? [It renders and appears successful]
I don't know and I really don't want to know.
What is the best practice for dealing with multiple heads [for CSS/Javascript] without having to demand all pages use the same JS and CSS.
Don't do it :-)
Is there a reason you can't just include the JS files in the body / head without the extra tags?
Or add the css / js files in the 'normal' head section of the document (where it should be).
Well atleast you want the CSS files to be loaded as soon as the page starts loading. JS files can (sometimes) be loaded at the end of the HTML.
For example if the JS files need to have a completely loaded DOM (for e.g. accessing DOM elements).
Note
Sorry this isn't really an answer to your question, however what you are doing just looks way bad. :) And is almost certainly not needed / there will be a better solution for it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Xna ModelBones - How to move them away from eachother? Hello I know that one can get absolute transforms of bones in a model.. But how to move them away (like inflating) ? I think to do so, I need to move them forward to their local positions but what I have is the absolute transfoms by
Model.CopyAbsoluteBoneTransformsTo(ModelAllTransforms);
How to proceed further ? I mean I can use
mesh.ParentBone.Transform = Matrix.CreateTranslation(?) * ModelAllTransforms;
but what would be the ? sign ..
Thanks a lot! :)
A: The direction you're looking for is basically the local bone's absolute transform minus the center, then normalized.
Something like this:
//"time" is your timing value, "speed" is some float value
Vector3 direction = bone.Translation - center;
direction.Normalize();
Vector3 translate = time * speed * direction;
bone.Translation += translate;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575389",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What Is the Issue Suddently the Database Stopped Sending Emails Out After It is Upgraded from Oracle 10g to 11g R1? Hi Oracle Database Gurus,
What is the issue suddently the Database stopped sending Emails out after it is upgraded from Oracle 10g to 11g R1? I double check the email demon on the server it is working fine when I send an email from the linux command line (not through an database procedue). And the smtp_out_server parameter value is the same before and after the upgrade...
Thanks!
A: Do you get any errors? The first thing that jumps to mind is that 11g introduces more fine-grained permissions for packages like UTL_MAIL and UTL_SMTP that interact with other servers. Your DBA would need to create an appropriate network ACL in order to allow you to access external servers from within your PL/SQL code.
If you don't have sufficient permission, your code should be getting an "ORA-24247: network access denied by access control list (ACL)" error. Are you getting such an error? Or is it possible that you have a WHEN OTHERS exception handler that is hiding that error from you?
Do you see any rows in USER_NETWORK_ACL_PRIVILEGES (or DBA_NETWORK_ACL_PRIVILEGES or ALL_NETWORK_ACL_PRIVILEGES depending on what user you're logging in as, what user is sending mail, and your privilege level)? If so, is there a row for your mail server with whatever port range your SMTP server is listening on?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Which of the following code blocks are more logical? Imagine a condintion should be true for a method to do its stuff. Which block represents the best approach (performance related and readability), or if not what is your suggestion?!
private void method()
{
if(!condition)
{
MessageBox.Show("ERROR!");
return;
}
else
{
//DO STUFF
}
}
OR
private void method()
{
if(condition)
{
//DO STUFF
}
else
{
MessageBox.Show("ERROR!");
return;
}
}
A: Well, neither, as you wouldn't use both else and return.
So, you would either do:
private void method() {
if (!condition) {
MessageBox.Show("ERROR!");
} else {
//DO STUFF
}
}
or:
private void method() {
if (condition) {
//DO STUFF
} else {
MessageBox.Show("ERROR!");
}
}
or:
private void method() {
if (!condition) {
MessageBox.Show("ERROR!");
return
}
//DO STUFF
}
or:
private void method() {
if (condition) {
//DO STUFF
return;
}
MessageBox.Show("ERROR!");
}
Which you use depends mostly on what the code actually does. The code is seldom as simple as in the examples, so it matters what more the code will do.
The first two have the advantage of having a single exit point, which often makes it easier to follow the code. You would usually put the shorter code first, as it's easier to spot there than in an else after a larger code block.
The third is often used to validate input before continuing with the main code, and you can easily have more than one validation:
private void method() {
if (!condition) {
MessageBox.Show("ERROR!");
return
}
if (!anotherCondition) {
MessageBox.Show("ANOTHER ERROR!");
return
}
//DO STUFF
}
The fourth is useful if you have several conditions that you don't want to put in the same if statement:
private void method() {
if (condition) {
var data = GetSomeData();
if (data.IsValid) {
var moreData = GetSomeMoreData();
if (moreData.IsValid) {
//DO STUFF
return;
}
}
}
MessageBox.Show("ERROR!");
}
A: Neither. Use a guard clause instead:
private void method()
{
if(!condition)
{
MessageBox.Show("ERROR!");
return;
}
//inputs have been checked, proceed with normal execution
}
Done this way you can deal with all the exceptional behaviour up-front and avoiding excessive levels of indentation for the normal execution path.
A: Second! Second!
But I do admit to doing the first sometimes if the "//DO STUFF" is really long and nested.
A: I prefer an "If condition" approach as opposed to the negation of a condition, but that's just personal preference.
A: It depends.
In most cases, the second version.
if the amount of code in the (!condition) block is only a few lines of code, and the code in the (condition) block is a LOT of code, then I'd reverse the answer. it's easier to read through the if statement if you can see the "else" without having to scroll.
A: I prefer a guard clause as David mentions, but in the general case you should put the most common case first. It makes it easier to follow the flow of a method.
A: This is more of a style question than a "logical" question. Both of these approaches work, and which one you will use generally depends on your style as a thinker/developer.
That said, once you start using either one of these styles, it generally pays to be consistent. Having large classes where some functions do it the first way and others the second way can lead to maintainability concerns later.
Robert Martin's Clean Code presents an interesting chapter on functions that suggests, whichever way you choose, the //DO STUFF part should be another function call
Functions Should Only Do One Thing
A: Readability/standards wise. I would accept number 2. I don't think there is a difference performance wise, but I'm not a low-level guy.
A: As usually this is a question which asks for the following answer: "it depends" and I'll show by two examples.
IF NOT CONDITION
For the ASP .Net Web Forms validation I'm seeing very often this code
protected void btSubmit_OnClick(object sender, EventArgs e)
{
Page.Valide();
if (!Page.IsValid)
return;
var customer = new Customer();
// init 20 properties of customer
....
var bo = new CustomerBO();
bo.Save(customer);
}
There is another one much more popular:
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
}
}
IF CONDITION
public void UpdateCustomer(int customerId, string ...../*it might be a customer type also*/)
{
using (var ctx= CreateContext())
{
var customer = ctx.Customers.FirstOrDefault(c=>c.CustomerId = customerId);
if ( customer != null)
{
/*code update 20 properties */
}
}
}
I hope the code is clear :P
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iPhone - Objective C - UIScrollView inside UITableView rendering funny I'm currently working on an iPhone app that's doing some strange things with a UIScrollView inside a UITableView. This is my first foray into iPhone dev, so I'm sure it's something silly I'm missing.
In each UITableViewCell I am putting in a basic UITableViewCell. In that UITableViewCell is a Label and a UIScrollView.
The label and scrollview is setup and working properly, but when it first displays it is offset about 30 pixels down on the y axis than it should be, or is positioned by the XIB/NIB. I am not moving it around manually. The label shows up in the right spot. at 0,0. The UIScrollView should be showing up at 0,22 but is showing up closer to 0,40.
When I swipe to scroll the containing UITableView, then all the UIScrollViews will show up in the right spot assuming that when the UITableView scrolled that UITableViewCell went offscreen.
Here is the code for the UITableView.cellForRowAtIndexPath
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"GalleryRowCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
[cell.layer setMasksToBounds:TRUE];
[cell.layer setCornerRadius:10.0];
Contagion *c = (Contagion *)[self.dataSet objectAtIndex:indexPath.row];
GalleryRowViewController *subView = [[GalleryRowViewController alloc] initWithContagion:c];
[cell.contentView addSubview:subView.view];
subView.contagionName.text = c.name;
subView.contagion = c;
return cell;
}
Here is the code for my GalleryRowViewController.viewDidLoad
- (void)viewDidLoad {
[super viewDidLoad];
self.imageScroll.delegate = self;
[self.imageScroll setBackgroundColor:[UIColor blackColor]];
[self.imageScroll setCanCancelContentTouches:NO];
self.imageScroll.indicatorStyle = UIScrollViewIndicatorStyleWhite;
self.imageScroll.clipsToBounds = NO;
self.imageScroll.scrollEnabled = YES;
self.imageScroll.pagingEnabled = NO;
NSInteger x = 0;
CGFloat xPos = 0;
for (x=0;x<=10;x++) {
UIImage *image = [UIImage imageNamed:@"57-icon.png"];
UIImageView *imageView = [[UIImageView alloc] initWithImage:image];
[imageView setBackgroundColor:[UIColor yellowColor]];
CGRect rect = imageView.frame;
rect.size.height = 70;
rect.size.width = image.size.width;
rect.origin.x = xPos;
rect.origin.y = 5;
imageView.frame = rect;
[self.imageScroll addSubview:imageView];
xPos += imageView.frame.size.width+5;
}
[self.imageScroll setContentSize:CGSizeMake(xPos, [self.imageScroll bounds].size.height)];
}
--- EDIT FOR IMAGES ---
After App Loads: http://img809.imageshack.us/img809/4576/screenshot20110927at427.png
After Scrolling the rows offscreen and back: http://img690.imageshack.us/img690/9461/screenshot20110927at428.png
A: Well, as my previous response was at too low a level, let me take another shot at it.
First, I just noticed the core problem that you're using a viewcontroller for each cell. To quote Apple, " "A single view controller typically manages the views associated with a single screen’s worth of content." That would also get rid of your XIB (just manually configuring your scrollview), which I bet will get rid of your problem.
To proceed, your main choice is whether to create a ContagionTableViewCell class or not as suggested by Scott.
If so, following the Elements example, create a subclass of UITableViewCell ContagionTableViewCell with properties of a scrollView, a labelview and a contagion. Like they use a custom setter for the element, use one for the contagion, so that whenever it is assigned, it also updates the cells label (and associated pictures).
Move your imageScroll code from GalleryRowViewController.viewDidLoad into the ContagionTableViewCell init code. Put the image code into a new routine, which will be called from the contagion setter.
If NOT, then move the GalleryRowView Controller code into your UITableView. I suggest you take a look at cellForRowAtIndexPath in Apple's tableViewSuite, the fourth example on subviews. In particular, it shows this pattern of separating the creation of a cell (when you need a brand new one) vs configuring the cell (when reusing it). As you have 10 imageViews inside your scrollView, you'll have to decide whether to delete all those (and/or the scrollview), or just reach inside and update their images when a cell is reused.
A: Can you post a screenshot. Its a bit hard to visualize what you are describing. I'm not sure how you are computing y origin to be 22.
As a side note I believe its cleaner to do this by creatint your own TableViewCell subclass and use that instead of the default UITableViewCell. There is an example called Elements which shows how to do this properly: http://developer.apple.com/library/ios/#samplecode/TheElements/Introduction/Intro.html
A: Well, I don't know it's the cause of your problem, but you've definitely got an issue. Note that every time you are asked for a cell, you're adding the galleryRow subview. When a cell goes off-screen, it's put on the reusableCell queue. Then you're asked for another cell; you get it from the queue, it still has the old galleryRow subview, and now you add another one; so that's not good. You should either reuse or delete the old one.
Finally, why are you using UITableViewCellStyleSubtitle, and then not using any of the default fields in that UITableView?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: set up an action with a tab bar item - iphone I don't no if this is possible, but this there a way to treat a tab bar item click like a regular button click(action)? Here's the reason: I have a tab bar in my application, and for most of the tab bar items, I don't change the screen upon a touch, but I do change the data displayed in the view. It seems that it would be going a bit overboard to use a TabBarAppDelegate for this...is there a better way?
Thanks
A: Personally, I would use UISegmentedControl and place it in a UIToolbar or UINavigationBar. That way you get the same touch-to-change-data effect, but don't have to swap view controllers (or try to bypass switching tabs)
A: The most straightforward way is the UITabBarDelegate. Sorry. Implement your class and inherit the protocol by adding <UITabBarDelegate> after your class definition e.g.:
@interface MyViewController : UIViewController<UITabBarDelegate>
and then define the method tabBar:didSelectItem: in that class e.g.
- (void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item {
// Do Stuff!
// if(item.title == @"First") {...}
}
Then set the delegate on your tabbar like so: myTabBar.delegate = myClassInstance. The tabBar:didSelectItem: method can be anywhere including your view controller and is where you will get the event that the button was clicked. More info here:
http://developer.apple.com/library/ios/#DOCUMENTATION/UIKit/Reference/UITabBarDelegate_Protocol/Reference/Reference.html
A: I'd suggest going with a UIToolbar. Or make your own custom UIView and design it to your liking
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575430",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Windows Phone 7 swimming tiles effect I wonder how to achieve effect of swiming tiles (like in windows phone 7, when you start arrange start menu tiles - other ones swim softly and randomly).
Someone have any ideas?
A: Check out the HubTile implementation in the Windows Phone toolkit, full open source is up at http://silverlight.codeplex.com/ - it has a hub tile service that manages such communication.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575435",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: XCode Update - iOS Link Error I just converted my project up from Xcode 3 to 4 and updated to the latest SDK. The project runs fine when I open it in XCode 3, but there are errors when I run in XCode 4.
I am getting the following link error:
Undefined symbols for architecture armv7:
"_objc_memmove_collectable", referenced from:
__ZN9cPlaylistaSERKS_ in MediaItemManager.o
ld: symbol(s) not found for architecture armv7
From what I have read about memmove_collectable it has something to do with guards around garbage collected memory. However in my project settings are set to:
Obj-C Garbage Collection - Unsupported
I am not even sure there is garbage collection to be had in iOS. Anyone know what I might be doing wrong?
Some help demangling the name would be great too. My MediaItemManager is a C++ class, it does call new/delete and memset/memcpy. However none of them are in a function called Playlists. Here is evertying in MediaItemManager with the word Playlist in it. cPlaylist makes no calls to memset/memcpy functions.
cPlaylist* AllSongsPlaylist() { return mSongList; }
pPlaylistVec Playlists() { return &mPlaylists; }
cPlaylist* PlaylistByIndex(uint32 idx);
cPlaylist* PlaylistByName(NSString* name);
...
std::vector<cPlaylist> mPlaylists;
typedef std::vector<cPlaylist>* pPlaylistVec;
Edit:
It seems to happen with armv7 or armv6. It may be an installation issue with XCode, I am not sure how XCode installation should look though. I did have to add this symbolic link to get XCode building after the install.
iPhone Codesign object file format invalid or unsuitable
A: I assume that your C++ code is in a library. Did you rebuild the library?
The error suggests that your library needs to be rebuilt, because it doesn't contain armv7 symbols, as the error suggests. In other words, it's not a universal library. You'll need to rebuild that library, OR, change your primary project to build for armv6 only.
It is worth noting that Xcode4 defaults to building for armv7 only. If you want to support iOS4 versions earlier than 4.2, you have to add armv6 to the supported architectures in your build settings. AND, you have to rebuild any dependent libraries accordingly.
Does that make any sense?
A: So you are probably gonna hate this because it takes an hr or so but what I have had to do with these linker errors is completely uninstall xcode and then restart reinstall xcode and restart. Usually that is the issue because installing xcode 3 and then xcode 4 without uninstalling xcode 3 usually causes huge problem. So you are gonna have to go to terminal and cd to your developer folder and sudo /Library/uninstall-devtools --mode=all sorry man :( Hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575437",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Getting own EF 4.1 Code First classes to work with .NET Membership I am working on a simple web application that is built with EF 4.1 Code First and MVC3. My Domain Model sits in a project outside the MVC3 project.
I have gotten to the stage where my web application is more or less complete. However right now, my application doesn't have any form of authorization or authentication. So a regular user can get to Actions and Controllers that only an Admin is suppose to have access to.
My question is, how do I get my web application to work with the .NET Membership ? Because I am aware that the .NET Membership has many database tables of its own !
My knowledge is fairly limited, thus any clear, easy to follow responses would be greatly appreciated.
After the Membership is set up, I know my way around applying Authentication and Authorization to Actions and Controllers.
Thank You.
A: Go into your C:\Windows\Microsoft.NET\Framework\v2.xx or v4.xx\ and execute aspnet_regsql, this will launch a wizard that allows you to choose your database and it will add the stored procs and tables to allow membership to function.
Then you run the ASP.NET configuration wizard (the little toolbox icon at the top of your solution explorer) and then configure your roles and accounts. See this page and skip to the Configuring the website for membership and roles section.
A: ASP.Net membership is actually kinda interesting and frustrating to an extent. To you run a tool called aspnet_regsql.exe found in your Windows\Microsoft.net\Framework folder which generates all of the necessary tables to get it running. Next move onto your Web.config file. If you started with your basic ASP.NET MVC 3 template then you should have a <connectionStrings> entry under the name "ApplicationServices". Change that to your database connection string. This is what the membership provider uses to hook everything up. If you look through the rest of the config file there should be sections for <authentication>, <membership>, <profile>, and <roleManager>. These deal with the various sections and settings that the ASP.Net user management is broken into.
At this point everything should be hooked up. If you select your project in the solution explorer, a little red hammer icon should appear. This is the ASP.NET configuration manager. You can use this to set up different profiles and manage different users.
Now this stuff won't be connected to your EF4.1 code first stuff at all. Instead, you can interact with your membership provider through static classes Membership and Roles. If you take a look at the AccountController on a default ASP.Net MVC 3 Internet application template it will give you a good idea how it works.
After working with this stuff for several months, I found it much easier to basically write your own. Tying things together eventually becomes a huge pain and there is a whole lot of extras that the membership provider gives you that is unnecessary for small applications.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: RabbitMQ + Node.JS Connection issue, frame size too large? I have been playing around with RabbitMQ with apache + php and wanted to see how it compared to Node.JS in performance.
Using the latest node.js (0.4.12) and amqp module (npm install amqp), i get a unknown exception connecting which it seems like it is the frame size causing error (line 181 in amqp.js), removing the error from the code just throws another related to allocating too large of an array size.
the RabbitMQ server is is just a "apt-get install rabbitmq-server" with default configuration. This works in PHP just fine.
Starting ... AMQP URL: amqp://localhost
events.js:47
throw new Error("Uncaught, unspecified 'error' event.");
^
Error: Uncaught, unspecified 'error' event.
at Connection.emit (events.js:47:15)
at AMQPParser.onError (/nodeJS_stuff/node_modules/amqp/amqp.js:839:12)
at AMQPParser.throwError (/nodeJS_stuff/node_modules/amqp/amqp.js:145:25)
at AMQPParser.execute (/nodeJS_stuff/node_modules/amqp/amqp.js:181:18)
at Connection.<anonymous> (/nodeJS_stuff/node_modules/amqp/amqp.js:851:12)
at Connection.emit (events.js:64:17)
at Connection._onReadable (net.js:672:14)
at IOWatcher.onReadable [as callback] (net.js:177:10)
Any one ever run into this? i have tried a couple examples and i always get this. i am running this on EC2 as well, if that helps any.
A: I just saw this problem today. It seemed to me like a mismatch between the versions of rabbitmq and amqp. I was testing two versions of node-amqp (0.0.2 and 0.1.0) and rabbitmq (1.7.2 and 2.3.1). I found out that node-amqp 0.0.2 works with both versions of rabbitmq, but the newer node-amqp (0.1.0, actually as of version 0.0.6) doesn't work with the older rabbitmq. So try rolling back your node-amqp to an older version and see if it works.
A: It is definitely a version mismatch between amqp and the installed version of RabbitMQ. The problem is most probably due to rabbitmq-server being too old. I had the exactly same problem on my Debian machine and the RabbitMQ installation guide pointed me to the right direction.
Uninstall your current version of rabbitmq-server and download the most recent one from the RabbitMQ website.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575440",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: BDD and ASP.NET MVC - Finding the Highway About half a year ago, I started digging into unit testing. I made my way into TDD (or what I thought it was) and now I want to develop a MVC Application behavior-driven.
The concept of acceptance testing (real end-to-end) is new to me, because my last project didn't run in a acceptance testable environment.
I started out by reading some good articles, notably Sanderson's http://blog.stevensanderson.com/2010/03/03/behavior-driven-development-bdd-with-specflow-and-aspnet-mvc/ and am backing up my MVC skills by reading his book on that topic.
I'm using SpecFlow and SimpleBrowser for end-to-end testing.
Driving navigation through the navigation bar was a piece of cake, however I'm stuck now.
I aim to implement user accounts for further creating articles and commenting. Driving the registration process gave me headaches. Given this feature file:
Feature: User accounts
In order to customize and influence page content
As a user
I want to able to create an own user account
Scenario: Create a user
Given I am on the /Account/Create page
When I fill out the registration formular as follows
| NickName | EmailAddress |
| test123 | test.address@test-server.com |
And I click the "Create" button
And I clicked the link in the authentication mail
Then I should be on the root page
And I should see the message "Welcome test123!"
I can't really figure out how to provide the necessary testing environment (a mail server in this example) and make the test less brittle (think of relabeling the "Create" button to "Submit"). Let alone weaving in a capture generator to prevent automatic user creation (oh irony) at a later time. Maybe I'm just thinking too much ahead, which you actually shouldn't in TDD, but there are times I'm just staring at the screen and thinking about my next test.
Soo.. after that wall of text the actual question: How should I implement this kind of behavior?
*
*Stick to UI level tests and refactor as necessary for implementing capture logic
*Fall back to controller level testing
*Any other way you enlighten me on
A: I cannot say what is right or wrong here, so I'll just say what I do, since it works pretty well for me.
I use SpecFlow for testing my service layer. In ASP.net MVC, that would be the controller. As you mentioned, that kind of UI testing is very brittle, so I only recur to it when using some kind of advanced JavaScript UI.
That way, my testing stack looks something like this:
*
*NUnit tests for more complex algorythms in the model
*SpecFlow for testing the controller. This assures that the views receive what they should and that the models interact as intended.
*QUnit tests for my JavaScript models, which I use mainly with Knockout JS (those two look like they were made for each other)
*Manual acceptance tests (very coarse-grained and not too many of these), well documented
*A few (very few) automated UI tests with WatiN for more advanced UIs
That said, about 75% of the tests written are for item 2 (SpecFlow) and 15% for item 3 (QUnit). That is just how it seems to work for me, but any suggestions are very welcome too.
A: I would not combine both the clicking on create button and clicking on the confirmation link in one test. I would finish the first test (clicking on create button) as I should see some message that says to check my email. If you want to test the rest of the behavior, you should create another test where given a confirmation URL and clicking on it, you should see the welcome page.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: does the existence of an asterisk in a select exclude other columns? This question is all about laziness... I'd like to do something like this:
select some_func(some_col), * from my_table
So that I don't have to do this:
select some_func(some_col), col_1, col_2... col_ad_infinitum from my_table
Is there any way to make the first query work? This is the error I get when I run it:
ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '* from my_table' at line 1
A: Unfortunately, mysql only supports the asterisk at the start of the column list (unlike every other DB I am familiar with)
(Edited: start not end - oops!)
A: Change the order of your select params:
select *,some_func(some_col) from my_table
Anyway, as the Zen of Python says: "Explicit is better than implicit". Always try to write the fields you're selecting, and if it's posible try to put the table they're from too, you can use an alias. Your future YOU will thank you.
select t.some_col from my_table t
A: Do you mean that in MySQL your first query:
SELECT some_func(some_col), *
FROM my_table
produces this error?:
Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*' at line 1
You can change your code into (this results in no errors!):
SELECT *, some_func(some_col)
FROM my_table
or into this, if you want to have the calculated columns first:
SELECT some_func(some_col), t.*
FROM my_table AS t
A: When I do that with PostgreSQL, I get the column(s) I specify followed by all the other columns (possibly repeating the column(s) I specified).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575443",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Thread.interrupt() and java.io.InterruptedIOException I'm running Java 1.5 on Solaris 10.
My program is a standalone java program, using java concurrency package and log4j-1.2.12.jar to log certain information. primary logic is as below
ExecutorService executor = new AppThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(Integer.MAX_VALUE), new AppThreadFactory("BSRT", true), new ThreadPoolExecutor.CallerRunsPolicy());
CompletionService<Integer> completionService = new ExecutorCompletionService<Integer>(executor);
for (final Integer id : taskList) {
Callable<Integer> c = new Callable<Integer>() {
public Integer call() throws Exception {
int newId = DB operation(id);
return newId;
}
};
completionService.submit(c);
}
logger.debug("Start retrievie result");
for (Integer id : taskList) {
try {
Future<Integer> future = completionService.poll(1, TimeUnit.SECONDS);
Integer taskId=null;
if (future != null) {
logger.debug("future is obtained.");
taskId = future.get();
} else {
logger.error("wait too long and get nothing!");
break;
}
if (taskId != null) {
taskIdList.add(taskId);
}
} catch (ExecutionException ignore) {
// log the cause and ignore this aborted task,coninue with
// next available task.
logger.warn(ignore.getCause());
} catch (InterruptedException e) {
logger.warn("interrupted...");
// Re-assert the thread’s interrupted status
Thread.currentThread().interrupt();
}
}executor.shutdown();
During the execution of my program, Sometimes (not always) I'm getting this error ...
executor.shutdown();
will not be able to interrupt AppThread after return from the call super.run();
because the woker is already removed from workers set used internally by ThreadPoolExecutor, executor does not have reference to AppThread from that point of time.
btw: the log file is accessible and size is big enough.
log4j:ERROR Failed to flush writer,
java.io.InterruptedIOException
at java.io.FileOutputStream.writeBytes(Native Method)
at java.io.FileOutputStream.write(FileOutputStream.java:260)
at sun.nio.cs.StreamEncoder$CharsetSE.writeBytes(StreamEncoder.java:336)
at sun.nio.cs.StreamEncoder$CharsetSE.implFlushBuffer(StreamEncoder.java:404)
at sun.nio.cs.StreamEncoder$CharsetSE.implFlush(StreamEncoder.java:408)
at sun.nio.cs.StreamEncoder.flush(StreamEncoder.java:152)
at java.io.OutputStreamWriter.flush(OutputStreamWriter.java:213)
at org.apache.log4j.helpers.QuietWriter.flush(QuietWriter.java:57)
at org.apache.log4j.WriterAppender.subAppend(WriterAppender.java:315)
at org.apache.log4j.DailyRollingFileAppender.subAppend(DailyRollingFileAppender.java:358)
at org.apache.log4j.WriterAppender.append(WriterAppender.java:159)
at org.apache.log4j.AppenderSkeleton.doAppend(AppenderSkeleton.java:230)
at org.apache.log4j.helpers.AppenderAttachableImpl.appendLoopOnAppenders(AppenderAttachableImpl.java:65)
at org.apache.log4j.Category.callAppenders(Category.java:203)
at org.apache.log4j.Category.forcedLog(Category.java:388)
at org.apache.log4j.Category.debug(Category.java:257)
at AppThread.run( AppThread.java: 33)
33 is the line: if (debug)
logger.info("Exiting " + getName());
import java.util.concurrent.atomic.AtomicInteger;
import org.apache.log4j.Logger;
public class AppThread extends Thread {
public static final String DEFAULT_NAME = "MyAppThread";
private static volatile boolean debugLifecycle = false;
private static final AtomicInteger created = new AtomicInteger();
private static final AtomicInteger alive = new AtomicInteger();
private static final Logger logger = Logger.getLogger(AppThread.class);
private boolean dump = false;
public AppThread(Runnable r) {
this(r, DEFAULT_NAME);
}
public AppThread(Runnable runnable, String name) {
super(runnable, name + "-" + created.incrementAndGet());
logger.debug(name + "'s constructor running");
}
public void interrupt() {
if (!dump) {
super.interrupt();
}
if (dump) {
logger.debug("interrupt : " + getName() + " <<<");
Thread.dumpStack();
logger.debug("interrupt : " + getName() + " >>>");
}
}
public void run() {
boolean debug = debugLifecycle;
if (debug)
logger.info("Created " + getName());
try {
alive.incrementAndGet();
super.run();
logger.debug("running!");
} finally {
alive.decrementAndGet();
dump = true;
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
logger.debug(e);
}
if (debug)
logger.info("Exiting " + getName());
}
}
public static int getThreadsCreated() {
return created.get();
}
public static int getThreadsAlive() {
return alive.get();
}
public static boolean getDebug() {
return debugLifecycle;
}
public static void setDebug(boolean b) {
debugLifecycle = b;
}
}
Another problem is that in order to debug the cause of java.io.InterruptedIOException , I added
try {
Thread.sleep(100000);
} catch (InterruptedException e) {
logger.debug(e);
}
in finally clause in the run method for AppThread. when InterruptedException is catched in the finally clause, the override interrupt() method is never called. so who interrupt AppThread? is the same guy cause java.io.InterruptedIOException?
A: Yes:
shutdownNow
Attempts to stop all actively executing tasks, halts the processing of waiting tasks, and returns a list of the tasks that were awaiting execution.
There are no guarantees beyond best-effort attempts to stop processing actively executing tasks. For example, typical implementations will cancel via Thread.interrupt(), so any task that fails to respond to interrupts may never terminate.
JavaDoc.
Simply use shutdown() instead of shutdownNow(). When you are forcibly calling shutdownNow() this is what you should expect - JVM gracefully interrupts I/O and shuts down the thread as fast as possible.
However I would make sure that logging isn't the bottleneck in your application. Simply make few thread dumps during the execution of your program and see how often threads are writing or waiting for I/O. Poor man's profiling.
A: Interrupting the worker threads is actually a feature of the Executor framework to allow worker threads to gracefully shut down when asked to do so through interrupt(). It's documented behavior for shutdownNow().
If you don't want this, call shutdown() -- it won't interrupt() your worker threads, the Executor will just stop accepting new tasks.
A: I have similar problems.
My research went so far that Thread.interrupt() sets the interrupt flag. This leads to an interrupted IO operation deep in the Java Stack. But the IO methods are typically not declared to throw an InterruptedException.
Instead an InterruptedIOException is thrown and the interrupted state of the Thread is cleared!. If you wrote a Worker that expects (catches) IOExceptions, you have to catch the InterruptedIOException separately and call Thead.currentThread().interrupt() in the catch clause.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Change column name by looking up I know that I can change a data.frame column name by:
colnames(df)[3] <- "newname"
But there might be cases where the column I want to change is not in the 3rd position. Is there a way to look up the column by name and change it? Like this...
colnames(df)[,"oldname"] <- "newname"
BTW, I have tried this code and I keep getting incorrect number of subscripts on matrix.
Thanks.
A: colnames(df)[colnames(df)=="oldname"] <- "newname"
or
names(df)[names(df)=="oldname"] <- "newname"
(since names and colnames are equivalent for a data frame)
or you might be looking for
library(reshape)
df <- rename(df,c(oldname="newname"))
A: I was using package data.table today and when I tried to change a column name using my usual method a message appeared recommending this approach:
library(data.table)
df <- read.table(text= "
region state county
1 1 1
1 2 2
1 2 3
2 1 4
2 1 4
", header=TRUE, na.strings=NA)
df
setnames(df, "county", "district")
df
A: A somewhat more general approach that will replace all of the "old"s at the beginning of any current name with "new" in the same character location:
names(df) <- sub("^old", "new", names(df) )
A: colnames(df)[colnames(df)=="oldname"] <- "newname"
or just names
names(df)[names(df)=="oldname"] <- "newname"
There are various functions for renaming columns in packages as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Reading a date string with a different time zone in javascript I have a datestring, pulled from an external source, that looks like this:
9/25/2011 4:38:40 PM
That source in the the PDT timezone.
I'd like to create a UTC date out of that information, using date.js. I'm using this code to parse it at present:
var dateString = '9/25/2011 4:38:40 PM';
var d = Date.parseExact('9/25/2011 4:38:40 PM', 'M/d/yyyy H:m:s tt');
While this does load the date, it does so as if it were in my timezone. How can I tell date.js that the date I'm telling it is from a different time zone?
A: putting an e in a date format will signify the timezone. I haven't tested this, but:
Date.parseExact(dateString + " PDT", "M/d/yyyy H:m:s tt e")
Does not account for daylight savings time shifts (PST instead of PDT), but you get the gist.
A: Use timezone format specifier...
var dateString = '9/25/2011 4:38:40 PM EST';
var d = Date.parseExact(dateString, 'M/d/yyyy H:m:s tt Z');
A: Have you tried something like this?:
var dateString = '9/25/2011 4:38:40 PM';
var date = Date.parseExact(dateString, format);
var utc_date = new Date(date.getTime() - (date.getTimezoneOffset() * 60000))
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575453",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: PHP replace ereg(i)(_replace) globally I have 150+ PHP files I need to change (updating ereg to preg_match). I tired to update them manually but it takes for ever and I want to make sure all my replace will work the first time. What can I do to do this kind of operation?
Here's some example of my ereg(i)
if(eregi("^[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}$", $ip)) { /* ... */}
if (eregi($regexp, $label, $match)) { /* ... */}
$string = eregi_replace("[[:space:]]+", ' ', $string);
Thanks
A: #!/bin/bash
perl -p -i -e "s/eregi_replace *\\( *\"([^\@]+?)(?<\!\\\\)\", */preg_replace(\"\@\\1\@i\", /g" $1
perl -p -i -e "s/eregi_replace *\\( *\'([^\@]+?)(?<\!\\\\)\', */preg_replace(\'\@\\1\@i\', /g" $1
perl -p -i -e "s/ereg_replace *\\( *\"([^\@]+?)(?<\!\\\\)\", */preg_replace(\"\@\\1\@\", /g" $1
perl -p -i -e "s/ereg_replace *\\( *\'([^\@]+?)(?<\!\\\\)\', */preg_replace(\'\@\\1\@\', /g" $1
perl -p -i -e "s/eregi *\\( *\"([^\@]+?)(?<\!\\\\)\", */preg_match(\"\@\\1\@i\", /g" $1
perl -p -i -e "s/eregi *\\( *\'([^\@]+?)(?<\!\\\\)\', */preg_match(\'\@\\1\@i\', /g" $1
perl -p -i -e "s/ereg *\\( *\"([^\@]+?)(?<\!\\\\)\", */preg_match(\"\@\\1\@\", /g" $1
perl -p -i -e "s/ereg *\\( *\'([^\@]+?)(?<\!\\\\)\', */preg_match(\'\@\\1\@\', /g" $1
Here's a little bash script that I use. Someone with more time than me can probably squash all of this into less (1?) regular expressions, but it should do the trick. Feel free to replace @ with your delimiter of choice. Just paste this into a file, chmod +x it, and then call it, passing the file as an argument.
If you need to use it en masse, something like this should suffice:
find /path/to/your/project -name '*.php' -exec foo {} \;
Where foo is whatever you named the bash script.
Note: This isn't perfect, so you'll still need to manually change any fringe cases that it misses, but it will still save you a lot of work. Also note that this does in-place file edits.
A: replacing the actual ereg call would be a fairly simple matter of doing a search/replace operation. But actually fixing up your pattern to include the delimiters that preg requires is somewhat non-trivial. You can easily do:
$newcode = str_replace('eregi("', 'preg_match("/', $oldcode));
but then you'll still have to find where the pattern ends to add a delimiter there, as well as the i modifier. And you'd have to do this for every variant of ereg calls as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575455",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Navigation and URL rewriting in AJAX heavy page I have an ecommerce site, that isn't up to par for what we need. It was originally developed using one main page that contains user controls for item search and catagories navigation... I have a search ascx and a catagories.aspx, that talk to a restuls.ascx through default.aspx..
Anyway, there is no navigation on this site. I've looked around at URL rewriting, but most of the material was dated. Also I'm not sure this is the best route. Most of what I'm reading on URL rewriting is to put you at a certain point in a page, as opposed to bringing back a colection of search restuls for example. I'm also seeing in some places where I think people are writing page load events to look for parameters to recreate the dynamic page.
*
*Is URL rewriting the best answer?
*If it is, would I rewrite the page load to look for parameters to trigger the search again to bring back the results? Or is there a less manual and possibly less resource heavy way of accomplishing this?
I would like to make my site more SEO but navigation is the main issue at the moment. I'm using dotnet 3.5sp1.
A: The option are:
*
*URL ROUTING within the .net framework
*URL REWRITING with IIS (i think from version 6)
*Or URL REWRITER
I recently had the same problem and I solved with URL ROUTING.
Whatever you choose, make sure you point the OLD Url (not rewritten maybe present on the SERP) to the new URL using 301 Permanent redirect, so you inform Search Engine of the new path without loosing Page Rank.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575456",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C++: Should I initialize pointer members that are assigned to in the constructor body to NULL? Suppose I have:
// MyClass.h
class MyClass
{
public:
MyClass();
private:
Something *something_;
}
// MyClass.cpp
MyClass::MyClass()
{
something_ = new Something();
}
Should I initialize something_ to NULL (or 0) in the constructor initialization list of the MyClass constructor? Or is that not necessary because I'm assigning to it in the body of the constructor? What is the recommended practice?
A: Generally speaking - no. But if somewhere in your constructor pointer is used before it has been initialized then you get undefined behaviour. However, the biggest problem that you have is this - if exception is thrown in constructor, its destructor is not called. So imagine you have two pointers to objects and allocation of the first object succeeds while the second allocation fails, in that case you end up with a resource leak. This can be solved by using "smart" pointers. But in that case they will be initialized in initialization list, and if you don't want to assign value to them twice then you better allocate memory in there rather than in constructor body.
A: Generally you only assign it once, in the initialization list or the body, unless the body initialization may or may not happen, or has prerequisite code:
MyClass::MyClass()
{
//this code must happen first
// _now_ max is known
something_ = new Something(max);
}
MyClass::MyClass()
{
if (max)
something_ = new Something(max);
else
something_ = NULL;
}
MyClass::MyClass()
: something_(new Something())
//as pointed out in the comments, use smart pointers
{
}
A: Not necessary, especially if you immediately initialize in the constructor body, however if initialization is not so obvious then why not NULL it to avoid accidental access to uninitialized variable.
*
*minimal performance overhead
*saves so much debugging/troubleshooting time with crazy bug hunting
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: Foreign Keys auto increment does not work in sqlite .NET provider I insert multiple data into a sqlite table and get always the same ID back. But the field Id is configured as PK + autoinc Id.
I use this as connection string:
public static void SetConnectionString(string dataDataAccessPath)
{
_connectionString = String.Format(@"Data Source={0};Foreign Keys=ON", dataDataAccessPath);
}
This "Foreign Keys=ON" was implemented for the connection besides the "PRAGMA foreign_keys = ON;" which had to be executed for every opened connection.
Now I wonder why the new attribute on the connectionstring does not work...
Do I something wrong?
A: I'm not an expert on SQLite (in fact I have no practical experience with it) but I would imagine that whether or not your IDENTITY fields automatically increment with your insert has something to do more with the definition of the table than with the connection string you are using.
Be reminded that you cannot increment a FOREIGN KEY per se, but rather you need to increment the table with the IDENTITY field that serves as the PRIMARY KEY that the FOREIGN KEY then references.
Can you add the definition of the table that you are having trouble with?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575462",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ajax to ActionResult, getting Model I have an action (Index) that return a View with a concrete model.
Inside that view (Is a calendar) I have two buttons to change months.
When I click one of those I call back Index action to that will return the same view with a modified model.
$("#right").live("click", function () {
$.post($(this).attr("href"), function (response) {
$("#wrapper").replaceWith($(response).filter("div#wrapper"));
});
return false;
});
So, I click #right and it call /Home/Index and Index return something like:
return View(new DateViewModel(dt, _bDays.GetDaysFromMonth(dt)));
So as you see, I replace div#wrapper with the new one. Perfect but...
Is there a way to get the model of the response? I mean, that action return a view with a model and apart from getting the concrete div I want the model.
Any idea?
A: I don't know why you would need the model in the AJAX callback, and thus there is probably a better solution than the one I am about to propose. So you could have your controller action render the partial view into a string and then return a JSON object containing both the HTML and the model:
[HttpPost]
public ActionResult MyAction()
{
MyViewModel model = new DateViewModel(dt, _bDays.GetDaysFromMonth(dt));
string html = RenderPartialToString("partialName", model);
return Json(new { Model = model, Html = html });
}
and in your AJAX callback:
$.post($(this).attr("href"), function (response) {
var model = response.Model;
var html = response.Html;
$("#wrapper").replaceWith($(html).filter("div#wrapper"));
});
A: One possible approach would be to call a separate controller action and return a JsonResult:
[HttpPost]
public ActionResult MyAction()
{
return Json(new DateViewModel(dt, _bDays.GetDaysFromMonth(dt)));
}
This action will return a JSON representation of your ViewModel that you can reference in your AJAX response.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to send Method's name for elements I'm making method to make button easily. but I don't know how to send method's name.. which is a button have to be called when user press this button. Is there any way to send this name?
I want to know "???????????????????"part on my source below..
this source is part of "Support.m" which I'm making.
Thanks..
+ (id)CreateButton:(id)layer (NSString*)filename secondfilename:(NSString*)filename2 sameimage:(BOOL)sameimage position:(CGPoint)position
{
CCSprite *sprite1 = [CCSprite spriteWithSpriteFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:filename]];
CCSprite *sprite2 = [CCSprite spriteWithSpriteFrame:[[CCSpriteFrameCache sharedSpriteFrameCache] spriteFrameByName:filename2]];
CCSprite *sprite1 = [CCSprite spriteWith
CCMenuItem *MenuItem = [CCMenuItemImage itemFromNormalSprite:sprite1 selectedSprite:sprite2 target:layer selector:@selector(???????????????????????????????)];
MenuItem.position = position;
CCMenu *Menu = [CCMenu menuWithItems:MenuItem, nil];
Menu.position = CGPointZero;
return Menu;
}
A: Just put the name of the method which you want to be called when that menu item is selected:
CCMenuItem *MenuItem = [CCMenuItemImage itemFromNormalSprite:sprite1
selectedSprite:sprite2
target:layer
selector:@selector(methodToRunWhenMenuItemIsSelected:)];
Whatever object the target is, in this case layer then needs to have a method of that name implemented:
- (void) methodToRunWhenMenuItemIsSelected: (CCMenuItem *)item {
// Do something interesting
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575469",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Readonly text box not allowing menuitem shortcut I have a text box which is read only. I also have a tool strip menu item which has a short cut of Ctrl + R. When the focus is in the textbox the toolstrip menuitem shortcut no longer works.
I can intersect the key down event and check if the key was Ctrl + R, but since I am using a generic text box control, this would take raising an event or passing a delegate to call given specific keys to my generic control.
Does anyone have any experience getting a toolstip menuitem's shortcut to fire if the focus is on a read only control?
A: protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
{
if (keyData == (Keys.Control | Keys.R))
{
MessageBox.Show("Handle with care! :)");
}
return base.ProcessCmdKey(ref msg, keyData);
}
Put that logic on the form that contains the read-only control.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Assigning issue with numpy structured arrays I was trying this simple line of assigning codes to a structured array in numpy, I am not quiet sure, but something wrong happens when I assign a matrix to a sub_array in a structured array I created as follows:
new_type = np.dtype('a3,(2,2)u2')
x = np.zeros(5,dtype=new_type)
x[1]['f1'] = np.array([[1,1],[1,1]])
print x
Out[143]:
array([('', [[0, 0], [0, 0]]), ('', [[1, 0], [0, 0]]),
('', [[0, 0], [0, 0]]), ('', [[0, 0], [0, 0]]),
('', [[0, 0], [0, 0]])],
dtype=[('f0', '|S3'), ('f1', '<u2', (2, 2))])
Shouldn't the second field of the subarray equals at this stage
[[1,1],[1,1]]
A: I think you want to set things slightly differently. Try:
x['f1'][1] = np.array([[1,1],[1,1]])
which results in:
In [43]: x = np.zeros(5,dtype=new_type)
In [44]: x['f1'][1] = np.array([[1,1],[1,1]])
In [45]: x
Out[45]:
array([('', [[0, 0], [0, 0]]), ('', [[1, 1], [1, 1]]),
('', [[0, 0], [0, 0]]), ('', [[0, 0], [0, 0]]),
('', [[0, 0], [0, 0]])],
dtype=[('f0', '|S3'), ('f1', '<u2', (2, 2))])
This is not to say that this isn't strange behavior though since both x['f1'][1] and x[1]['f1'] print the same results, but clearly are different:
In [51]: x['f1'][1]
Out[51]:
array([[1, 1],
[1, 1]], dtype=uint16)
In [52]: x[1]['f1']
Out[52]:
array([[1, 1],
[1, 1]], dtype=uint16)
In [53]: x[1]['f1'] = 2
In [54]: x
Out[54]:
array([('', [[0, 0], [0, 0]]), ('', [[2, 1], [1, 1]]),
('', [[0, 0], [0, 0]]), ('', [[0, 0], [0, 0]]),
('', [[0, 0], [0, 0]])],
dtype=[('f0', '|S3'), ('f1', '<u2', (2, 2))])
In [55]: x['f1'][1] = 3
In [56]: x
Out[56]:
array([('', [[0, 0], [0, 0]]), ('', [[3, 3], [3, 3]]),
('', [[0, 0], [0, 0]]), ('', [[0, 0], [0, 0]]),
('', [[0, 0], [0, 0]])],
dtype=[('f0', '|S3'), ('f1', '<u2', (2, 2))])
I'd have to think about it a bit more to figure out exactly what is going on.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575471",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to display JLabel text for 1 second? I am wanting my error messages to display in a JLabel temporarily, then set the text back to "". But instead it looks like it just skips over setting the message. I've stepped through the code and found it's setting the text, but it isn't displaying for some reason. I've even tried the repaint() method, but still nothing. Any help would be greatly appreciated.
Here's what I have:
public void displayError(String msg){
int ctr = 0;
while(ctr<2){
try {
lblError.setText(msg);
lblError.repaint();
Thread.sleep(500);
} catch (Exception e) {}
ctr++;
}
lblError.setText("");
}
A: I'm assuming that you're calling this method on the event dispatch thread. (If not, you should be, since almost all Swing calls should be made there.)
You need to allow the thread to retake control, which it's not able to do because of your Thread.sleep(). Look instead at invoking a Timer or SwingWorker background thread which, after two seconds, will reset the text.
http://download.oracle.com/javase/tutorial/uiswing/concurrency/dispatch.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575478",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Minimum element in empty array If you have a function int getMin(int a[], int n) then what would you say is the cleanest solution to deal with the empty array case?
A: Assuming you're looking for the minimum value in the array how about:
if (!n)
throw YourPreferredException();
Or:
#include <limits>
//...
if (!n)
return std::numeric_limits<int>::max();
Or, if it should never happen:
#include <cassert>
//...
assert(n);
It depends on the application and the values you're expecting to be passing in. What makes most sense and what fits the existing code base is hard to guess.
A: Maybe instead, do it the way the standard library does: Take two iterators as parameters and return the end parameter if the sequence is empty. Better still use min_element instead of rolling your own.
If you need to do it the array/length way either throw or return std::numeric_limits<int>::max()
A: Return a pointer to the minimum element instead of the element itself. This way, a pointer value of one past the end of the array can indicate not found. (Or in this case empty)
This is the strategy taken by std::min_element, which already implements what you're doing.
You can even implement this in terms of std::min_element:
int* getMin(int a[], int n)
{
return std::min_element(a, a+n);
}
A: There is definitely no "cleanest solution" absent an understanding of the domain. Mathematically, the infimum of any set of values from a domain is the greatest lower bound (in the domain) of all elements of the set. For the extended integers, this would be +infinity for an empty set. (See, e.g., the Wikipedia article on Empty Set) If your domain is all C++ int values, a (mathematically consistent) return value would then be INT_MAX.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: restrict file upload selection to specific types Anyway to restrict the selection of file types via the <input type="file" /> element?
For instance, if I wanted only images types to be uploaded, I would restrict the possible selections to (image/jpg,image/gif,image/png), and the selection dialog would grey out files of other mime types.
p.s. I know that I can do this after the fact with the File API by scanning the .type attributes. I'm really trying to restrict this before hand.. I also know I can do this via flash, but I do NOT want to have use flash for this.
A: It's better to let user select any file, and then check its type - this is better supported by the browsers:
var
file = (el[0].files ? el[0].files[0] : el[0].value || undefined),
supportedFormats = ['image/jpg','image/gif','image/png'];
if (file && file.type) {
if (0 > supportedFormats.indexOf(file.type)) {
alert('unsupported format');
}
else {
upload();
}
}
You can also check for file size using file.size property.
A: There is an html attribute for this specific purpose called accept but it has little support across browsers. Because of this server side validation is recommended instead.
<input type="file" name="pic" id="pic" accept="image/gif, image/jpeg" />
If you don't have access to the backend have a look at a flash based solution like SWFUpload.
See more on this here: File input 'accept' attribute - is it useful?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7575482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "54"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.