text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Keep posting number on line with for statements PHP I am looking for something that shows a number on each line, rather than just all the numbers after the page has loaded.
the code for instance is:
for($a=0;$a<=10;$a++){
echo $a;
echo '<br>';
}
The output would of course be:
1
2
all the way to 10 after the page would load,
but I want it to show,
1
then 2, without the browser just loading everything.
I want a pause and to watch the numbers increase.
A: You can force php to flush it's output with flush(). Of course, if PHP's output buffering is enabled, this will only flush it into the output buffer.
Once PHP flushes, it's not guaranteed to go directly to the browser, PHP flushes to the web server, which sends it on to the browser depending on the web server's own configuration.
However, as far as PHP is concerned, the following will work (at least on the command line, or on your webserver, if it's configured right):
demo.php
<?php
ob_end_flush(); // make sure output buffering is off
for($i=0;$i<10;$i++){
echo "{$i}\n";
flush();
sleep(1);
}
From the command line:
$ php demo.php
should display 1... 2 ... 3 ... with a one second delay between.
EDIT: One more thing I thought of. Even if the web server does "stream" your output as you flush from PHP, if your output is in the middle of other markup, the users' browsers may not render anything until the entire response is received.
That said, if you're doing something basic, I've used the above strategy to output status for long-running utility scripts. In those cases, I probably didn't even include tags in my output, but it worked like you want it to (at least on the servers I was dealing with at the time).
This approach might be good enough for internal tools, but I'd never rely on this technique for anything end-users might ever see.
A: Here is a php script which will accomplish this. It isn't really a PHP script, but rather a page that accomplishes the same with javascript. Which gives you much more control with what happens on the clients browser. With output buffering and everything else, there's no way to guarantee the browser will render it as you want to just controlling the output with PHP.
<?php ?>
<html>
<head>
<title>
The Counting Page
</title>
<script type="text/javascript">
var oldbody;
function countTo(a,b)
{
if(oldbody == null)
{
oldbody = document.body.innerHTML;
document.body.innerHTML = '';
}
if(a <= b)
{
elem = document.createElement("div");
elem.innerHTML = a;
document.body.appendChild(elem);
a++;
setTimeout('countTo(' + a + ',' + b + ')',1000);
}
else
{
document.body.innerHTML = oldbody;
}
}
</script>
<head>
<body onload="countTo(1,10)">
Here is the body text.
</body>
</html>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591757",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Connection pool detection I am creating an application in java using glassfish server in netbeans. I've created connection pool and data source for sql query execution. I have created a sample jsp page to check the transection using connection pool which is as follows.
And as I run this file in browser I get this internal error.
"javax.servlet.jsp.JspException: Unable to get connection, DataSource invalid: "java.sql.SQLException: Error in allocating a connection. Cause: null""
A: Got the solution!! :)
The problem was. I didn't set password for mysql. At the time setting up a new connection pool, providing password is mendatory. so I just added the password and now it is working. I hope if anybody else faces the problem then it would be helpful
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591758",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: log4net writing to file. How to open up permissions I was happily using log4net with my WPF program on an XP machine and happily using a fileAppender FileAppender to write log messages to c:\log.txt. All was well. However, it does not work on a Windows 7 machine. No error or anything, just that the file isn't created, much less logged to. A little research reveals that it's a file permissions problem (UAC) with Windows 7, and in fact it works if I run the executable as administrator. It doesn't work if I just click on it (even though I'm logged on as administrator) and it doesn't work when I launch from Visual Studio.
Questions:
1. Can someone point me to an example where I ask for permission to write to one and only one file (C:\log.txt). I've seen some examples of where the app.config is configured to ask that the whole program is run with admin privileges. This seems like overkill but I guess it would work.
2. Is there as better way to send the information to a log file? After all, perhaps C: does not exist on user machine. I think I recall the idea of a "user partition" in Windows 7, but whatever I do has to work on XP and Vista.
Thanks a ton,
Dave
A: You should not be trying to write directly to the root folder. Under windows 7, you will either have to run as administrator or disable UAC for that to work and neither are recommended.
Instead you can write to a folder in the 'application data' area
If you are using a .config file to configure log, you can use something like
<file value="${ALLUSERSPROFILE}\CompanyName\ProductName\Log.txt" />
or
<file value="${APPDATA}\CompanyName\ProductName\Log.txt" />
depending on whether you want the log files to be specific to a user or not.
(Obviously you replace CompanyName and ProductName with your own details).
This should work on Xp/Vista/W7.
A: You have 3 options in my eyes:
*
*like mentioned always run your app as admin altough thats not a brilliant solution
*Use the local path of the executing app to store your log - I always prefer this method as I always know where my logs are ( AppDomain.CurrentDomain.BaseDirectory will help you)
*Use "My Documents" or some similar special folders - a quick google gives us: special folders
I hope this helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Weird glitch when reloading UITableView sections I am seeing a strange visual glitch in UITableView when reloading a section in some tables. Here is a video of this in action. Happens in both simulator and device.
Ideas?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591767",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to create screen form in Informix SQL? I am new to Informix-SQL. I am trying to create form in Informix. I referred to some resources online
This is how I am accessing my database at the moment dbaccess database_name. I can't see the 'form' menu for me to create the form. I am an absolute beginner. I would appreciate it if someone could guide me to the right direction (correct commands that I should run and documentations that I can refer to). Thanks in advance.
A: The DB-Access program is not ISQL. Indeed, the main distinguishing feature of DB-Access compared with ISQL is precisely that DB-Access does not support reports or forms.
To create forms, you need the development version of Informix SQL, and you either run the isql program (choose the Forms option, and then Generate, and follow the prompts), or you run the sformbld program with options to create a default form:
sformbld -d formname database table1 ...
Either way, you normally end up editing, often extensively, the form source file (.per extension, for the Perform (aka sperform) program which will run it). Use the plain text editor of your choice (vim, emacs, pico, etc - anything that's OK for C code will work for ISQL too.
What is the difference between isql and sformbld?
$ ls -il isql sformbld sperform saceprep sacego
212302 -rwxr-xr-x 5 informix informix 844005 2010-09-17 11:24 isql
212302 -rwxr-xr-x 5 informix informix 844005 2010-09-17 11:24 sacego
212302 -rwxr-xr-x 5 informix informix 844005 2010-09-17 11:24 saceprep
212302 -rwxr-xr-x 5 informix informix 844005 2010-09-17 11:24 sformbld
212302 -rwxr-xr-x 5 informix informix 844005 2010-09-17 11:24 sperform
$
Different names for the same executable. However, the executable behaves differently depending on the name it is invoked by. When invoked as sformbld, it compiles forms; with the -d option, it generates a form and then compiles it. When invoked as sperform, it runs a form. When invoked as saceprep, it compiles an ACE report; when invoked as sacego, it runs a report. (The 's' prefix indicates the SQL version of ACE and Perform (and FormBuild); when it was first released in 1985, there was also a non-SQL product called Informix 3.30 with these programs as part of the suite.)
When invoked as isql, the program behaves as an interactive menu IDE for creating and running forms and reports - unless invoked with options to make it run a form or compile a report or whatever.
isql -fc form # Compile form
isql -fr form # Run form
isql -rc report # Compile report
isql -rr report # Run report
isql dbase [-|script] # Runs SQL script, rather like DB-Access does
(Actually, once upon an evening back in the very early 90s - or perhaps very late 80s - DB-Access was created by stripping unneeded code from ISQL. So, DB-Access behaves like ISQL does, rather than vice versa.)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591769",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How can I convert 0x70, 0x61, 0x73 ... etc to Pas ... etc in C++? I am using MSVC++ 2010 Express, and I would love to know how to convert
BYTE Key[] = {0x50,0x61,0x73,0x73,0x77,0x6F,0x72,0x64};
to "Password" I am having a lot of trouble doing this. :( I will use this knowledge to take things such as...
BYTE Key[] { 0xC2, 0xB3, 0x72, 0x3C, 0xC6, 0xAE, 0xD9, 0xB5, 0x34, 0x3C, 0x53, 0xEE, 0x2F, 0x43, 0x67, 0xCE };
And other various variables and convert them accordingly.
Id like to end up with "Password" stored in a char.
A: Key is an array of bytes. If you want to store it in a string, for example, you should construct the string using its range constructor, that is:
string key_string(Key, Key + sizeof(Key)/sizeof(Key[0]));
Or if you can compile using C++11:
string key_string(begin(Key), end(Key));
To get a char* I'd go the C way and use strndup:
char* key_string = strndup(Key, sizeof(Key)/sizeof(Key[0]));
However, if you're using C++ I strongly suggest you use string instead of char* and only convert to char const* when absolutely necessary (e.g. when calling a C API). See here for good reasons to prefer std::string.
A: All you are lacking is a null terminator, so after doing this:
char Key_str[(sizeof Key)+1];
memcpy(Key_str,key,sizeof Key);
Key_str[sizeof Key] = '\0';
Key_str will be usable as a regular char * style string.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Enum values as dropdown list I am facing an issue populating a dropdown list from Enum class values. My enum class code is:
package abc.xyz.constants;
public enum StateConstantsEnum
{
NEWYORK("NY"),
FLORIDA("FL"),
CALIFORNIA("CA"),
private String fullState;
private StateConstantsEnum( String s )
{
fullState = s;
}
public String getState()
{
return fullState;
}
}
I want populate dropdown list with NEWYORK, FLORIDA and CALIFORNIA. I am creating and adding the list to Spring model this way:
List<StateConstantsEnum> stateList = new ArrayList<StateConstantsEnum>( Arrays.asList(StateConstantsEnum.values() ));
model.addAttribute("stateList", stateList);
Then I am trying to populate the dropdown in JSP using:
<select name="${status.expression}" name="stateLst" id="stateLst">
<option value=""></option>
<c:forEach items="${stateList}" var="option">
<option value="${option}">
<c:out value="${option.fullState}"></c:out>
</option>
</c:forEach>
</select>
But I am getting an exception "Exception created : javax.el.PropertyNotFoundException:
The class 'abc.xyz.constants.StateConstantsEnum' does not have the property 'fullState'."
How do I fix this problem? Help much appreciated
A: fullState is private, getState() is the accessor.
<c:out value="${option.state}"></c:out>
Or rename your getter to getFullstate().
A: in your JSP you can use a like that :
<form:select path="*">
<form:options items="${stateList}" itemLabel="fullState" />
</form:select>
it will extract all element in your liste (stateList) and if you dont specify an itemLabel and itemValue, it'll take your enums values
of course you have to set your getter to getFullState,and declare springmvc tags in your page
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: php code transfer into js the javascript code in php is
<script language="JavaScript" type="text/javascript">
xajax_getCountry('<?php echo $row['mradio_area']?$row['mradio_area']:0 ?>',
<?php echo $row['mradio_country']?$row['mradio_country']:0 ?>,
<?php echo ($row['mradio_rate']==1?1:0); ?>);
</script>
I want to put it into the .js file.
How do I change the <?php echo $row into js format?
Thanks a lot for any answer!
A: i just don't know what you are doing because there is no javascript at all but if you want to make this as javascript .js file set the headers of this php file using this code
header("Content-type: text/javascript");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591777",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-5"
}
|
Q: Sharing hashmap between different JVM running on the same machien I have some maps that contains cached data from db. Currently 5 instance of the same server is running on same machine in different JVM. How can I share maps between JVM? cache is write once and read many. Currently the problem is because of this cache JVM footprint is very big. So storing this map in all JVM is consuming lot of memory. I need some solution which may not consume much cpu time. Is there way to do this in the same way class sharing is done between JVM?
Thanks
Nikesh PL
A: Basically, you can't: those are two different address spaces.
You could serialize one and read it from the other, but that wouldn't be like sharing them.
How about a process to manage the cache, and a quick, low-bandwidth interface that your application programs can use to access the data?
A: Why dont you look at coherence a project from oracle. Its not free but you can download and test it for free on a development system. It does precisely what you are looking for. It is used as a cache for storing database data but is ultimately a map of keys and values. Its pretty simple to set up and use. Here's a link to get you started:
http://download.oracle.com/docs/cd/E13924_01/coh.340/e14135.pdf
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591780",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Is there a way around repetitive tables in Subqueries? Notice that I'm calling and joining the same tables for my main query and subquery.
Now my actually query is using many more subqueries like that.
Is there a way to call a subquery field from the main query thus eliminating the need to reuse the same join tables in the subqueries? I want to make it more efficient without sacrificing speed.
SELECT tb1.id, tb1.title,
(SELECT tb1.title
FROM table1 AS tb1
JOIN table2 AS tb2 ON tb2.id = tb1.id
LEFT JOIN table3 AS tb3 ON tb2.id = tb3.id
WHERE tb1.id > '123' LIMIT 1) AS next
FROM table1 AS tb1
JOIN table2 AS tb2 ON tb2.id = tb1.id
LEFT JOIN table3 AS tb3 ON tb2.id = tb3.id
WHERE tb1.id='123'
A: You can use a View to abstract that query.
CREATE VIEW tbl_view AS
SELECT
tb1.id as id,
tb1.title as title
FROM table1 AS tb1
JOIN table2 AS tb2 ON tb2.id = tb1.id
LEFT JOIN table3 AS tb3 ON tb2.id = tb3.id
The shorter query would be
SELECT
id,
title,
(SELECT title FROM tbl_view
WHERE id > '123' LIMIT 1) AS next
FROM
tbl_view
WHERE id='123'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Tricky "grouped" ordering in SQL Been having trouble with this for some time.
I have a database sort of like this:
Car_ID Car_Brand Car_Model Car_Price
1 Ford Fiesta 4000
2 Ford Mustang 29000
3 Ford Focus 12000
4 Honda Civic 15000
6 Honda Jazz 5000
7 Toyota Prius 14000
I want to perform a search that finds the cheapest car then orders the rest of the cars of the same brand by price ascending.
I want my output to be this:
Car_ID Car_Brand Car_Model Car_Price
1 Ford Fiesta 4000
3 Ford Focus 12000
2 Ford Mustang 29000
6 Honda Jazz 5000
4 Honda Civic 15000
7 Toyota Prius 14000
The cheapest car is the Ford Fiesta so that and the rest of the Ford models follow it directly ordered by price. Honda then has the second cheapest model so the Jazz and the rest of the Hondas follow and so on.
Is this possible?
A: Something like this should work:
SELECT a.*
FROM Cars a
LEFT JOIN (
SELECT Car_Brand, MIN(Car_Price) AS MinPrice
FROM Cars
GROUP BY Car_Brand
) b ON a.Car_Brand = b.Car_Brand
ORDER BY b.MinPrice, a.Car_Price
A: What you need to do is create a transient data set that contains car_brand and the lowest price for that brand (which I'll call brand_price), then JOIN that data back to your original cars table. This will give you the additional piece of information (brand_price) that you need to sort the data:
SELECT car_id, car_brand, car_model, price FROM cars C1
JOIN (select car_brand, MIN(price) AS brand_price FROM cars GROUP BY car_brand) C2
ON C1.car_brand = C2.car_brand
ORDER BY C2.brand_price, C1.car_brand, C1.price
A: I would do a min grouped by Car_Brand order by the min price and then do a join ordered by the sorted car_brand and price. I will see if I can get the query done for this.
A: I think you will be able to do that with the following query
SELECT Car_ID, Car_Brand, Car_Model, Car_Price
FROM tblcars
ORDER BY Car_Price, Car_Brand
unless I missed something
A: select * from cars order by Car_Price, Car_Brand ASC
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591784",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: jQuery mobile is messing with my links I'm using using jQuery mobile. Testing my web page on iPhone.
Here is the issue:
I am on http://www.mywebsite.com/here.html and I have an anchor on that page that points to
href="http://www.mywebsite.com/some/folder/there.html", I'm navigated to
http://www.mywebsite.com/here.html#/some/folder/there.html
If I remove jQuery mobile js file, everything works as expected. So it looks like jQuery mobile is intercepting my 'tap' event and modifies url to the link. Weird. Why is it doing that?
A: Looks like this is done on purpose to help you with animated page transitions and such.
I can turn it off by adding this attribute to the anchor data-ajax="false"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MVC3 DropDownList not validating with [Required] class field as type int? Any idea why the following dropdownlist won't validate with required field as type int (the "Title" field below)?
[Required] // This works!
[Display(Name = "Name")]
public string Name { get; set; }
[Required] // This doesn't work
[Display(Name = "Title")]
public int TitleId { get; set; }
<div class="editor-label">
@Html.LabelFor(model => model.Name, "Name")
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name, "This can't be blank!")
</div>
<div class="editor-label">
@Html.LabelFor(model => model.TitleId, "Title")
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.TitleId, (SelectList)ViewBag.TitleId, String.Empty)
@Html.ValidationMessageFor(model => model.TitleId)
</div>
A: [Required] only works for nullable objects and int cannot be nullable.
Try using int? instead of int
A: According to this work item, client-side validation breaks when the SelectList in the ViewBag uses the same name as the field in question. (i.e. both are TitleId in your case.)
Try this:
@Html.DropDownListFor(model =>
model.TitleId, (SelectList)ViewBag.TitleIdList, String.Empty)
with your SelectList renamed to TitleIdList accordingly.
A: Or else try with this. Add the below code in your site.css file
select.input-validation-error {
/*border: 1px solid #e80c4d;*/
/*Other styles*/
}
This will show the drop down border color as red, when it is empty.
And in View page:
@Html.DropDownListFor(model => model.TitleID, Model.TitleIDList, "-- Select --", new { @class = "dropdownlist" }) @Html.ValidationMessageFor(model => model.TitleID, "This can't be blank")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591791",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Javascript Radio / Checkbox Problems I have this simple script. I'm trying to get the checked values and add them to a running total that's in the diabled input box. I know it's getting checked option but it's not updating to the input box and I'm not sure why. Can anyone help me?
<html>
<head>
<script type="text/javascript">
function updateForm()
{
var type = document.pizzaForm.pizzaType;
var toppings = document.pizzaForm.toppings;
var pizzaType;
var toppings;
for(var i = 0; i <= type.length; i++)
{
if(type[i].checked)
{
total = type[i].value;
}
}
for(var i = 0; i <= toppings.length; i++)
{
if(toppings[i].checked)
{
toppings += toppings[i].value;
}
}
var total = pizzaType + toppings;
pizzaForm.total.value = total;
}
</script>
</head>
<body>
<h1>Order Pizza Here:</h1>
<form action="" method="get" name="pizzaForm">
What Type of Pizza Would You Like? <br />
<input type="radio" name="pizzaType" value="10.00" onchange="updateForm()" />Vegetarian<br />
<input type="radio" name="pizzaType" value="20.00" onchange="updateForm()" />Meat Lovers<br />
<br />
<br />
Extra Toppings: <br />
<input type="checkbox" name="toppings" value="2.00" onchange="updateForm()" />Extra Cheese <br />
<input type="checkbox" name="toppings" value="3.00" onchange="updateForm()" />Mushrooms <br />
<input type="checkbox" name="toppings" value="4.00" onchange="updateForm()" />Anchovies <br />
<br />
Total <input type="text" disabled="disabled" name="total" />
</form>
</body>
</html>
A: You have a few basic Javascript errors:
*
*your for loops look like:
for(var i = 0; i <= type.length; i++)
this means they will go from 0 to length (including length) = length + 1
It should be:
for(var i = 0; i < type.length; i++)
see the diffference? <= is now <. (off by one error?)
*you are using toppings variable twice. (javascript is really bad with this and lets you shoot yourself in the foot.) Also you should be initialisng all values.
var type = document.pizzaForm.pizzaType;
var toppings = document.pizzaForm.toppings;
var pizzaTypeValue = 0;
var toppingsValue = 0;
I've also added Value to the variables that hold numbers rather than elements. Other might prefix this or some such convention to remember it holds a value not a list of elements.
*the values in markup are strings use parseFloat( to turn them into floats:
pizzaTypeValue += parseFloat(type[i].value);
also note the += means: add this to me. Equivalent to pizzaTypeValue = pizzaTypeValue + ....
*there is no real need for the total variable. just add a comment if you want to remember it is the total.
See this jsFiddle: http://jsfiddle.net/F53ae/ to see it in action.
A: Here is the working code. I put it in jsfiddle for you. The main problem was that you had two variables named toppings. Also, in the first loop, you were setting the "total" variable, when you meant to set the other total. Check it out.
http://jsfiddle.net/eXPAj/1/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591792",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: mootools clone form element I cannot get a form to submit additional fields that have been cloned. When a form like the one below is submitted, it does not include the cloned form elements. Does anybody know why and how I can alleviate this issue.
<form>
<table>
<tr><td><input type="text" value="50" name="myvar[]" /></td></tr>
<!-- This button will clone the previous set of form elements -->
<tr><input type="button" value="Add New Line" onclick="this.getParent('tr').getPrevious('tr').clone().inject(this.getParent('tr'), 'before')" /></tr>
</table>
</form>
A: Your HTML isn't well formed, so this.getParent('tr') is returning null at least for me in Firefox. Put the button inside a td that is inside the tr and it works.
JSFiddle: http://jsfiddle.net/delvarworld/r99fN/ clicking the button throws an error
A: Thanks for the comment but the form was meant to be an example not actually what I had. I looked back at the form and the top form element was inside the table and the bottom form element was outside of the table. I moved the top form element outside of the table and everything works perfectly.
thanks,
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591801",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Xcode 4 will no longer run apps on 4.2.10 device (CDMA iPhone) Up until today, I have been able to test my app on my CDMA iPhone, running 4.2.10. I am building against the 4.3 SDK, with a deployment target of 4.0.
After restarting my phone today, Xcode will no longer allow me to test the app on my phone, with this message in the Organizer window: "The version of iOS on "iPhone" does not match any of the versions of iOS supported for development with this installation of the iOS SDK. Please restore the device to a version of the OS listed, or update to the latest version of the iOS SDK"
Unfortunately there are some bugs with location services in the simulator, so I can't use that for testing either.
Can I even install the 4.2 SDK in Xcode 4? Is anyone else having this problem, or (hopefully) does anyone know how to fix it? Thanks for any help!
A: If you install xcode 4 it will actually gather the build chain from your phone and use it for compiling. You can see this in the organizer window (Window->Organizer?).
A: You know I had that same issue i found that I had to download the latest xcode and reinstall because for some reason the ios that came with xcode knew how to build on my phone. Sorry man.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591815",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android Streaming Video using MediaPlayer I'm back with another problem!
I'm trying to create an app that would list a selected Livestreams, from Own3d.TV, Justin.Tv etc...
If my research isn't totally failed, I can use the MediaPlayer object to Stream video, the only question is how do I use it?
So far my code looks like this, but it's giving me an Exception when trying to prepare the MediaPlayer.
public class Media extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SurfaceView sw = new SurfaceView(this);
SurfaceHolder sh = sw.getHolder();
setContentView(sw);
Uri ur = Uri.parse("http://www.twitch.tv/widgets/live_embed_player.swf?channel=hashe");
MediaPlayer mp = new MediaPlayer();
mp.setDisplay(sh);
try {
mp.setDataSource("http://www.twitch.tv/widgets/live_embed_player.swf?channel=hashe");
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
//mp.setDisplay(sw);
}
}
Is it even possible to Stream the video from these sites using the MediaPlayer?
If not, how shoud I approach this problem?
Thanks!
A: when implementing mediaPlayer, try something like this, it worked fine for me: http://android-er.blogspot.com/2010/11/play-3gp-video-file-using-mediaplayer.html
but I think, u cant use source like u have written in your code. You have to use some URL from where is video streamed directly with progresive streaming, not URL of html site with player embeded. You can recognize: when u write useful URL with streamed video in your internet browser, browser starts to download this streamed video in your computer. And I think, MediaPlayer supports in core .3gp or .mp4 format only..
I hope u understand my bad english
A: Use ExoPlayer instead of MediaPlayer. See Android official documentation:
ExoPlayer supports features like Dynamic adaptive streaming over HTTP (DASH), SmoothStreaming and Common Encryption, which are not supported by MediaPlayer. It's designed to be easy to customize and extend.
ExoPlayer - Android Developers
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591817",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to create OAuth token with public/private key I'm fairly new to OAuth but have done some PKI in the past. Can anyone point me to some example on how to generate a OAuth token, application secret using public/private key? google didn't turn up any good results.
I've read the google oauth examples and the OAuth intro http://hueniverse.com/oauth/guide/history , but they're not really relevant. thx
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Objective c Facebook I am developing an application that posts in IOS Facebook wall.
I'm using SDK Facebook.
My problem is if I have installed Facebook on my iPhone, when I call the permissions, it calls the Facebook app.
If i uninstall the facebook app, the authorization opens inside my application.
There's a way to open inside my application even with the Facebook app installed?
A: This is really not recommended because it is less secure and more of a hassle for users. However it is still currently allowed for the time being. In the Facebook.m file, change authorizeWithFBAppAuth to NO and safariAuth to NO:
[self authorizeWithFBAppAuth:NO safariAuth:NO]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591826",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Fit content in various screens I have a html page which is table based. I have a ul as menu few charts and few tables. I am trying to design it such that it just fits in any screen without any scrollbar. My browser doesn't honer the height=100% which i tried for the main table of the page. Any thoughts? Thanks in advance :)
A: you will not fit height as you want except using javascript, or use frameset
A: Here is javascript/jquery code that I have used to force the height of certain elements.
function resize(){
winH = 460;
if (document.body && document.body.offsetWidth) {
winH = document.body.offsetHeight;
}
if (document.compatMode=='CSS1Compat' &&
document.documentElement &&
document.documentElement.offsetWidth ) {
winH = document.documentElement.offsetHeight;
}
if (window.innerWidth && window.innerHeight) {
winH = window.innerHeight;
}
$('#container').height(winH);
}
$(function(){
resize();
});
//the following code readjusts the element's height every time the browser window is altered.
window.onresize = function() {
resize();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591828",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Help with SQL command not working I have an SQL command I am attempting to execute.
The syntax is as follows
Public Shared Function CanRaiseWorkOrder(connection As IDbConnection, ProductID As Guid) As Boolean
Using sqlCmd As IDbCommand = connection.CreateCommand
With sqlCmd
.CommandTimeout = 30
.CommandType = CommandType.Text
.CommandText = "DECLARE @CanRaiseWorkOrder BIT, @WorkOrderQtyCount INT, @ProductAvailCount INT SET @WorkOrderQtyCount = (SELECT SUM(Qty) FROM WorkOrder WHERE ProductID = @ProductID AND WorkOrder.Status <> 4) --4 = Voided SET @ProductAvailCount = (SELECT Qty FROM Product WHERE ProductID = @ProductID) IF @WorkOrderQtyCount < @ProductAvailCount BEGIN SET @CanRaiseWorkOrder = 1 END ELSE BEGIN SET @CanRaiseWorkOrder = 0 END SELECT @CanRaiseWorkOrder AS CanRaiseWorkOrder"
Dim params As New List(Of IDbDataParameter)({
ProductDAL.CreateTSqlParameter("@ProductID", DbType.Guid, ProductID)
})
.Parameters.AddRange(params)
Return .ExecuteScaler(Of Boolean)()
End With
End Using
End Function
As you will probably notice there is some customization there in regards to how the parameters are created and the command executed but you can assume those aspects of the system work as required (We have a significant amount of code that functions correctly using those methods).
I will probably get some people asking why this is not a stored procedure and the answer is "because my boss said so".
I have run SQL profiler and here is the output that this query actually generates.
exec sp_executesql N'DECLARE @CanRaiseWorkOrder BIT, @WorkOrderQtyCount INT, @ProductAvailCount INT SET @WorkOrderQtyCount = (SELECT SUM(Qty) FROM WorkOrder WHERE ProductID = @ProductID AND WorkOrder.Status <> 4) --4 = Voided SET @ProductAvailCount = (SELECT Qty FROM Product WHERE ProductID = @ProductID) IF @WorkOrderQtyCount < @ProductAvailCount BEGIN SET @CanRaiseWorkOrder = 1 END ELSE BEGIN SET @CanRaiseWorkOrder = 0 END SELECT @CanRaiseWorkOrder',N'@ProductID uniqueidentifier',@ProductID='0908C780-763F-4CE6-B074-CEC01F4451B4'
Running the code in query analyser (when I originally created it) works fine but if I run the above query as outputted from the SQL command all I get is "Command(s) completed successfully."
Any ideas?
A: Figure I'll make it an answer, but also wanted to make sure I was accurate (considering how long I've been up now :grin:).
From what I can see (and this is probably due to condensing your statement for the sake of making it a one-liner in a code file) you have a comment declaration in the middle of your statement:
--4 = Voided [...]
What's happening is you're executing only your DECLARE and first SET command (which are done without error) but the rest of your statement is being ignored because it follows the comment declaration (--).
Make sure if you do condense your query that you remove commented lines. Once they're on one line, SQL doesn't care and WILL ignore anything past the --.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591830",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android browser-like implementation, where do I cache images imagine a browser-like implementation and I would like to view html pages offline in this app, where would I store the images?
*
*a cache directory within the app's data folder (not sure if this is persistent data, or if android will wipe it out, or if it will make the app too big)
*a developer made cache directory on the user's external storage?
*persistent storage as string objects in a database or in sharedpreferences (again, this may make app too big if cache too large)
*??? other solutions?
insight appreciated
A: If you are writing an app for API lvl 8 (android 2.2) you should use getExternalCacheDir()
and put your stuff there. Everything in there gets cleaned up(deleted) when the app is uninstalled. If you are just caching for performance i would think that that is to most satisfying result for the user.
Take a look at this for further infos: Data Storage
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591835",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Load local XML file - Chrome 14 I've been trying to get Chrome to load and transform local files. I can attach a style sheet to XML files and that works fine (once the --allow-file-access-from-files switch is added to the command line). However, when trying to load files using xmlHTTPRequest pretty much exactly as in the question Loading local XML file in Chrome (see below), it fails on the line xmlHttp.send(null).
Does anyone know why or can offer assistance?
Here's the code from that question:
function readxml()
{
xmlHttp = new window.XMLHttpRequest();
xmlHttp.open("GET","test.xml",false);
xmlHttp.send(null);
xmlDoc = xmlHttp.responseXML.documentElement;
}
The version of Chrome there was 12, I'm using 14 but I wouldn't have thought that would make a difference.
Edit
Ghosty's answer got me one more step, it got send to work. Now the xmlHttp.responseXML object is null. I have the following switches set:
*
*--allow-file-access-from-files
*--allow-file-access
*--disable-web-security
A: Try --disable-web-security parameter
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591840",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Looking for JS/JQuery FULLY modal overlay I need a modal overlay that will block interaction with the rest of the page and is NOT CLOSABLE by the user, but can't seem to find one where I don't have to override existing functionality (like removing the X button or removing the esc-to-close feature).
Anyone know of a JQuery plugin or other JS library that can do this? Smaller + simpler is better...
Actually this is fairly straightforward to write myself (cover the entire page with a 100% transparent div), but it is harder to perfect (What if the user resizes the window? What about tabbing?). So ideally I'd use a plugin but I hate configuring plugins for my needs, since they seem to be never perfect for me!
A: http://developer.yahoo.com/yui/examples/container/panel-loading.html
Luckily I'm using YUI already, just overlooked this. Exactly what I want.
A: I think just add overlay div would be easier and requires less code, than using any library.
$('<div></div>').css({ top: 0, bottom: 0, left: 0, right: 0, position: absolute, zIndex: 1000 }).appendTo(document.body);
A: You can pull that off with just CSS with an overlay div that is absolutely positioned top, left, right, bottom by 0 of its container, like so:
HTML
<div class="overlay"></div>
<div class="content">
<button type="button">Click Me!</button>
<button type="button">Click Me!</button>
<button type="button">Click Me!</button>
<button type="button">Click Me!</button>
<button type="button">Click Me!</button>
<button type="button">Click Me!</button>
<button type="button">Click Me!</button>
<button type="button">Click Me!</button>
<button type="button">Click Me!</button>
<button type="button">Click Me!</button>
<button type="button">Click Me!</button>
<button type="button">Click Me!</button>
</div>
CSS
.content {
width:400px;
height:400px;
position:relative;
z-index:1;
}
.overlay {
opacity:0;
filter: alpha(opacity = 0);
position:absolute;
top:0; bottom:0; left:0; right:0;
display:block;
z-index:2;
background:transparent;
}
Demo http://jsfiddle.net/andresilich/WHEK3/4/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591843",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Help on extracting a string pattern, typically conference id from a meeting invitation Somebody can help me to extract matching pattern string?
I want to extract conference Id from a meeting invite.
A typical example would be
< meeting agenda text...
....
Conference Id : *12322#
....
more text....
/>
Platform: .Net, Language: C#
A: Using a regular expression...
var str = "< meeting agenda text... .... Conference Id : *12322# .... more text.... />";
var re = new Regex(@"Conference Id : \*(\d+)");
var m = re.Match(str);
if (m.Success)
{
Console.WriteLine(m.Groups[1]);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: What am I doing wrong? /noob ?Learning to program I am trying to create a simple calculator in the console for single digit numbers.(Well I actually only care about multiplication)
So, here is my code and if someone could help me.
class multiplythisnumber
{
static void Main()
{
int input, input1, output; //variable decleration
System.Console.WriteLine("This application is meant to multiply two single digit numbers.");
System.Console.WriteLine("You can choose both numbers, however this is only a test.\r I am not sure the read command even does what I think it does.");
System.Console.WriteLine();
System.Console.Write("Please enter the first number: ");
input = System.Console.Read(); //Reads my input + 48(assuming 48 is the value of enter)
input = input - 48;
System.Console.WriteLine();
System.Console.Write("Please enter the second number: ");
input1 = System.Console.Read(); //Doesn't wasit for input and sets input1 = 13
System.Console.WriteLine();
output = input * input1;
System.Console.WriteLine();
System.Console.Write("{0} times {1} equals {2}.", input, input1, output);
System.Console.ReadKey();
}
}
I added comments to explain what I was doing to everyone else, and just as personal notes.
The last line always ends up as "(0) times 13 equals 0." -Assuming I used zero for input 1.
Edit:
Just to clarify I know 0*13=0 (yes it said 12 earlier what it has really been saying is 13). The problem is that it is not allowing me to set input1 and is just setting it at 13 and continuing executing.
Edit2: I would like to say thanks to Matt, because the changes he made allowed the code to work correctly. So, looks like I have my first code that actually does something other than tell you your own name.
A: Console.Read() only reads one character. So your first Console.Read() reads your number and the second reads the CR Ascii code (13) because of your "Enter".
Use ReadLine() instead.
System.Console.Write("Please enter the first number: ");
string first = System.Console.ReadLine();
input = Convert.ToInt32(first);
System.Console.WriteLine();
System.Console.Write("Please enter the second number: ");
string second = System.Console.ReadLine();
input1 = Convert.ToInt32(second);
System.Console.WriteLine();
output = input * input1;
System.Console.WriteLine();
System.Console.Write("{0} times {1} equals {2}.", input, input1, output);
System.Console.ReadKey();
A: The problem is that you are reading two characters one after the other. input is set when you press the 1 key. input1 is read when you press the Enter key. Just don't press the Enter key; instead enter both numbers immediately one after the other. The best way to solve this is System.Console.ReadLine
System.Console.Read reads a single character from the console. When you type the 0 key, your program actually reads the character '0' ('0' == 48 in ASCII) not the number 0.
Here's how I would fix your program:
Instead of using System.Console.Read, which reads a character, I would use System.Console.ReadLine which reads an entire line rather than a single key/character. This would allow your users to enter numbers longer than one digit. You can convert the user's input from a string to an integer by using Int32.Parse
class multiplythisnumber
{
static void Main()
{
int input, input1, output; //variable decleration
System.Console.WriteLine("This application is meant to multiply two single digit numbers.");
System.Console.WriteLine("You can choose both numbers, however this is only a test.\r I am not sure the read command even does what I think it does.");
System.Console.WriteLine();
System.Console.Write("Please enter the first number: ");
input = Int32.Parse(System.Console.Read());
//input = input - 48;//No need to do this anymore as we have already converted the user's input to an integer.
System.Console.WriteLine();
System.Console.Write("Please enter the second number: ");
input1 = Int32.Parse(System.Console.ReadLine());
System.Console.WriteLine();
output = input * input1;
System.Console.WriteLine();
System.Console.Write("{0} times {1} equals {2}.", input, input1, output);
System.Console.ReadKey();
}
}
A: It has to do with how Read() and ReadLine() work. Try ReadLine() instead.
A: I believe it is because your program is using Console.Read() instead of Console.ReadLine() This means that it is reading 1 character at a time from the input. Your first input is 5 + a return. Try using ReadLine and you need to protect against entering something that isn't an integer. You can use the following program to achieve what you want.
class Program
{
static void Main(string[] args)
{
int input, input1;
string output; //variable decleration
System.Console.WriteLine("This application is meant to multiply two single digit numbers.");
System.Console.WriteLine("You can choose both numbers, however this is only a test.\r I am not sure the read command even does what I think it does.");
System.Console.WriteLine();
System.Console.Write("Please enter the first number: ");
int.TryParse(System.Console.ReadLine(),out input); //Reads my input
System.Console.WriteLine();
System.Console.Write("Please enter the second number: ");
int.TryParse(System.Console.ReadLine(), out input1);
System.Console.WriteLine();
if (input != 0 && input1 != 0) {
input = input - 48;
output = (input * input1).ToString();
}else
{
output = "NaN";//not a number
}
System.Console.WriteLine();
System.Console.Write("{0} times {1} equals {2}.", input, input1, output);
System.Console.ReadKey();
}
}
A: May be you need an C# expert to answer, but when I debug I got that, because when you ENTER, it will push to Console 13 and 10. So you need to Read twice to through them.
Just COPY and PASTE to your code
static void Main()
{
int input, input1, output; //variable decleration
System.Console.WriteLine("This application is meant to multiply two single digit numbers.");
System.Console.WriteLine("You can choose both numbers, however this is only a test.\r I am not sure the read command even does what I think it does.");
System.Console.WriteLine();
System.Console.Write("Please enter the first number: ");
input = System.Console.Read(); //Reads my input + 48(assuming 48 is the value of enter)
input = input - 48;
/**
*HINT: Try to use below double line:
*/
System.Console.Read();
System.Console.Read();
System.Console.Write("Please enter the second number: ");
input1 = System.Console.Read(); //Doesn't wasit for input and sets input1 = 13
System.Console.Read();
output = input * input1;
System.Console.WriteLine();
System.Console.Write("{0} times {1} equals {2}.", input, input1, output);
System.Console.ReadKey();
}
UPDATE:
You can try to see more:
static void Main()
{
Console.Write("Please enter just one number and press enter:");
int input1 = Console.Read();
int input2 = Console.Read();
int input3 = Console.Read();
Console.WriteLine("You've inputted: {0},{1},{2}",input1, input2, input3);
Console.ReadKey();
}
Output:
Please enter just one number and press enter:1
You've inputted: 49,13,10
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591848",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Jquery-related-selects i'm tryng to make 7 related select boxes with this script: https://github.com/tukutela/jquery-related-selects,
here the shot: http://vitrineonline.com/porra/
and so, the problem is: on the 3 select, the script stop to push up the script.
could someone please just give me a hint of what is going on? thanks :)
the code:
<form id="example">
<ul>
<li><label>Produto</label>
<select name="categoriaID">
<option value="AC">Acessórios</option>
<option value="CA">Calçados</option>
<option value="RO">Roupas</option>
</select></li>
</ul>
<ul>
<li><label>Tipo</label>
<select name="tipoID">
<option value="">Escolha »</option>
</select></li>
</ul>
<ul>
<li><label>Condição</label>
<select name="condicaoID">
<option value="">Escolha »</option>
</select></li>
</ul>
<ul>
<li><label>Tamanho</label>
<select name="tamanhoID">
<option value="">Escolha »</option>
</select></li>
</ul>
<ul>
<li><label>Tamanho Disponível</label>
<select name="tamanho_dispoID">
<option value="">Escolha »</option>
</select></li>
</ul>
<ul>
<li><label>Cor</label>
<select name="corID">
<option value="">Escolha »</option>
</select></li>
</ul>
<ul>
<li><label>Material</label>
<select name="materialID">
<option value="">Escolha »</option>
</select></li>
</ul>
</form>
$(function(){
$("#example").relatedSelects({
onChangeLoad: 'datasupplier.php',
loadingMessage: 'Please wait',
selects: ['categoriaID','tipoID','condicaoID','tamanhoID','tamanho_dispoID', 'corID','materialID']
});
});
<?php
$categoriaID = $_GET['categoriaID'];
$tipoID = $_GET['tipoID'];
$condicaoID = $_GET['condicaoID'];
$tamanhoID = $_GET['tamanhoID'];
$tamanho_dispoID = $_GET['tamanho_dispoID'];
$corID = $_GET['corID'];
$materialID = $_GET['materialID'];
$categoria = array();
$categoria['AC'] = "Acessórios";
$categoria['CA'] = "Calçados";
$categoria['RO'] = "Roupas";
$tipo = array();
$tipo['AC']['BOL'] = 'Bolsa';
$tipo['AC']['BRIN'] = 'Brinco';
$tipo['CA']['TEN'] = 'Tenis';
$tipo['RO']['CAM'] = 'Camisa';
$condicao = array();
$condicao['AC']['BOL']['NOV'] = "Novo";
$condicao['AC']['BOL']['USA'] = "Usado";
$condicao['CA']['TEN']['USA'] = "Usado";
$condicao['RO']['CAM']['NOV'] = "Novo";
$tamanho = array();
$tamanho['AC']['BOL']['NOV']['GRAN'] = 'Grande';
$tamanho['AC']['BOL']['USA']['PEQ'] = 'Pequeno';
$tamanho_dispo = array();
$tamanho_dispo['AC']['BOL']['NOV']['PEQ']['P']= "P";
$tamanho_dispo['AC']['BOL']['USA']['PEQ']['M']= 'M';
$cor = array();
$cor['AC']['BOL']['NOV']['PEQ']['M'] ['AZ']= 'Azul';
$cor['AC']['BOL']['USA']['PEQ']['M'] ['VE']= 'Vermelho';
$material = array();
$material['AC']['BOL']['NOV']['PEQ']['M'] ['VE'] ['ALG'] = "Algodão";
$material['AC']['BOL']['USA']['PEQ']['M'] ['VE'] ['FER']= "Ferro";
if($categoriaID && !$tipoID && !$condicaoID && !$tamanhoID && !$tamanho_dispoID && !$corID && !$materialID ){
echo json_encode( $tipo[$categoriaID] );
}
elseif( $categoriaID && $tipoID && !$condicaoID && !$tamanhoID && !$tamanho_dispoID && !$corID && !$materialID ) {
echo json_encode( $condicao[$tipoID][$categoriaID] );
}
else {
echo '{}';
}
?>
A: $condicao[$tipoID][$categoriaID]
should be
$condicao[$categoriaID][$tipoID]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591850",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Restart passenger synchronously? Is there a way to restart a passenger server synchronously?
Running touch tmp/restart.txt will restart the server, but the touch command is asynchronously.
A: You can follow up the touch tmp/restart.txt command with curl -I http://your-server. That will cause passenger to immediately restart your application.
Is that the functionality you were after?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there a capybara for Node.js? Does anyone know whether there is anything similar to capybara for Node.js?
A: I'm a rails-turned-node developer and I've always been looking for a analogy in the JS world for the winning RSpec/Capybara combination. Here is what I've found what I like best.
*
*Mocha - for running asynchronous tests
*Chai - for assertions
*Request - for handling HTTP request/response
*Cheerio - for selecting HTML elements from responses
Here is a more involved post on how to set up this stack including continuous test running.
Happy Testing!
A: Cucumber-JS is the closest you will get in Javascript:
https://github.com/cucumber/cucumber-js
You can use the library to drive JS, headless and Selenium, however it is missing the 'capybara' shared API between each of the different 'worlds'. There is a good talk at http://skillsmatter.com/podcast/agile-testing/cucumber-js-cuke-up-your-javascript and supporting github code at https://github.com/jbpros/cukecipes
I'm hoping that when the phantomjs webdriver wire protocol is finished (https://github.com/detro/ghostdriver) and if Soda/Selenium (https://github.com/LearnBoost/soda) is able to drive it then the headless tests will be able to be automated via Selenium thus bypassing the need for Capybara.
A: See jelly.io:
Jellyfish is a Node project that aims to make it easy to launch different JavaScript environments and run your code.
A: How about Zombie?
Zombie.js
Insanely fast, headless full-stack testing using Node.js
The Bite
If you're going to write an insanely fast, headless browser, how can you not call it Zombie Zombie it is.
Zombie.js is a lightweight framework for testing client-side JavaScript code in a simulated environment. No browser required.
A: Hy!
I've created a library to help out with cucumber-js. It gives you callable steps and parsed arguments. This works with cucumber and doesn't replace it.
Quick features:
*
*Sync step definitions, no more callbacks;
*Call other step from step definitions;
*Parse values such as arrays, objects and decimals;
https://github.com/hackhat/cucumberry
Hope you find it useful (:
A: We created a complete acceptance testing solution in JS
http://xolv.io/products/chimp
It uses CucumberJS (Mocha/Jasmine soon) to drive your acceptance tests
*
*Downloads and starts Phantom / Selenium
*Injects a preconfigured Webdriver.IO instance into the testing context
*Includes the request npm library (for REST)
the assertion library of your choice (Chai / Jasmine-expect)
*Uses fibers for synchronous testing (no callback hell / promise confusion)
*Works with SauceLabs / BrowserStacks etc
*Support outside in testing with a watch mode that continuously runs the scenarios you tag with @focus
*Supports CI out of the box and tested on Circle/Codeship/Travis (using headless Chrome/Firefox)
It doesn't make you coffee, yet
A: In terms of acceptance testing, I have heavily used Capybara for Rails. And I am unhappy with the alternatives listed here for NodeJS. You will want a popular web automation utility combined with the ability to make assertions against scenarios of a particular feature.
When you think of web automation in Node, Phantom and, thus, Casper is dead. So what is in the rise as of now? Puppeteer. I started using Puppeteer a few years ago when it was in beta and few articles and SO posts about it. But now Puppeteer is becoming the leader of web automation in Node. However, you cannot assert things in Puppeteer which is what you would expect from a testing framework.
But that doesn't stop us from integrating a testing tool into Puppeteer web automation. I found a few solutions using jest as the testing tool.
const puppeteer = require('puppeteer');
describe('Open Website', () => {
var browser, page;
var url = 'https://website.io'
beforeEach (async () => {
browser = await puppeteer.launch({ headless: false });
page = await browser.newPage();
})
afterEach (() => {
browser.close()
})
test('Title == Website Tools', async () => {
await page.goto(url);
const title = await page.title();
expect(title).toBe("Website Tools");
});
A: Yes, see expresso and more here - Unit testing framework for node.js that specifically supports testing async code?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591854",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
}
|
Q: From random integers to an actual String This is a code that takes in an array of all the printing characters of the ASCII table. I am trying to make it so that any String message in the form of integers (e.g. String "aba" that is converted 97098097 can be put back into its original String form. 100101101 can be taken and made back into "dee". I've really tried hard with this method but it does not seem to be working, especially when it comes to numbers and such please help me. It is in Java by the way and I am using Eclipse.
public static String IntToString (){
int n = 0;
String message = "";
String message2 = null;
String [] ASCII = {" ","!","\"","#","$","%","&","\'","(",")","*","+",",","-",".","/","0","1","2","3","4","5","6","7","8","9",":",";","<","=",">","?","@","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","[","\\","]","^","_","`","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","{","|","}","~"};
String IntMessage = result.toString();
String firstChar = IntMessage.substring(0,2);
if (IntMessage.substring(0,1)=="1" && IntMessage.length()%3==0)
{
for (int x = (IntMessage.length() % 3 - 3) % 3; x < IntMessage.length()-2; x += 3)
n = Integer.parseInt(IntMessage.substring(Math.max(x, 0), x + 3));
message=message.concat(ASCII[n-31]);
return message;
}
else if (IntMessage.length()%3==2)
message2=ASCII[(Integer.parseInt(firstChar))-31];
for (int x = 2; x < IntMessage.length()-2; x += 3)
n = Integer.parseInt(IntMessage.substring(x, x + 3));
message=message2+=ASCII [n - 31];
return message;
A: It would seem that your encoding scheme is, er, crazy.
First, you take the ASCII value of a string, then take the character representation of that ASCII value, then store it as a string.
So "abc" => {97, 98, 99} => "979899".
But since you are using ASCII, which can have values of 100 or more, you are padding your ints with 0 if they are under 100:
"abc" => {97, 98, 99} => {"097", "098", "099"} => "097098099"
But you decide to do this only sometimes, because somehow
"aba" => "97098097"
That is, the first "a" is turned into "97", but the last "a" is turned into "097".
I'd say you should fix your encoding scheme first.
Also, these are hopefully not "random integers" because you are trying to turn them into sensible strings. Otherwise a simple mapping such as base64 would easily map any integers to strings, they just might not make much sense.
In fact, they aren't even really integers. You're storing your encoded strings as strings.
A: public static void main(String[] srgs){
String aaa = "100101101";
String[] a = split(aaa, 3);
String s = "";
for(int i=0;i<a.length;i++){
char c = (char)Integer.parseInt(a[i]);
s += Character.toString(c);
}
System.out.println(s);
}
public static String[] split(String str, int groupIndex){
int strLength = str.length();
int arrayLength = strLength/groupIndex;
String[] splitedArray = new String[strLength/groupIndex];
for(int i=0;i<arrayLength;i++){
String splitedStr = str.substring(0, groupIndex);
str = str.substring(groupIndex, str.length());
arrayLength = str.length();
splitedArray[i] = splitedStr;
}
return splitedArray;
}
The most important is that ASCII string covert to Char value, than turn it to real Character value in the string. The ASCII code length need be fix by 3 can be helpful in this case.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591858",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: How do I evaluate an expression in bash and assign the value to a variable? I have an expression like this:
if [[ $s == *Mar* ]]; then "match"; else "not"; fi;
How do assign its value to a variable?
command substitution syntax does not work, because bash tries to evaluate the result of the expression:
x=$(if [[ $s == *Mar* ]]; then "match"; else "not"; fi;)
gives the error:
-bash: match: command not found
So, basically I want to tell bash to evaluate an expression, but do not treat the output as a command.
How do I do that?
A: if [[ $s == Mar ]]; then "match"; else "not"; fi
is not an expression; it is a command. You could make it into a command that outputs either match or not by inserting appropriate echo commands, and then capture the output with backticks or $().
But that would be pointlessly indirect. Why not simply
if [[ $s == Mar ]]; then
x="match"
else
x="not"
fi
?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591859",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Will NSNotificationCenter call back method be called in main thread or background thread? My code is just play a downloaded mp4 files and register the view controller to observe the notification of end of player.
It works pretty good in not only iOS5 but also iOS4.
But I just want to know for sure that whether the call back method by NotificationCenter will be called in background thread or main thread.
(loadMoviePlayerStateChanged:(NSNotification*)notification is call back method in my code)
Do anyone know exactly about this?
- (void) playMovie:(NSURL *)fileURL {
MPMoviePlayerViewController *MPVC = [[MPMoviePlayerViewController alloc] initWithContentURL:fileURL];
self.mMPVC = MPVC;
self.mMPVC.moviePlayer.controlStyle = MPMovieControlStyleFullscreen;
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadMoviePlayerStateChanged:)
name:MPMoviePlayerLoadStateDidChangeNotification
object:self.mMPVC.moviePlayer];
[MPVC.moviePlayer prepareToPlay];
[MPVC release];
}
- (void) loadMoviePlayerStateChanged:(NSNotification*)notification {
int loadState = self.mMPVC.moviePlayer.loadState;
if(loadState & MPMovieLoadStateUnknown) {
IGLog(@"The load state is not known at this time.");
return;
}
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerLoadStateDidChangeNotification
object:self.mMPVC.moviePlayer];
[self.mMPVC.view setFrame:self.view.bounds];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:self.mMPVC.moviePlayer];
/* if I do not use performSelectorOnMainThread method to add subview to UIViewController`s view,
the view of MPMoviePlayerViewController would not be removed from superview normally */
[self.view performSelectorOnMainThread:@selector(addSubview:)
withObject:self.mMPVC.view
waitUntilDone:YES];
[self.mMPVC.moviePlayer play];
}
- (void) moviePlayBackDidFinish:(NSNotification*)notification {
[self.mMPVC.moviePlayer stop];
[self.mMPVC.moviePlayer.view removeFromSuperview];
NSString* dstFilePath = [[_mPopupVC.mSelectedMovie decryptionFilePath] stringByAppendingPathExtension:@"mp4"];
[[NSFileManager defaultManager] removeItemAtPath:dstFilePath error:nil];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:self.mMPVC.moviePlayer];
}
A: I got an answer for my question in apple developer site, the answer is,
"notifications safely thread themselves and perform their selectors on the main thread.
however, your problem is that you should not be adding and removing the player view like that, use the presentModalVideo methods provided as a category in your view controller class."
and I solved the problem that i had. code is below..
- (void) playMovie
{
/*
*create and initialize MPMoviePlayerViewController with specified url and retain it
*/
MPMoviePlayerViewController *MPVC = [[MPMoviePlayerViewController alloc] initWithContentURL:vodWebURL];
self.mMPVC = MPVC;
[MPVC release];
self.mMPVC.moviePlayer.controlStyle = MPMovieControlStyleFullscreen;
self.mMPVC.moviePlayer.shouldAutoplay = NO;
[self.mMPVC.moviePlayer prepareToPlay];
/*
*register movie player to NSNotificationCenter
*/
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(loadMoviePlayerStateChanged:)
name:MPMoviePlayerLoadStateDidChangeNotification
object:self.mMPVC.moviePlayer];
}
- (void) loadMoviePlayerStateChanged:(NSNotification*)notification
{
/*
*do your work for the state of the movie player
*/
int loadState = self.mMPVC.moviePlayer.loadState;
if(loadState & MPMovieLoadStateUnknown) {
NSLog(@"The load state is not known at this time.");
return;
} else if(loadState & MPMovieLoadStatePlayable) {
NSLog(@"MPMovieLoadStatePlayable : The buffer has enough data that playback can begin, but it may run out of data before playback finishes.");
} else if(loadState & MPMovieLoadStatePlaythroughOK) {
NSLog(@"MPMovieLoadStatePlaythroughOK : Enough data has been buffered for playback to continue uninterrupted.");
} else if(loadState & MPMovieLoadStateStalled) {
NSLog(@"MPMovieLoadStateStalled : The buffering of data has stalled.");
}
/*
*set frame of the view of MPMoviePlayerViewController and add it
*call play method
*/
[self.mMPVC.view setFrame:self.view.superview.bounds];
[self.view.superview addSubview:self.mMPVC.view];
[self.mMPVC.moviePlayer play];
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerLoadStateDidChangeNotification
object:self.mMPVC.moviePlayer];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(moviePlayBackDidFinish:)
name:MPMoviePlayerPlaybackDidFinishNotification
object:self.mMPVC.moviePlayer];
}
- (void) moviePlayBackDidFinish:(NSNotification*)notification
{
/*
*remove the view of MPMoviePlayerViewController
*release MPMoviePlayerViewController
*/
[self.mMPVC.moviePlayer stop];
[self.mMPVC.moviePlayer.view removeFromSuperview];
self.mMPVC = nil;
[[NSNotificationCenter defaultCenter] removeObserver:self
name:MPMoviePlayerPlaybackDidFinishNotification
object:self.mMPVC.moviePlayer];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591861",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Controling Selenium test speed in hudson There is Selenium plugin (RC) in Hudson and the builds are taking to too long and keep failing if the server takes a while to respond. I do not think putting in waits in the test files would be a good Idea as the test code will be bloated with "Waits" and would increase the build time and the tests can still fail if there is a delay in response.
I was wondering if the speed at which selenium test cases are executed can be controlled in Hudson? just like you drag the slider to reduce and maximise speed in the browser.
Thanks.
A: I don't think it will be possible to control the speed of test execution from hudson/jenkins. However, you can set speed of a test by the following Selenium method (in this case Selenium will wait 1 second after each command):
selenium.setSpeed("1000");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591862",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to render a button depending on the state list? I have a button, which should be disabled if a particular list is empty. And, accordingly, active, if list not empty. When the initial page load button is disabled, because list is empty. And then the list is filled, but the button is still disabled and does not react to this. I put it in a panelGroup, but I do not know where to render it again. In what place I must to insert the attribute "render" or "rendered". And what they should be equal? Any help would be greatly appreciated. Thanks in Advance.
This is my code:
<h:panelGroup id="buttonSave">
<h:commandButton value="#{bean.value}"
action="mypage"
actionListener="#{bean.onSave}"
disabled="#{empty bean.list}"/>
</h:panelGroup>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591868",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Linq2SQL Filter on multi columns If I have a data table like this
id, Name, Address, Status
How would I in Linq search across multiple columns?
So if I enter a search term of "slappy" I'd want all matches in columns Name, Address and Status.
Is there an easy way or do I need to apply contains for each column?
A: var searchTerm = "slappy";
var result = context.table.Where(row => row.Name.Contains(searchTerm) ||
row.Address.Contains(searchTerm) ||
row.Status.Contains(searchTerm));
A: Did you consider to use a search engine library?
It is not based on EF, but EF is not the best choice for your purpose. Surely you can mix technologies.
http://incubator.apache.org/lucene.net/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591870",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: how to change the syntax of this sql query to 92's explicit join systax How can i rewrite the below query in SQL '92's Explicit join syntax using only inner or outre joins
SELECT e.emp_id ,
( SELECT AVG(salary)
FROM #salary d
WHERE d.emp_id = e.emp_id )
FROM #emp e
A: I'm not even sure why you need the outer select; The employee id is present in both tables, you don't need a join at all:
SELECT salary.emp_id, AVG(salary.salary)
FROM salary
GROUP BY salary.emp_id
Well, maybe some employees aren't salaried, and you just want a NULL (is AVG() strict on your DBMS?)
SELECT e.emp_id, AVG(d.salary)
FROM employee e
LEFT OUTER JOIN salary d ON e.emp_id = d.emp_id
GROUP BY e.emp_id
A: Good point byTokenMacGuy about not needing the #emp table. However, let's say that you only want to query those records in #salary that are also in #emp. In that case, you'll need to move your WHERE clause to the ON clause of a join, and add a GROUP BY clause:
SELECT e.emp_id, AVG(d.salary)
FROM #salary d
INNER JOIN #emp e ON d.emp_id = e.emp_id
GROUP BY e.emp_id
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
}
|
Q: Fetching Data from PL-SQL Table as OUT parameter in Java I am executing a procedure from java code, which has 2 out parameters, One of those is a Object table. here is the overview of package
PROCEDURE SalesProc (
p_S_table IN t_s_table
, p_T_table IN OUT t_t_table
, x_message OUT VARCHAR2
)
t_table is IN OUT parameter which contains several String and Numbers into it. Before executing the package I am creatng an SalesObject array and setting into it.
Here, the aim is to get some value from t_table using resultSet.
the source I am trying to get working is:
callstmt.registerOutParameter(2, Types.ARRAY,"T_TABLE");
callstmt.setArray(2, mySalesObjectArray);
callstmt.execute();
java.sql.Array aa = callstmt.getArray(2);
ResultSet rs = aa.getResultSet();
while(rs.next()){
String ss = rs.getString(1);
}
Following line is giving "java.sql.exception"
String ss = rs.getString(1);
I am also trying to cast it into Object type as follows
salesObject[] sArray = (salesObject[])callstmt.getArray(2);
Which is throwing classCastException.
"classcastException.Cannot cast java.lang.Object[2][id=16062] to java.lang.String[]"
how can I avoid these exceptions?
A: You have 3 parameters, the counting starts from 1 from the left most parameter:
*
*p_S_table
*p_T_table
*t_t_table
I use Oracle as a DBMS but haven't use IN/OUT parameters but I'm sure that if u change youre procedure into a function (because a function returns something) that takes the IN parameters and returns the OUT one, same code will work.
As for the casting here:
salesObject[] sArray = (salesObject[])callstmt.getArray(2);
your salesObject class should implement either ORAData or SQLData.
SQLData seems nicer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591879",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Large textinput makes http post fail I have a form in my application where technicians input information about different events or actions taken (like updating a server). The problem is that these inputs can be quite lengthy and then my form stops working. The server returns a 302 error to the browser if the browsers tries to send data, but just as often the browser does nothing when I try to submit. When the browser does nothing a quick look in the Chrome Developer Tools shows that the browser tries to execute a post to the correct path, but the status is listed as failed. This always occurs if the textarea contains more than ~3500 characters. I've tried to change the enctype to see what happens but it hasn't solved the problem.
<form enctype="application/x-www-form-urlencoded" action="/some/path/" method="post" _lpchecked="1">
<fieldset>
<input type="hidden" name="machineId" value="some_integer">
<input type="hidden" name="eventId" value="some_integer">
Titel:
<select name="form[title]">
<option>Some_option</option>
<option>some_option</option>
</select>
<textarea name="form[text]" rows="25" cols="90"></textarea>
<input type="submit" value="Spara" title="Spara">
</fieldset>
</form>
Any ideas on why it doesn't work and what can be done?
EDIT:
My application is based on PHP and running on Debian/Apache. I haven't been able to find any settings that might prevent the post from working correctly. I do have a post_max_size set at 8MB, but a text of 3500 chars are not larger than 8MB so...
A: Your text via POST will most likely NOT be 1 byte/character. Apache mod_security might be filtering the data. And it could be any other number of Apache mods that affect post encryption. You might check out mb_get_info() and other mb_* functions to verify how PHP is encoding the text. If you don't want to have to dig too deeply, you can make an educated guess from a couple data points as to how many bytes per character are being used in your POST and adjust post_max_size to suit your needs.
If you are cannot print errors to screen, you can check out
tail -n 30 /var/log/apache2/error.log #prints last 30 lines of error.log
immediately after your white screen symptom to get more detailed information on errors/warnings/etc encountered during the script.
Also note that post_max_size is limited by memory_limit ... I don't think that is the issue, but it may be something to consider for another reader.
A: what server side language you are using? maybe you need some text compression like this one Huffman Algorithm
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591885",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: HTML5 Localstorage & jQuery: Delete localstorage keys starting with a certain word I have 2 apps working together with localstorage and I was wondering how can I delete all the keys which start with note- and todo- . I know localstorage.clear() clears everything but thats not my aim.
Here is an example of what I have in my localstorage:
Where I want to delete all the todo-* with a button click and all note-* with other button click using jquery.
Thanks alot
A: Object.keys(localStorage)
.forEach(function(key){
if (/^todo-|^note-/.test(key)) {
localStorage.removeItem(key);
}
});
A: I used a similar method to @Ghostoy , but I wanted to feed in a parameter, since I call this from several places in my code. I wasn't able to use my parameter name in a regular expression, so I just used substring instead.
function ClearSomeLocalStorage(startsWith) {
var myLength = startsWith.length;
Object.keys(localStorage)
.forEach(function(key){
if (key.substring(0,myLength) == startsWith) {
localStorage.removeItem(key);
}
});
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591893",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
}
|
Q: How to check if UDP port is available in iPhone Now I am developing an iPhone project.
I want to iterate UDP port from 5060 to 50xx
How can I check if specific port is already open or free to use?
Thanks~~
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Get largest value from array without sorting I am creating a somewhat simple game, and I need to keep track of what players have what score. 25 people will be playing this game at one time, these players will be put into an array:
public static int[] allPlayers = new int[25];
Depending on a correct answer, the current player will earn 100 points, let's say. So, if player 1 were up, the code would be something similar to the following:
allPlayers[0] += 100;
If player 3 were up, the code on a correct answer would be:
allPlayers[2] += 100;
At the end of the game, I want to determine which player has the accumulated the most amount of points. Please note that I cannot simply sort this array because I need the order of the array to remain intact. If the order is not left intact, I will not be able to tell which player had which points to his/her name.
I'm interested to hear what you all have to say and I look forward to your responses.
Thank you very much,
Evan
A: No need to sort, just iterate through the array, keeping track of the largest value seen so far and the index of that value.
var largest = -1;
var player = -1;
for (var i = 0; i < allPlayers.Length; ++i)
{
if (allPlayers[i] > largest)
{
player = i;
largest = allPlayers[i];
}
}
Console.WriteLine( "Player {0} wins, with score {1}", player, largest );
Handling ties is left as an exercise.
A: Using Linq as an alternative if you wanted a ranking of possibly more than one player (a simple loop with keeping the index of the winning player is much more effective for the base case):
var player = allPlayers.Select((x, i) => new { Score = x, Player = i })
.OrderByDescending(x => x.Score)
.First();
Console.WriteLine("Player {0} wins with a score of {1}", player.Player, player.Score);
A: I'd like to be a LINQ purist and say that if you are using OrderByDescending, you're doing an O(NlogN) sort. Since max is an O(N) algorithm, we should be able to do better with LINQ. Here is my O(N) proposal for LINQ:
var player=allPlayers.Select((x, i) => new {Score=x, Player=i})
.Aggregate((self, next) => self.Score>=next.Score ? self : next);
Console.WriteLine("Player {0} wins with a score of {1}", player.Player, player.Score);
A: Use
int max = maxplayers.Max()//linq extension method of [] int
see this post
A: If you are unable to sort or keep a parallel data structure that can do the sorting or keep a a reference to the largest value, you are going to have an O(n) algorithm.
Easiest way would be to keep a reference to the highest value inserted into the array.
A: Using Linq:
int max = allPlayers
.Select((x, i) = > new { Player = i, Score = x })
.OrderByDescending(x => x.Score)
.First();
Without Linq:
int score;
int player;
for(var i = 0; i < allPlayers.Length; i++)
{
if(allPlayers[i] > score)
{
score = allPlayers[i];
player = i;
}
}
A: You can keep a tracking wich player has the max value in all the process, in each increase you can review if the new value is bigger than the old value, so in this way you can to know wich player has the max value in any moment at the game.
private int maxPlayer = 0;
private int value = 0;
public void setIncrement(int player, int amount)
{
allPlayer[player] += amount;
if(allPlayer[player] > value)
{
maxPlayer = player;
value = allPlayer[player];
}
}
public int getMaxPlayer()
{
return maxPlayer;
}
A: Just iterate throught it once as others have suggested. That's unavoidable,
UNLESS
You wrap your players array into an array and encapsulate the way to set player score. Then you can make the comparison when adding stuff to your list.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Using Meta Search or Ransack with Geocoder I've created a form that supplies search criteria:
= search_form_for @q do |f|
%h3
Search:
= f.label :category_id
%br
= f.collection_select :category_id_eq, Category.all, :id, :name, :include_blank => true
%br
= f.label "Sub-Category"
%br
= f.collection_select :subcategory_id_eq, Subcategory.all, :id, :name, :include_blank => true, :prompt => "select category!"
%br
= f.label "Contains"
%br
= f.text_field :title_or_details_cont
%br
= f.submit
I want to be able to also do a search based on the "Near" functionality of the Rails Geocoder gem. Does anyone know how to incorporate an existing scope, or specifically how to use the "Near" scope with Meta Search or Ransack?
Thus far, all of my attempts have been futile.
A: This is actually quite easy to achieve simply by adding a non-search_form_for field within your form.
In my view (note the difference in the two form fields):
<%= search_form_for @search do |f| %>
<%= f.label :will_teach, "Will Teach" %>
<%= f.check_box :will_teach %>
<%= label_tag :within %>
<%= text_field_tag :within, params[:within], {:class => "span1"} %> miles
<% end %>
This then produces a param string like the following:
Parameters: {"utf8"=>"✓", "q"=>{"will_teach"=>"1"}, "within"=>"10", "commit"=>"Search"}
You can then put some conditional logic into your controller to hoover these params up, and combine Geocoder with Ransack. I check to see if the "within" parameter is present, if so, check it's a number (to_i returns 0 for anything but a number, hence the > 0 check).
I then combine the Geocoder "near" with Ransack's "search".
If the "within" parameter isn't there (i.e. the user didn't enter a number) then I search without the Geocoder bits.
Finally I'm using Kaminari, so that goes on the end of the search results:
if params[:within].present? && (params[:within].to_i > 0)
@search = Tutor.near(request.location.city,params[:within]).search(params[:q])
else
@search = Tutor.search(params[:q])
end
@tutors = @search.result.page(params[:page]).per(9)
Hope this helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How do I wait a certain amount of time before continuing in PHP? So this is kind of two questions...
First off, when a user logs out, I want to redirect them back to the login page. I do this by using header('login_form.php');, however, prior to doing such, I try to print out the text "You have successfully logged out. You are now being redirected to the login form.". I do this using echo and echoing out the text, however, the header runs so quickly that I'm almost immediately transferred back to the login form, without getting a chance to read the message. So, how can I delay a little bit, and let the message display for just 5 seconds or so prior to redirecting the user with the header?
My second question is, what's the best way to simply display "incorrect login" above the login form? So, when I browse to the login form and enter an incorrect user/password, instead of going to "login.php" and then redirecting back to login_form.php, it simply determines whether the login was a success or not, and if not simply displays "Incorrect Login" above the input fields, as opposed to having to redirect back to login_form (which also doesn't notify the user that the login was incorrect).
A: Return a simple HTML page with a meta refresh tag pointing to the desired location in the <head>.
<meta http-equiv="refresh" content="5;url=login_form.php">
This will refresh (redirect) the page after 5 seconds to the given URL. I'd also consider adding a direct <a> link for the impatient.
<p>
You are logged out. You will be redirected to the login page in 5 seconds.
Click <a href="login_form.php">here</a> if you're impatient.
</p>
I personally find 5 seconds too long. Make it 3.
As to your second question, just let the form submit to self and redisplay the very same form with dynamically inlined error messages next to the input fields. Only redirect if the login has succeeded.
A: *
*Doing this in php alone would be difficult, or perhaps even impossible depending on the circumstances. Instead, take them to logout.php, or whatever page displays "You have been logged out," and simply add a meta refresh header, as in:
<meta http-equiv="refresh" content="5; url=login_form.php">
This will redirect them to login_form in 5 seconds. This is a popular technique, but I can't guarantee it will work in all circumstances either. However, as the other answer suggests, you can include a link to redirect directly.
*This can be done with javascript (you can perform the validation with ajax and display an appropriate error message/let them log in as needed). If javascript is not an option or if you also need to handle users who don't have it, when login.php rejects the authentication, set a _SESSION parameter such as _SESSION[login_fail_message] = true. On login_form.php, check if this value is true. If it is, display your "Incorrect login" message. Clear this value on login attempt (or ideally if they leave the page).
A: For the first part, know that changing the location header will have an immediate effect. Some sites allow the login form to display the message that the user has successfully logged out.
For the second part, have javascript do the validation first and display any errors client-side. If it passes the javascript, have the server do the server-side validation from the POST and return the login form again, but this time with the error areas marked. A login success should redirect them instead as normal.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Setting alpha on a BitmapDrawable in XML I was wondering if its possible to set transparency in XML for a Drawable.
In this case its setting the disabled state of a button. Instead of using a separate image i should like to create a grayed-out version by changing the alpha. I know I could do that in code. But can it also be predefined in XML?
A: Since: API Level 11 it is possible for View. but if we are talking about ImageView there is a tint attribute ans it's since API Level 1.
http://developer.android.com/reference/android/widget/ImageView.html#attr_android:tint
http://developer.android.com/reference/android/view/View.html#attr_android:alpha
A: I have been looking for the same thing. Even though this is posted over four years ago, this is one of the top post when googling the issue, so I'll reply here.
This is my solution
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false">
<bitmap android:alpha="@integer/disabled_alpha" android:src="@drawable/item"/>
<item/>
<item android:state_enabled="true" android:drawable="@drawable/item" />
</selector>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Jquery UI Accordion - Collapsed & Clickable Links I am attempting to use the Jquery UI accordion as a Side Navigation option. The problem is I am unable to have the accordion totally collapsed on load (and when desired by user) and to have active links on some of the pannel headers.
Using
Jquery 1.6.2 &
Jquery UI 1.8.16.
$(function() {
$( "#accordion" ).accordion({
active: false,
collapsible: true,
autoHeight: false,
});
});
<div id="accordion">
<h3><a href="http://link1.html">Outside Link 1</a></h3>
<div></div>
<h3><a href="http://link2.html">Outside Link 2</a></h3>
<div></div>
<h3><a href="http://link3.html">Outside Link 3</a></h3>
<div></div>
<h3><a href="#">More Info</a></h3>
<div class="subNav">
<ul>
<li><a href="pageLink1.html">Another Page 1</a></li>
<li><a href="pageLink2.html">Another Page 2</a></li>
<li><a href="pageLink3.html">Another Page 3</a></li>
</ul>
</div>
<h3><a href="http://link4.html">Outside Link 4</a></h3>
<div></div>
<h3><a href="#">More Info 2</a></h3>
<div class="subNav">
<ul>
<li><a href="pageLink4.html">Another Page 4</a></li>
<li><a href="pageLink5.html">Another Page 5</a></li>
<li><a href="pageLink6.html">Another Page 6</a></li>
</ul>
</div>
...etc
</div>
"Outside Links" should link to other pages directly. "More Info & More Info 2" should open up so the user can choose "Another Page" respectively.
I am not able to collapse the accordion on load or if clicked if I change the header selector (I can access the "Outside Links" this way). Could my empty divs be the culprit?
Any help is appreciated. Thanks in advance.
A: You're in luck. someone made a plugin for this.
http://www.i-marco.nl/weblog/jquery-accordion-3/# It works like you want it to.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Mental block with os.walk - want to process a file not the filename string Trying to implement a little script to move the older log files out of apache (actually using a simple bash script to do this in 'real life' - this is just an exercise to practice using Python). I'm getting the filename as a string as the variable f, but I want this to actually be a file when i pass it to self.processFile(root, f, age, inString).
I tried opening the actual file a few different ways, but I'm missing the target, and end up getting an error, a path that doesn't always seem to be correct, or just a string. I'll blame it on the late night, but I'm blanking on the best way to open f as a file right before passing to self.processFile (where it will be gzipped). Usually its something very simple that i'm missing, so I have to assume that's the case here. I'd appreciate any constructive advice/direction.
"""recursive walk through /usr/local/apache2.2/logs"""
for root, dirs, files in os.walk(basedir):
for f in files:
m=self.fileFormatRegex.match(f)
if m:
if (('access_log.' in f) or
('error.' in f) or
('access.' in f) or
('error_log.' in f) or
('mod_jk.log.' in f)):
#This is where i'd like to open the file using the filename f
self.processFile(root, f, age, inString)
A: Use os.path.abspath:
self.processFile(root, open(os.path.abspath(f)), age, inString)
Like so:
import os
for root, dirs, files in os.walk(basedir):
for f in files:
m=self.fileFormatRegex.match(f)
if m:
if (set('access_log.', 'error.', 'access.', 'error_log.','mod_jk.log.').intersection(set(f))):
self.processFile(root, open(os.path.abspath(f)), age, inString)
Or os.path.join:
import os
for root, dirs, files in os.walk(basedir):
for f in files:
m=self.fileFormatRegex.match(f)
if m:
if (set('access_log.', 'error.', 'access.', 'error_log.','mod_jk.log.').intersection(set(f))):
self.processFile(root, open(os.path.join(r"/", root, f)), age, inString)
# Sometimes the leading / isnt necessary, like this:
# self.processFile(root, open(os.path.join(root, f)), age, inString)
More about os.path
Yet another way using file() instead of open() (does almost the same thing as open):
self.processFile(root, file(os.path.join(root, f), "r"), age, inString)
self.processFile(root, file(os.path.abspath(f), "r+"), age, inString)
A: base = "/some/path"
for root, dirs, files in os.walk(base):
for f in files:
thefile = file(os.path.join(root, f))
You'll have to join the root argument to each of the files argument to get a path to the actual file.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591920",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Check if an IEnumerable has less than a certain number of items without causing any unnecessary evaluation? Sometimes I expect a certain range of items and need to do some validation to ensure that I am within that range. The most obvious way to do this is to just compare the number of items in the collection with the range.
public static bool IsWithinRange<T>(this IEnumerable<T> enumerable, int max)
{
return enumerable.Count() <= max;
}
Although, my understanding is that the linq Count() method will evaluate the entire enumerable before returning a result. Ideally I would only cause evaluation on the minimal number of items to get my result.
What would be the best way to ensure that an enumerable has less than a certain number of items without causing any unnecessary evaluation?
A: There are several different ways to do this. Perhaps the simplest is:
public static bool IsWithinRange<T>(this IEnumerable<T> enumerable, int max)
{
return enumerable.Take(max+1).Count() <= max;
}
A: Don't use Count(), as you already know, the entire collection would have to be traversed in general.
You can do this instead:
public static bool IsWithinRange<T>(this IEnumerable<T> enumerable, int max)
{
return !enumerable.Skip(max).Any();
}
Note you will still have to enumerate over the first max items in the collection, that's unavoidable unless you try to make some assumptions about the underlying collection.
To really optimize this further, you can check if the underlying type is an ICollection<> or ICollection in order to access the Count property. That way you don't have to enumerate over the items at all. Otherwise fallback on enumerating the items.
public static bool IsWithinRange<T>(this IEnumerable<T> enumerable, int max)
{
var asCollection = enumerable as System.Collections.ICollection;
if (asCollection != null) return asCollection.Count <= max;
var asGenericCollection = enumerable as ICollection<T>;
if (asGenericCollection != null) return asGenericCollection.Count <= max;
return !enumerable.Skip(max).Any();
}
Of course this isn't exactly free as you're doing additional checks, but it beats having to enumerate over the collection if at all possible, particularly if max is large.
A: You could combine Count() with Take().
return enumerable.Take(max + 1).Count() <= max;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591921",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: How to move Content Control DataTemplate to Dictionary Resources XML I've been given a great example of how to apply a dynamic style within a Conten Control.
I know my XAML for each style is going to get really big, I'd like to split the DataTemplate off to separate XAML files (I guess ResourceDictionary's). I just can't seem to get it to work.
<ContentControl Content="{Binding MyViewModel}">
<ContentControl.Resources>
<DataTemplate x:Key="DefaultTemplate">
<TextBlock Text="DefaultTemplate" />
</DataTemplate>
<DataTemplate x:Key="TemplateA">
<TextBlock Text="Template A" />
</DataTemplate>
<DataTemplate x:Key="TemplateB">
<TextBlock Text="Template B" />
</DataTemplate>
</ContentControl.Resources>
<ContentControl.Style>
<Style TargetType="{x:Type ContentControl}">
<Setter Property="ContentTemplate" Value="{StaticResource DefaultTemplate}" />
<Style.Triggers>
<DataTrigger Binding="{Binding SelectedView}" Value="ViewA">
<Setter Property="ContentTemplate" Value="{StaticResource TemplateA}" />
</DataTrigger>
<DataTrigger Binding="{Binding SelectedView}" Value="ViewB">
<Setter Property="ContentTemplate" Value="{StaticResource TemplateB}" />
</DataTrigger>
</Style.Triggers>
</Style>
</ContentControl.Style>
As an example, I want this template:
<DataTemplate x:Key="TemplateB">
<TextBlock Text="Template B" />
</DataTemplate>
to reside in a different XAML file (lets call it Test.xaml).
I've tried creating a ResourceDictionary file and referencing the Key in the DataTemplate, but obviously it couldn't find the key because it resides in a different XAML file, so I've tried to implement a Merged ResourceDictionary but VS2010 throws errors - e.g.
Test.xaml
<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
<DataTemplate x:Key="TemplateB">
<TextBlock Text="Template B" />
</DataTemplate>
with:
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="Test.xaml"/>
</ResourceDictionary.MergedDictionaries>
</ResourceDictionary>
</Window.Resources>
But then I get an error "Resources Property has already been set".
What am I doing wrong?
Ben
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Maven : Failed to collect dependencies I have exported a Maven Project . (So i dont have settings.xml file with me )
When i ran the Mavens POM.xml file the build is failin due to this reasson
Failed to execute goal on project bayer-ws: Could not resolve
dependencies for project com.tata:bayer-ws:war:1.0: Failed to collect
dependencies for [com.tata:bayer-util:jar:1.0 (compile),
com.tata:bayer-model:jar:1.0 (compile), com.tata:bayer-samples:jar:1.0
(compile), com.tata:bayer-mw:jar:1.0 (compile),
com.tata:bayer-fixml:jar:1.0 (compile), cglib:cglib-nodep:jar:2.1_3
(runtime), jdom:jdom:jar:1.1 (compile),
org.apache.ws.commons.schema:XmlSchema:jar:1.4.5 (runtime),
javax.servlet:servlet-api:jar:2.5 (provided), junit:junit:jar:4.4
(test), org.easymock:easymockclassextension:jar:2.3 (test),
org.easymock:easymock:jar:2.3 (test),
org.apache.cxf:cxf-rt-bindings-http:jar:2.2.1 (compile),
org.apache.cxf:cxf-rt-ws-security:jar:2.2.1 (compile),
org.apache.derby:derby:jar:10.3.1.4 (test),
org.springframework:spring-beans:jar:2.5.2 (compile),
org.springframework:spring-context:jar:2.5.2 (compile),
org.springframework:spring-core:jar:2.5.2 (compile),
org.springframework:spring-web:jar:2.5.2 (compile),
log4j:log4j:jar:1.2.14 (runtime),
commons-logging:commons-logging:jar:1.1.1 (runtime),
com.tata:middleware:jar:5.0.0 (compile), com.tata:PRO:jar:1.0.0
(compile), com.tata:legacy.backoffice:jar:1.0.0 (compile),
hessian:hessian:jar:3.0.8 (compile),
commons-httpclient:commons-httpclient:jar:3.1 (runtime),
xstream:xstream:jar:1.2.2 (compile), bouncycastle:bcprov-jdk16:jar:140
(runtime), org.apache.ws.security:wss4j:jar:1.5.8 (compile),
net.sf.ehcache:ehcache-core:jar:2.4.1 (runtime)]: Failed to read
artifact descriptor for commons-logging:commons-logging:jar:99.1:
Could not transfer artifact commons-logging:commons-logging:pom:99.1
from/to maven-central (http://repo1.maven.org/maven/): No connector
available to access repository maven-central
(http://repo1.maven.org/maven/) of type legacy using the available
factories AsyncRepositoryConnectorFactory,
WagonRepositoryConnectorFactory -> [Help 1]
// Before
<repositories>
<repository>
<id>central</id>
<url>http://repo1.maven.org/maven2</url>
<releases>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
<repository>
<id>codehaus</id>
<url>http://repository.codehaus.org/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
<repository>
<id>Apache Incubating Repository</id>
<url>http://people.apache.org/repo/m2-incubating-repository</url>
<releases>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
<repository>
<id>apache-snapshot</id>
<name>Apache Maven Snapshot</name>
<url>http://people.apache.org/repo/m2-snapshot-repository</url>
<releases>
<enabled>false</enabled>
<updatePolicy>always</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
<repository>
after
<repositories>
<repository>
<id>central</id>
<url>http://nexus.sonatype.org/url> <!--Here i did a change-->
<releases>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
<repository>
<id>codehaus</id>
<url>http://repository.codehaus.org/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
<repository>
<id>Apache Incubating Repository</id>
<url>http://people.apache.org/repo/m2-incubating-repository</url>
<releases>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
<repository>
<id>apache-snapshot</id>
<name>Apache Maven Snapshot</name>
<url>http://people.apache.org/repo/m2-snapshot-repository</url>
<releases>
<enabled>false</enabled>
<updatePolicy>always</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
<repository>
A: It seems you're trying to access Maven 1 legacy repositories.
Please check this answer:
How to use a maven 1 repository with maven 2?
"The Nexus repository manager is able to proxy Maven 1 repositories for Maven {2,3} clients."
A: You missed the "<" in your end URL tag
<repositories>
<repository>
<id>central</id>
<url>http://nexus.sonatype.org</url> <!--Here is your problem-->
<releases>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
<repository>
<id>codehaus</id>
<url>http://repository.codehaus.org/</url>
<releases>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
<repository>
<id>Apache Incubating Repository</id>
<url>http://people.apache.org/repo/m2-incubating-repository</url>
<releases>
<enabled>true</enabled>
<updatePolicy>never</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
<repository>
<id>apache-snapshot</id>
<name>Apache Maven Snapshot</name>
<url>http://people.apache.org/repo/m2-snapshot-repository</url>
<releases>
<enabled>false</enabled>
<updatePolicy>always</updatePolicy>
</releases>
<snapshots>
<enabled>false</enabled>
<updatePolicy>always</updatePolicy>
</snapshots>
</repository>
<repository>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: C++ compiler from VS2005 If I would like to use the compiler that comes with Visual Studio 2005 but without IDE which Platform/Windows SDK should I install to get it? Windows SDK 2008?
A: Download the .NET Framework 2.0 Software Development Kit (SDK) (x86) for 2005.
A: According to this MSDN blog article:
*
*Updated Windows SDK Visual C++ Cross Compilers
The compilers in the new Windows Server 2008 and .NET Framework 3.5 SDK match (are exactly the same as) the compilers shipped with Visual Studio 2008. In the Windows Vista RTM SDK or the Windows Vista Update SDK, the compilers matched the Visual Studio 2005 compilers.
You can find a link to the Windows Vista Update SDK in this Wikipedia article:
*
*Microsoft Windows SDK
A: (For reference) If you have Visual Studio 2005 installed you can run one of the special command prompts they put in the start menu to get access to the command line compiler and tools.
Edit:
You can still find Visual Studio C++ 2005 Express Edition download in various places. That should contain the command line compilers. Otherwise try looking for a Visual C++ 2005 Toolkit download.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NoSql Referential Data Disclaimer: by referential Data, i do not mean referential integrity
I am learning nosql and would like to understand how data should be modeled. In a typical relational database for an CMS application, for example, you may have two tables: article and author, where article have an reference to the author.
In nosql system, you may create an article document this way since they are just disguised object graph
{
title: "Learn nosql in 5 minutes",
slug: "nosql_is_easy",
author: {firstName: "Smarty"
lastName: "Pants"
}
{
title: "Death to RDBMS",
slug: "rdbms_sucks",
author: {firstName: "Smarty"
lastName: "Pants"
}
and so on...
Say one day Mr. Smarty Pants decided to change his name to Regular Joe because nosql has become ubiquitous. In such uses case, every article would need to be scanned and the author's name updated.
So my questions is, how should the data be modeled in nosql to fit the basic use cases for an CMS so that the performance is on par or faster than RDBMS? mongodb, for example, claims CMS as an use-case ...
Edit:
Few people have already suggested normalizing the data like:
article
{
title: "Death to RDBMS",
slug: "rdbms_sucks",
author: {id: "10000001"}
}
author
{
name: "Big Brother",
id: "10000001"
}
However, since nosql, by design, lack joins, you would have to use mapreduce-like functions to bring the data together. If this is your suggestion, please comment on the performance of such operation.
Edit 2:
If you think nosql is not suitable solution for any kind of data that requires referential data, please also explain why. This would seem to make the use case for nosql rather limited since any reasonable application would contain relational data.
Edit 3:
Nosql doesn't mean non-relational
A: Your data is clearly relational: an article has an author. You can model your data in a NOSQL store like MongoDB in just the same way as you would in a relational store BUT because there are no joins in the database you have to make two calls to the database so you haven't gained anything.
BUT ... what you CAN do with a NOSQL store is to denormalize the data somewhat to get improved performance (a single round trip to get everything you need to display the article) BUT at the expense of immediate consistency: trading off always accurate author names for eventually accurate author names.
You might for example, use this in your article:
author: {firstName: "Smarty", lastName: "Pants", _id:DE342624EF }
Now you can display the article really fast and when someone does change their name you can either kick off a background task to update all the existing articles or you can wait for a periodic consistency sweep to fix it.
Many major web sites no longer give you immediate consistency. There are changes that you make that are only eventually seen by the other users on the site.
A: I suppose CouchDB is a NoSQL database, if you say so.
But really, we have general-purpose programming languages, and domain-specific languages. Similarly, CouchDB is a domain-specific database.
I use CouchDB a lot but I really don't care whether it uses SQL or NoSQL. CouchDB is valuable (to me) because the API is 100% HTTP, JSON, and Javascript. You can build web applications with the browser fetching HTML from CouchDB and then querying for data over AJAX. To say this is "not SQL" is an understatement!
Anyway, back to Smarty Pants and Regular Joe. Maybe he has 100,000 documents. What if we just updated them all, the hard way? Well, that is a pretty small amount of Javascript.
$.getJSON('/db/_design/cms/_view/by_user?key=Smarty+Pants', {
success: function(result) {
// Change the name right here, in the result objects.
var docs = result.rows.map(function(row) {
row.value.firstName = "Regular";
row.value.lastName = "Joe";
return row.value;
})
// Store it!
$.post('/db/_bulk_docs', {"docs":docs}, function() {
console.log("Done! Renamed Smarty Pants in " + docs.length + " documents!");
})
}
})
Yes, this technique would get you an F in computer science class. However, I like it. I would write this code in Firebug. In my browser. The rename is not atomic and it has no referential integrity. On the other hand, it would probably complete in a couple of seconds and nobody would care.
You might say CouchDB fails at the buzzwords and benchmarks but aces the school of hard knocks.
P.S. The by_user view is built from map-reduce. In CouchDB, map-reduce is incremental which means it performs like most SQL indexes. All queries finish in a short, predictable (logarithmic) time.
A: for you specific case, use Flyweight pattern , store object id instead of object entity .
article
{
title: "Death to RDBMS",
slug: "rdbms_sucks",
author: {id: "10000001"}
}
author
{
name: "Big Brother",
id: "10000001"
}
for general mongodb Schema Design suggestion, read the offical documents
A: Allow me state that I am not an expert with NoSQL by any means. Instead, my knowledge of it is mostly theoretical.
That said, I'm a firm believer that implementing a CMS-type system like this in NoSQL is probably not the best way to go about things, since the data is primarily relational.
My take on this problem, is based on the presumption that the NoSQL system you're using allows for loading records by way of a "primary key"-type structure. I think most do, but I'm sure there are some that don't.
That said, I would suggest storing the data in the following fashion.
For the author:
{
_KEY: $AUTHOR_GUID,
firstName: "Smarty",
lastName: "Pants",
}
And for the post itself:
{
title: "Learn nosql in 5 minutes",
slug: "nosql_is_easy",
author: $AUTHOR_GUID,
}
Note that in the above, I use _KEY to represent that this is the "primary key"-type value.
After loading the post, you can then load the author by it's GUID.
A: This post has been here for some time, but I thought I'd point out another method to handle "joins" and cross-document references with CouchDB. This is a method I employ in the CMS I am (re)writing to use CouchDB (formerly it was written for MySQL).
The CMS is named BlueInk and can be found on Github at http://github.com/BigBlueHat/BlueInk At present the rewrite is focused on the document design and "rendering engine" portion, so there's no UI to speak of--you have to craft all the JSON by hand. That's something I hope to fix soon, but there's already enough in the repo (once installed into CouchDB) to give you an idea of how "joins" are done.
In BlueInk a page references content items which can themselves be included in one or more pages (or the same page multiple times). The page references the page items via their ID (as in your second JSON example). When run via the "page_and_items" view it will generate output that can be used with CouchDB's ?include_docs=true query parameter to pull in the full contents of the content items references within the page document.
The view output is then passed through a _list function and formatted via a Mustache template and output as an HTML page--all in a single GET request.
This same pattern of using referenced IDs with ?include_docs=true can be used in your use case above. The use of a _list function is completely "cosmetic," but it can be helpful for restructuring the output view JSON or templating it and outputting HTML, CSV, XML, etc.
A: You can model your data just fine with playOrm AND do joins in a noSQL store. playOrm has S-SQL(Scalable SQL) which is a twist on SQL in that you specify which partitions you are querying. In this way, you can move from DBMS to noSQL and still have the same familiar tools you were used too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
}
|
Q: How do I limit the threads in a ATL DCOM service? I have an ATL service which implements a free threaded COM object. Our testers are running more and more threads against the service but this eventually results in an ugly runtime crash when it starts running out of RAM.
How can I configure ATL (or COM) to limit the number of threads that are created inside the service?
I've been looking at the CComClassFactoryAutoThread. Looks like you enable this with the DECLARE_CLASSFACTORY_AUTO_THREAD macro but I don't know if I can use this with a service. Also how do I limit the thread pool size if I use this?
Thanks,
Tom
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Cocos2D for First Game - Advice for Beginner I never developed in Cocos2D. However, this animated app is not easy to make with regular UIView animation and CAAnimation.
I want a number of UIImageView's (from 1 to 30) to float around the screen with the certain path and I want them to be responsive for touch (they would do some animation when touched). I also need them to go back and forth the screen (new path would be calculated) when they are touched or reach the edge of screen. It's important to retrieve X and Y position of each element whenever needed.
Question is: what Cocos2D classes are best looking at (for a beginner) to make that happen? I've tried UIView animation and CAAnimation but I came across some difficulties so I have a feeling Cocos2D may bring better results. Thank you.
A: Yes, cocos2d makes it much easier. You want to create a CCSprite with the initWithFile: method. Example:
CCSprite *mySprite = [CCSprite initWithFile:@"fire.png"];
[self addChild:mySprite];
Where fire.png has been added to the project and self is the scene instance.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591953",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to change gitosis default search path? I installed gitosis on my ubuntu desktop. But when I try "git clone git@localhost:gitosis-admin.git", it kept searching /home/git/, not /home/git/repositories. So I have to type "git clone git@localhost:repositories/gitosis-admin.git".
I guess there's something wrong with the default search path of gitosis. However, how to change it?
UPDATE 1:
I searched around and some pages says the reason of cannot clone use the address like "git@localhost:gitosis-admin.git" is because I'm on the git server itself. This still need time to validate.
UPDATE 2:
Even in another computer, still cannot use the shortest url. I gave it up.
UPDATE 3:
Now I turn to gitolite, and it's easier configure.
A: Replay the part:
cd gitosis
sudo python setup.py install
The setup.py install script is supposed to create the repositories directory.
It takes the path from util.py:
def getRepositoryDir(config):
repositories = os.path.expanduser('~')
try:
path = config.get('gitosis', 'repositories')
except (NoSectionError, NoOptionError):
repositories = os.path.join(repositories, 'repositories')
else:
repositories = os.path.join(repositories, path)
return repositories
Note: considering the 'obsolete' status of the gitosis project, I mentioned in the comment Gitolite.
The OP liuyanghejerry approved:
You're right, I just installed gitolite in only few steps.
Now I can use git clone gitolite:gitolite-admin.git
A: Change the home path of the gitosis user, eg:
sudo usermod --home /repos/gitosis --move-home
This should change the gitosis repository search path.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: C++ OpenSSL HMACSHA1 works but not how I want it to This HMACSHA1 code below works for converting "Password" and "Message" to AFF791FA574D564C83F6456CC198CBD316949DC9 as evidence by http://buchananweb.co.uk/security01.aspx.
My question is, Is it possible to have:
BYTE HMAC[] = {0x50,0x61,0x73,0x73,0x77,0x6F,0x72,0x64};
BYTE data2[] = {0x4D,0x65,0x73,0x73,0x61,0x67,0x65};
And still get the same value: AFF791FA574D564C83F6456CC198CBD316949DC9.
For example, if I was on a server and received the packet:
[HEADER] 08 50 61 73 73 77 6F 72 64 00
[HEADER] 07 4D 65 73 73 61 67 65 00
And I rip 50 61 73 73 77 6F 72 64 & 4D 65 73 73 61 67 65 from the packet and used this for my HMACSHA1. How would I go about doing that to get the correct HMACSHA1 value?
BYTE HMAC[] = "Password";
BYTE data2[] = "Message";
//BYTE HMAC[] = {0x50,0x61,0x73,0x73,0x77,0x6F,0x72,0x64};
//BYTE data2[] = {0x4D,0x65,0x73,0x73,0x61,0x67,0x65};
HMAC_CTX ctx;
result = (unsigned char*) malloc(sizeof(char) * result_len);
ENGINE_load_builtin_engines();
ENGINE_register_all_complete();
HMAC_CTX_init(&ctx);
HMAC_Init_ex(&ctx, HMAC, strlen((const char*)HMAC), EVP_sha1(), NULL);
HMAC_Update(&ctx, data2, strlen((const char*)(data2)));
HMAC_Final(&ctx, result, &result_len);
HMAC_CTX_cleanup(&ctx);
std::cout << "\n\n";
for(int i=0;i<result_len;i++)
std::cout << setfill('0') << setw(2) << hex << (int)result[i];
int asd;
std::cin >> asd;
// AFF791FA574D564C83F6456CC198CBD316949DC9
EDIT:
It works by doing this:
BYTE HMAC[] = {0x50,0x61,0x73,0x73,0x77,0x6F,0x72,0x64, 0x00};
BYTE data2[] = {0x4D,0x65,0x73,0x73,0x61,0x67,0x65, 0x00};
By adding 0x00, at the end. But, my question is more towards ripping it from data, and using it... would it still be fine?
A: The issue is the relation ship between arrays, strings, and the null char.
When you declare "Password", the compiler logically treats the string literal as a nine byte array, {0x50,0x61,0x73,0x73,0x77,0x6F,0x72,0x64, 0x00}. When you call strlen, it will count the number of bytes until it encounters the first 0x00. strlen("Password") will return 8 even though there are technically nine characters in the array of characters.
So when you declare an array of 8 bytes as follows without a trailing null byte:
BYTE HMAC[] = {0x50,0x61,0x73,0x73,0x77,0x6F,0x72,0x64};
The problem is that "strlen(HMAC)" will count at least 8 bytes, and keep counting while traversing undefined memory until it finally (if ever) hits a byte that is zero. At best, you might get lucky because the stack memory always has a zero byte padding your array declaration. More likely it will return a value much larger than 8. Maybe it will crash.
So when you parse the HMAC and MESSAGE field from your protocol packet, you count the number of bytes actually parsed (not including the terminating null). And pass that count into the hmac functions to indicate the size of your data.
I don't know your protocol code, but I hope you aren't using strlen to parse the packet to figure out where the string inside the packet ends. A clever attacker could inject a packet with no null terminator and cause your code do bad things. I hope you are parsing securely and carefully. Typical protocol code doesn't include the null terminating byte in the strings packed inside. Usually the "length" is encoded as an integer field followed by the string bytes. Makes it easier to parse and determine if the length would exceed the packet size read in.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: counting number of occurrences of an object in a list I am trying to find the number of occurrences of an object in a list:
class Complex{
double re, im;
public:
Complex (double r, double i):re(r), im(i){}
Complex (){re = im = 0;}
friend bool operator == (Complex, Complex);
};
bool operator == (Complex a, Complex b){
return a.re == b.re and a.im == b.im;
}
template <class ContainerType, class ElementType>
int const count (ContainerType const & container, ElementType const & element){
int count = 0;
typename ContainerType::const_iterator i = std::find (container.begin(), container.end(), element);
while (i != container.end()){
++count;
i = std::find (i + 1, container.end(), element);
}
return count;
}
int main(){
std::list <Complex> lc;
lc.push_front (Complex (1.2, 3.4));
std::cout << count (std::string("abhi"), 'a') << '\n';
std::cout << count (lc, Complex (1.2, 3.4)) << '\n';
return 0;
}
I get this error with g++ 4.5:
templatizedcharOccurences.c++: In function ‘const int count(const ContainerType&, const ElementType&) [with ContainerType = std::list<Complex>, ElementType = Complex]’:
templatizedcharOccurences.c++:51:44: instantiated from here
templatizedcharOccurences.c++:41:4: error: no match for ‘operator+’ in ‘i + 1’
templatizedcharOccurences.c++:22:9: note: candidate is: Complex operator+(Complex, Complex)
Why is it complaining about i+1? Clearly, isn't i an iterator (pointer) and not a Complex object?
A: You could simplify the code a lot in one of two ways:
Use std::count or one of its variants to do the counting. So:
return std::count(container.begin(), container.end(), element);
Or just use a simple for loop like you already do but iterate it from beginning to end and do the counting yourself, like so:
int count = 0;
for (ContainerType::const_iterator it = container.begin(); it != container.end(); ++it)
{
if (*it == element) ++count;
}
return count;
Since you're already using parts of the STL I would suggest using the first method.
A: It seems Iterator does not have overloaded operator+(int), try:
class Complex{
double re, im;
public:
Complex (double r, double i):re(r), im(i){}
Complex (){re = im = 0;}
friend bool operator == (Complex, Complex);
};
bool operator == (Complex a, Complex b){
return a.re == b.re and a.im == b.im;
}
template <class ContainerType, class ElementType>
int const count (ContainerType const & container, ElementType const & element){
int count = 0;
typename ContainerType::const_iterator i = std::find (container.begin(), container.end(), element);
while (i != container.end()){
++count;
i = std::find (++i, container.end(), element);
}
return count;
}
int main(){
std::list <Complex> lc;
lc.push_front (Complex (1.2, 3.4));
std::cout << count (std::string("abhi"), 'a') << '\n';
std::cout << count (lc, Complex (1.2, 3.4)) << '\n';
return 0;
}
I hope this would work.
A: It is a list iterator which doesn't have random access operations. You want to do:
++i;
i = std::find (i, container.end(), element);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ec2 ami for rails 3.1 apache passenger Is there an ec2 ami available with
*
*apache
*passenger
*rails 3.1
preferably ubuntu or fedora.
A: Rather than look for an AMI with the software pre-installed, simply run an official Ubuntu server AMI and install the standard Ubuntu packages for the software you want.
It's probably as simple as:
sudo apt-get update &&
sudo apt-get upgrade &&
sudo apt-get install apache2 ...
Then tweak configuration and add your content / application.
If you are trying to run a version of software more recent than the one provided with the official release, then you may need to do a bit more work.
Remember to document / script exactly how you create the instance so that you can do it again in the future when you need to.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: HTTP Server System.out problem So I have an assignment where I have to make a HTTP Server with chosen programming language. No big deal. I have encountered a problem that I cant seem to figure out. Every time I load the homepage that and the server response, it prints out about 5 times. Cant figure out why. Okay so what I mean:
Code Snippets:
while(true){
connectedClient = listenSocket.accept();
inFromClient = new BufferedReader( new InputStreamReader( connectedClient.getInputStream()));
outToClient = new DataOutputStream(connectedClient.getOutputStream());
String requestString = inFromClient.readLine();
String headerLine = requestString;
StringTokenizer tokenizer = new StringTokenizer(headerLine);
String httpMethod = tokenizer.nextToken();
String httpQueryString = tokenizer.nextToken();
requestString = inFromClient.readLine();
if (httpMethod.equals("GET")) {
if (httpQueryString.equals("/Home")) {
// The default home page status code 200
dateHeader();
connectionCloseHeader();
}
//other code not related
}
And this is my date header method:
public static void dateHeader() throws Exception{
DateFormat dateFormat = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss z");
Date date = new Date();
System.out.println("Date: " + dateFormat.format(date));
}
My output to the terminal will be 5 printouts of the date. I made sure that the connection and such was closed but same thing happens. Anyone have an idea why this is happening? Thanks.
EDIT
Seems that when using Chrome I get the one print out no problem. I was testing with Opera and that was giving me the 5 printouts. Perhaps something with the way the browsers work is causing the issue. Ill just use chrome now for it though.
A: I can't account for five different invocations right off, but if you're using a typical browser to hit this HTTP server, you'll immediately see two requests: one for the resource itself and one for a favicon.ico. Somewhere in your request handler, you should read in and print out the entire request. Then you can see exactly what all the requests are for.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: php foreach key as a class variable Can someone please tell me if this method of doing foreach has drawbacks?
class someclass {
function foo() {
foreach ($my_array as $this->key => $this->value) {
$this->bar();
$this->baz();
}
}
function bar(){
//do something with $this->key or $this->value
}
function baz(){
//do something with $this->key or $this->value
}
}
A: It's pretty inefficient as you are essentially setting the key to an associative array on each loop. I would keep them local and then assign them when the loop is done if you need to store them. Also, pass the values to the methods when you call them.
class SomeClass {
function foo($myArray) {
foreach ($myArray as $key => $value){
$this->bar($key);
$this->baz($value);
}
$this->key = $key;
$this->value = $value;
}
function bar($key){
//do something with $this->key or $this->value
}
function baz($value){
//do something with $this->key or $this->value
}
}
A: If you need the keys and values to be accessible publicly in your methods, I'd go with:
class someclass{
function foo($my_array){
foreach ($my_array as $key => $value){
$this->loopArray[$key] = $value;
$this->bar();
$this->baz();
}
}
function bar(){
//do something with $this->key or $this->value
}
function baz(){
//do something with $this->key or $this->value
}
}
$obj = new someclass();
$my_array = array('value1','value2');
$obj->foo($my_array);
var_dump($obj->loopArray);
Outputs:
array(2) { [0]=> string(6) "value1" [1]=> string(6) "value2" }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591976",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: MySQL Connector C linking problem on VS2010 I am beginning on MySQL, and I encountered the error message while compiling the code:
error LNK2001: unresolved external symbol _mysql_init@4
I have searched the web, and did everything that seems to be the problem.
#include <my_global.h>
#include <mysql.h>
#define NULL 0
int main() {
MYSQL * sql = mysql_init(NULL);
return 0;
}
I have checked that I have been using /MT option. Include, link directory added. I use release, and included "lib\opt".
libmysql.lib is in linker->input->additional dependency.
I have been using windows 7 x64 with VS2010 x86, and downloaded and installed MySQL Connector/C
Windows (x86, 64-bit), MSI Installer 6.0.2
(mysql-connector-c-6.0.2-winx64.msi)
What might be the problem, can anybody help?
A: After a careful investigation, I found that the problem raised from the x64 settings.
x64 compilation option should be turned on when compiling an x64 project.
In this case, platform should be switched from win32 to x64,
and in project->properties->linker->advanced->target machine: x86 should be set to x64.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591977",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to synchronise some threads I do payment online system with asp.net mvc1.0, how can I do to allow only one person to buy something when it's stock is only one. In addtion I use other payment system(like ebay ) in this system.I mean when one product's stock is only one, and more than one person to buy it at one moment, how can i do to allow one person can buy it success and other can not buy it any more.
A: You will probably need to use database transactions to process your orders. It isn't just about locking an object (which, in this case, would have to be a static object in order to be shared by all web users), but about the access to complete an order in its entirety. Transactions are going to be what you need to use.
Also, it isn't clear when you say "I use other payment in this system." That doesn't have any bearing on the transactional management of inventory for sales.
A: In Order to only one thread to have access to crticial method you could use Lock keywork.
lock (myObj)
{
}
if you are looking for something more then would need more context to understand it.
A: You need to add a concurrent access control to your system.
For example you can implement this simple algorithm:
*
*Check the quantity of the objects present in the store that you want to sell
*Decrease the quantity for the number of object that you want to sell
*Pay the objects
*if payment is ok then end transaction
*if payment fails then execute the rollback the transaction, increase the quantity and return the money ;)
The important thing is point 2, updating the quantity of element in the store using an optimistic verify algorithm. For example write in the WHERE condition of your SQL operation the value of quantity that you have read in poit 1.
If someone change this value the update fails and the sell operation must be interrupted.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Silverlight ObservableCollection cannot get data from EntityQuery I am trying to get data that are returned from an EntityQuery
public EntityQuery<Product> GetProductsQuery()
and I am using an ObservableCollection to store them
var query = ctx.GetProductsQuery();
ctx.Load(query, op =>
{
var data = op.Entities;
ProductList = new ObservableCollection<Product>(op.Entities);
return;
}, null);
but after this code, the ProductList is still empty
A: Here are a couple of links hope they shed more light on your issue. They describe how to load data from RIA serives into ObservableCollections
Loading WCF RIA Services Query results to an ObservableCollection
Loading Data from RIA Services
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591980",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android Image Button I Have scoured the site and several others and I am having a problem finding a way to make a clarity nice icon styled image button. The image buttons I keep using fill the content and look just distorted, I want very nice looking icons styled image buttons, and instead its smudged stamps with little clarity. I want them spaced enough you can see the background behind them, Do i need to somehow make the src the image and the background clear?
heres some of my code:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/debface"
>
<TableLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="4"
android:gravity="bottom"
>
<!-- Images coming out Blurry, I need to compress like a hires icon file -->
<TableRow>
<ImageButton
android:id="@+id/button01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/debraidcard"
android:layout_weight="1"
android:padding="25px"
android:paddingLeft="25px"
android:paddingRight="25px"
/>
<ImageButton
android:id="@+id/button02"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:background="@drawable/debraidcard"
android:padding="25px"
android:paddingLeft="25px"
android:paddingRight="25px"
/>
<ImageButton
android:id="@+id/button03"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/debraidcard"
android:layout_weight="1"
android:padding="25px"
android:paddingLeft="25px"
android:paddingRight="25px"
/>
</TableRow>
I have used several different sizes on my images, i have switched between .jpg and .png. I follwed several tutorials, didn't like the outcomes. Any help pointing me in the right direction is greatly appreciated
A: Instead of setting your image to the background set it to src:
android:src="@drawable/cool_drawable"
that will give you your bitmap in the center of what looks like the default button.
If you don't like the button in the back set the background to #00000000 (transparent) and you will end up with only your Drawable as the button.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to use Tasks to simplify Delegate.BeginInvoke/Delegate.EndInvoke? Trying to wrap my head around the Tasks class, and more specifically, the Task.Factory.FromAsync method.
Currently in my code I am doing something like this:
var handler = MyEvent;
if (handler != null)
{
handler.Invoke(this, e);
}
Unfortunately, this is synchronous and I am looking for the asynchronous version. I could use BeginInvoke and EndInvoke but it seems like a bit of a waste considering I don't need a callback. I believe I heard somewhere it is possible to use one of the Task.Factory methods to simplify this call where a dummy callback would then not be necessary. Could anyone enlighten me?
A: It's somewhat unusual to invoke event handlers asynchronously; if the handler wants to process the event asynchronously, it should start a Task itself.
You can start a Task with the Task.Factory.StartNew Method*:
void MyClass_MyEvent(object sender, EventArgs e)
{
Task.Factory.StartNew(() =>
{
// do work
});
}
(* or the Task.Run Method in the Async CTP or .NET 4.5)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to turn off Android phone programmatically? I want to make a lock screen application. When the phone is in the lock mode, it will turn off the phone while the USB is plugged for prevent other users from accessing the phone data. Does anyone know how to turn off Android devices programmatically so other people can't access the data while a device on the lock mode?
here's the code to lock the home button on the lock screen activity:
@Override
public void onAttachedToWindow()
{
this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);
super.onAttachedToWindow();
}
A: It is impossible with the public Android SDK.
A: Yes it is possible,
Using making system application(Using firmware) not download application.
You can get the code for power off android device from AOSP.
A: This is what can provide you an insight of the OS you are working on , and not about developing an app that would run on any device, as you have not made OS's for them.
Just pull a branch of android , customize it according to your wish and in your mainfest remove the filters, permissions that don't allow you to do that, or add your owns. Now , you have to play with the battery if I talk of more depth.
But if you just want to trigger the click on power off then its far
simpler then.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Zend Framework _Redirect() not working but header(location:) is working I just got a new server and zend framework seems to be working properly EXCEPT, when a member posts something , they get a white page because $this->_redirect('/somepage'); doesn't work...
Am I unaware of some php setting or vhost setting I'm supposed to have? Header("Location:/somepage") works just fine.. :\
I've been looking through my logs with no luck. Also, my images aren't getting uploaded even when folders are set to 777...
I'm stumped. Let me know anything you need to help me fix this. It's a large site that is about to dissolve if this issue stays for longer than a couple days..
A: Some thoughts:
*
*Xdebug installed? Sometimes Problems with crazy errors
*Check Autoloader, possible redirect helper not found?
*Check Zend Framework (all files available?)
Have a look into your php.log if exceptions are thrown.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7591999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Variables in Redis configuration file I would like to set a REDIS_ROOT in my redis.conf file and be able to reuse that same variable across a number of other configuration points. I want to have all my logs, dumps, etc. go somewhere in this directory... something like $REDIS_ROOT/logs/redis.log.
Is there a way to set a variable of this kind in the Redis configuration file? Or am I stuck retyping it over and over (or doing some find-replace wizardry before using the conf file).
A: There does not appear to be any way to do this with Redis config files. However, there are only a couple places you should need to use a directory, unless you are doing a lot of includes. Redis configuration just isn't very complicated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592006",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: pythonw.exe processes not quitting after running script Every time I restart the shell or run a script and instance of pythonw.exe*32 is created. When I close out of IDLE these processes don't go away in the task manager. Any ideas on how to fix this?
Thanks!
A: Have you tried using python.exe instead of pythonw.exe?
Im pretty sure this is the intended default behavior for the window python interperter (pythonw.exe).
If its a .pyw file, just right click "Open With..." and use python.exe
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592008",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: xcode basic explanation needed I am actually a newby at xcode. I can make out a few things be myself but have questions about what some things do and why they are put there. I have tried to read many e-books, watched tutorials, but they never go into the basics, alway just say "Add this, Click here etc"
Could someone give me some answers to a few questions please.
Ok, I know an ios app is mostly made out of Views, views are controlled by controllers. Each controller has a header (.h) file and a module?class? file (.m). The .h file contains the declarations of variables and functions used in the .m file.
The whole app is controlled by a master "controller" called the "delegate".
Definitions in .h file may be for example an action IBAction or IBLabel or something.
What raises questions for me is for example these lines:
@class FlipsideViewController;
@protocol FlipsideViewControllerDelegate
- (void)flipsideViewControllerDidFinish:(FlipsideViewController *)controller;
@end
@interface FlipsideViewController : UIViewController
@property (nonatomic, assign) id <FlipsideViewControllerDelegate> delegate;
- (IBAction)done:(id)sender;
and why are sometimes in another view controller the delegate class loaded
@class MainViewController;
what does the following do, meaning what is the @interface declaration?
@interface flipAppDelegate : NSObject <UIApplicationDelegate>
what is
nonatomic, retain
sorry for asking really stupid questions, but every tutorial just skips these things.
I can follow a youtube video or a manual, but it doesn't teach me a lot...
A: Let me try to answer your questions, one at a time.
what is the @interface declaration?
The interface declares a class. By declaring a class, I mean it specifies the instance variables and private/public methods that it contains. Again, the header file only contains the declaration of the methods, and the implementation/body of the methods lies in the module class. So, here-
@interface FlipsideViewController : UIViewController
The class FlipsideViewController derives from/subclasses/extends UIViewController. i.e Is a type of UIViewController but adds its own features.
Similarly
@interface flipAppDelegate : NSObject <UIApplicationDelegate>
Subclasses NSObject and implements the UIApplicationDelegate protocol. A protocol is essentially a set of methods that a class promises to implement (although there can be optional methods).
why are sometimes in another view controller the delegate class loaded
The delegate pattern allows a class to delegate its work to another class that implements the delegate protocol. So, here, FlipsideViewController keeps an instance of the delegate object, so that its flipsideViewControllerDidFinish: can be called.
what is nonatomic, retain
It means that when you set a value to your instance variable, the value's refcount will be incremented and set to your variable. Also, it will not happen as an atomic operation. You need atomic only in a multi-threaded environment.
@synthesize is simply a shortcut to generate getters and setters for your variables.
A: You really need to read the Objective-C Programming Language from Apple. It's pretty brief, and runs down the basics of the architecture, concepts, and syntax.
To address, briefly, some specifics:
*
*The @class directive is used to declare the name of a class without importing it's header file. It is often used in a .h file declaring a protocol, because a protocol has no implementation, it doesn't need to import the interfaces of other classes (their .h files).
*A protocol is a way of declaring what methods and properties a class should have in order to "implement" the protocol.
*@interface is used in an interface file (.h) to declare a class, meaning to describe the methods and properties it will have, the protocols it will implement, and the superclasses from which it will inherit. In your example, the class will be called flipAppDelegate, which inherits all of the methods and properties of the NSObject class, and which implements the UIApplicationDelegate protocol.
*In your class (.m) file, you will define (with all your code) all of the methods and properties that you declared in your interface file. You include the methods and properties you declared yourself, and from the protocols you implement.
*@synthesize is used in a class implementation file (.m) to "synthesize" --- that is, automatically create the code for --- all the properties you declared in your interface (.h) file. Since properties normally just need basic accessors (a "getter" that just returns the current value, and a "setter" that just sets the current value), using @synthesize is a shortcut to let the compiler create the variable to store the value, the getter method, and the setter method for you automatically.
A: *
*Xcode = An IDE (Integrated Development Environment)
*Objective-C = A Language
*Cocoa Touch, Media FrameWork, Core FrameWork = Frameworks used in developing for iOS
I'd highly recommend starting by learning Objective-C. At least with a primer first:
https://developer.apple.com/library/ios/#referencelibrary/GettingStarted/Learning_Objective-C_A_Primer/_index.html
There's a wealth of tutorials and videos available from Apple for developers you might want to start on the developer portal.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Ideas for optimization algorithm for Fantasy Football So, this is a bit different than standard fantasy football. What I have is a list of players, their average "points per game" (PPG) and their salary. I want to maximize points per game under the constraint that my team does not exceed a salary cap. A team consists of 1 QB, 1 TE, 3 WRs, and 2 RBs. So, if we have 15 of each position we have 15X15 X(15 c 3)X(15 c 2) = 10749375 possible teams.
Pretty computationally complex. I can use a bit of branch and bound i.e. once a team has surpassed the salary cap I can trim the tree, but even with that the algorithm is still pretty slow. I tried another option where I used a "genetic algorithm" i.e. made 10 random teams, picked the best one and "mutated" it (randomly changing some of the players) into another 10 teams and then picked of those and then looped through a bunch of times until the points per game of the "best team" stopped getting better.
There must be a better way to do this. I'm not a computer scientist and I've only taken an intro course in algorithmics. Programmers - what are your thoughts? I have a feeling that some sort of application of dynamic programming could help.
Thanks
A: I think a genetic algorithm, intelligently implemented, will yield an acceptable result for you. You might want to use a metric like points per salary dollar rather than straight PPG to decide the best team. This way you are inherently measuring value added. Also, you should consider running the full algorithm/mutation to satisfactory completion numerous times so that you can identity what players consistently show up in the final outcomes. These players then should be valued above others.
Of course the problem with the genetc approach Is that you need a good mutation algorithm and that is highly personal for how you want to implement it.
A: Take i as the current number of players out of n players and j to be the current remaining salary that is left. Take m[i, j] to be the dynamic set of solutions.
Then m[i, 0] = 0, m[0, j] = 0
and
m[i, j] = m[i - 1, j] if salary for player i is greater than j
else
m[i, j] = max ( m[i - 1, j], m[i - 1, j - salary of player i] + PPG of player i)
Sorry that I don't know R but I'm good with algorithms so I hope this helps.
A further optimization you can make is that you really only need 2 rows of m[i, j] because the DP solution only uses the current row and the last row (you can save memory this way)
A: First of all, the variation you have provided should not be right. Best way to build team is limit positions by limited plus there is absolutely no sense of moving 3 similar positions players between themselves.
Christian Ronaldo, Suarez and Messi will give you the equal sum of fantasy points in any line-up, like:
Christian Ronaldo, Suarez and Messi
or
Suarez, Christian Ronaldo and Messi
or
Messi, Suarez, Ronaldo
First step - simplify the variation possibility.
Next step - calculate the average price, and build the team one by one by adding player with lower salary but higher price. When reach salary limit, remove expensive one and add cheaper but with same fantasy points - and so on. Don't build the variation, value the weight of each player by combination of salary and fantasy points.
A: Does this help? It sets up the constraints and maximises points.
You could adapt to get data out of excel
http://pena.lt/y/2014/07/24/mathematically-optimising-fantasy-football-teams
14/07/24/mathematically-optimising-fantasy-football-teams
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592010",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Trying to understand of DependencyProperty Being new to WPF, and its apparently amazing ability to change, bind, enable, and otherwise manipulate. I'm trying to get a mental overview of what is happening and hope some can either confirm or correct my readings.
Before WPF, you have delegates and events. You could have a dozen controls all listening (via being registered to the event), so when the event fires, all other controls will be notified automatically and can act on however they were so coded. Such as...
From Code Behind, you would do something like
GotFocus += MyMethodToDoSomething;
Then, the signature method
private void MyMethodToDoSomething(object sender, RoutedEventArgs e)
{
.. do whatever
}
Additionally, by using standard getter / setter, the setter can call its own methods in its own class to do something every time someone tries to get or set a value
private int someValue;
public int SomeValue
{
get { this.DoSomeOtherThing();
return someValue;
}
set { this.DoAnotherThing();
someValue = value;
}
Now, there's dependency properties, and the one/two-way binding. I understand (I think) about one-way to simulate more of a read-only operation.
Anyhow, with two way binding, the dependencies automatically notify anyone "depending" on a change in either the source or target respectively, without an explicit check if something has subscribed to an event, the framework automatically handles the announcing of the change to the respective controls (target or source).
So, let me through this scenario out with an old Add/Edit Save/Cancel maintenance form.
In an older framework, if someone clicked on an add or edit button, all the data entry fields would become "enabled" with either blank data for a new record, or editing existing data. At the same time, the add/edit buttons would become disabled, but the Save/Cancel buttons would now become enabled.
Likewise when finished via Save/Cancel, it would disable all the entry fields, save/cancel, and re-enable the Add/Edit buttons.
I don't quite understand how such this type of scenario would be handled under this dependency property scenario (yet), but am I close? I also understand you can bind to almost anything, including color schemes, show/hide, fonts, etc... But I'm taking small steps on trying to really grasp this stuff.
Thanks.
A: The getter/setter stuff is a feature of regular C# properties. It isn't unique to WPF.
This one-way/two-way stuff is talking about WPF data binding, which doesn't require you to create Dependency Properties - just to use them.
Dependency properties are built into controls themselves. They let you directly reference those properties when adding instances of your control to the form. They allow your custom control to feel a bit more "native".
Generally they are used to implement a property that can use data binding. In your apps, you'll mostly just use data binding, rather than implement new hooks for it.
... if someone clicked on an add or edit button, all the data entry fields would become "enabled" with either blank data for a new record, or editing existing data. At the same time, the add/edit buttons would become disabled, but the Save/Cancel buttons would now become enabled.
Likewise when finished via Save/Cancel, it would disable all the entry fields, save/cancel, and re-enable the Add/Edit buttons.
I would accomplish what you want to accomplish with:
*
*A view model
*Data binding on the view to that view model
*Exposing ICommand on that view model (for buttons)
*INotifyPropertyChanged on the view model (for all properties)
No new dependency properties need to be created for this scenario. You'll just use existing ones to do data binding.
Here's a code sample/tutorial of doing WPF with data binding and MVVM style.
Setting up the project
I created a WPF application in the New Project wizard, and named it MyProject.
I set up my project name and namespaces to match the generally accepted scheme of things. You should set these properties in solution explorer -> project -> right click -> properties.
I also have a custom folder scheme I like to use for WPF projects:
I stuck the view in its own "View" folder for organizational purposes. This is also reflected in the namespace, since your namespaces should match your folders (namespace MyCompany.MyProject.View).
I also edited AssemblyInfo.cs, and cleaned up my assembly References and app config, but that is just some tedium that I'll leave as an exercise for the reader :)
Creating a view
Start off in the designer, and get everything looking nice. Don't add any code behind, or do any other work yet. Just play around in the designer until things look right (especially when you resize). Here's what I ended up with:
View/EntryView.xaml:
<Window x:Class="MyCompany.MyProject.View.EntryView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Entry View" Height="350" Width="525">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBox Text="Test 1" Grid.Row="0" />
<TextBox Text="Test 2" Grid.Row="1" Margin="0,6,0,0" />
<TextBox Text="Test 3" Grid.Row="2" Margin="0,6,0,0" />
<TextBox Text="Test 4" Grid.Row="3" Margin="0,6,0,0" />
</Grid>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Button Content="Edit" IsEnabled="True" Grid.Column="0"
HorizontalAlignment="Left" Width="75" />
<Button Content="Save" IsEnabled="False" Grid.Column="1"
Width="75" />
<Button Content="Cancel" IsEnabled="False" Grid.Column="2"
Width="75" Margin="6,0,0,0" />
</Grid>
</Grid>
</Window>
View/EntryView.xaml.cs:
using System.Windows;
namespace MyCompany.MyProject.View
{
public partial class EntryView : Window
{
public EntryView()
{
InitializeComponent();
}
}
}
I didn't create any Name properties on these controls. That is on purpose. I am going to use MVVM, and won't use any code behind. I'll let the designer do what it wants to do, but I won't touch any of that code.
Creating a view model
Next I will make my view model. This should be designed in a way that it services the view, but could ideally be view independent. I won't worry about that too much, but the point is you don't have to have a 1-to-1 parity of view controls and view model objects.
I try to make my views/view models make sense in a bigger app context, so I'll start purposing the view model here. We'll make this "editable form" a rolodex entry.
We'll create a helper class that we need first...
ViewModel/DelegateCommand.cs:
using System;
using System.Windows.Input;
namespace MyCompany.MyProject.ViewModel
{
public class DelegateCommand : ICommand
{
private readonly Action<object> _execute;
private readonly Func<object, bool> _canExecute;
public DelegateCommand(Action execute)
: this(execute, CanAlwaysExecute)
{
}
public DelegateCommand(Action execute, Func<bool> canExecute)
{
if (execute == null)
throw new ArgumentNullException("execute");
if (canExecute == null)
throw new ArgumentNullException("canExecute");
_execute = o => execute();
_canExecute = o => canExecute();
}
public bool CanExecute(object parameter)
{
return _canExecute(parameter);
}
public void Execute(object parameter)
{
_execute(parameter);
}
public event EventHandler CanExecuteChanged;
public void RaiseCanExecuteChanged()
{
if (CanExecuteChanged != null)
CanExecuteChanged(this, new EventArgs());
}
private static bool CanAlwaysExecute()
{
return true;
}
}
}
ViewModel/EntryViewModel.cs:
using System;
using System.ComponentModel;
using System.Windows.Input;
namespace MyCompany.MyProject.ViewModel
{
public class EntryViewModel : INotifyPropertyChanged
{
private readonly string _initialName;
private readonly string _initialEmail;
private readonly string _initialPhoneNumber;
private readonly string _initialRelationship;
private string _name;
private string _email;
private string _phoneNumber;
private string _relationship;
private bool _isInEditMode;
private readonly DelegateCommand _makeEditableOrRevertCommand;
private readonly DelegateCommand _saveCommand;
private readonly DelegateCommand _cancelCommand;
public EntryViewModel(string initialNamename, string email,
string phoneNumber, string relationship)
{
_isInEditMode = false;
_name = _initialName = initialNamename;
_email = _initialEmail = email;
_phoneNumber = _initialPhoneNumber = phoneNumber;
_relationship = _initialRelationship = relationship;
MakeEditableOrRevertCommand = _makeEditableOrRevertCommand =
new DelegateCommand(MakeEditableOrRevert, CanEditOrRevert);
SaveCommand = _saveCommand =
new DelegateCommand(Save, CanSave);
CancelCommand = _cancelCommand =
new DelegateCommand(Cancel, CanCancel);
}
public string Name
{
get { return _name; }
set
{
_name = value;
RaisePropertyChanged("Name");
}
}
public string Email
{
get { return _email; }
set
{
_email = value;
RaisePropertyChanged("Email");
}
}
public string PhoneNumber
{
get { return _phoneNumber; }
set
{
_phoneNumber = value;
RaisePropertyChanged("PhoneNumber");
}
}
public string Relationship
{
get { return _relationship; }
set
{
_relationship = value;
RaisePropertyChanged("Relationship");
}
}
public bool IsInEditMode
{
get { return _isInEditMode; }
private set
{
_isInEditMode = value;
RaisePropertyChanged("IsInEditMode");
RaisePropertyChanged("CurrentEditModeName");
_makeEditableOrRevertCommand.RaiseCanExecuteChanged();
_saveCommand.RaiseCanExecuteChanged();
_cancelCommand.RaiseCanExecuteChanged();
}
}
public string CurrentEditModeName
{
get { return IsInEditMode ? "Revert" : "Edit"; }
}
public ICommand MakeEditableOrRevertCommand { get; private set; }
public ICommand SaveCommand { get; private set; }
public ICommand CancelCommand { get; private set; }
private void MakeEditableOrRevert()
{
if (IsInEditMode)
{
// Revert
Name = _initialName;
Email = _initialEmail;
PhoneNumber = _initialPhoneNumber;
Relationship = _initialRelationship;
}
IsInEditMode = !IsInEditMode; // Toggle the setting
}
private bool CanEditOrRevert()
{
return true;
}
private void Save()
{
AssertEditMode(isInEditMode: true);
IsInEditMode = false;
// Todo: Save to file here, and trigger close...
}
private bool CanSave()
{
return IsInEditMode;
}
private void Cancel()
{
AssertEditMode(isInEditMode: true);
IsInEditMode = false;
// Todo: Trigger close form...
}
private bool CanCancel()
{
return IsInEditMode;
}
private void AssertEditMode(bool isInEditMode)
{
if (isInEditMode != IsInEditMode)
throw new InvalidOperationException();
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string propertyName)
{
if (PropertyChanged != null)
PropertyChanged(this,
new PropertyChangedEventArgs(propertyName));
}
#endregion INotifyPropertyChanged Members
}
}
As is usual for this type of workflow, there are some requirements I missed when initially creating the view. For example, I figured out that it would make sense to have a "revert" feature that undoes the changes, but keeps the dialog open. I also figured out that I could reuse the edit button for this purpose. So I made a property that I will read to get the edit button's name.
The view model contains a lot of code to do something simple, but most of it is boilerplate for hooking up the properties. This boilerplate gives you some power, though. It helps isolate you from your view, so your view can change drastically with no changes or only minor changes to the view model.
If the view model gets too big, you can start pushing it into a additional sub view models. Create them wherever makes the most sense, and return them as properties on this view model. The WPF data binding mechanism supports chaining down the data context. You'll find out about this data context a little later when we hook things up.
Hooking up the view to our view model
To hook up the view to a view model, you have to set the DataContext property on view to point to your view model.
Some people like to instantiate and specify the view model in the XAML code. While this can work, I like to keep the view and the view model independent of each other, so I make sure I use some third class to hook the two up.
Normally I'd use a dependency injection container to hook up all my code, which is a lot of work, but keeps all the parts independent. But for an app this simple, I like to use the App class to bind my stuff together. Let's go edit it:
App.xaml:
<Application x:Class="MyCompany.MyProject.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Startup="ApplicationStartup">
<Application.Resources>
</Application.Resources>
</Application>
App.xaml.cs:
using System.Windows;
namespace MyCompany.MyProject
{
public partial class App : Application
{
private void ApplicationStartup(object sender, StartupEventArgs e)
{
// Todo: Somehow load initial data...
var viewModel = new ViewModel.EntryViewModel(
"some name", "some email", "some phone number",
"some relationship"
);
var view = new View.EntryView()
{
DataContext = viewModel
};
view.Show();
}
}
}
You can now run your project, though the logic we built won't do anything. This is because our initial view is created, but it doesn't actually do any data binding.
Setting up data binding
Lets go back and edit the view to finish hooking it all up.
Editing View/EntryView.xaml:
<Window x:Class="MyCompany.MyProject.View.EntryView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Rolodex Entry"
Height="350" Width="525"
MinWidth="300" MinHeight="200">
<Grid Margin="12">
<Grid.RowDefinitions>
<RowDefinition Height="*" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid Grid.Row="0">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<TextBlock Text="Name:" Grid.Column="0" Grid.Row="0" />
<TextBox Text="{Binding Name, UpdateSourceTrigger=PropertyChanged}"
IsEnabled="{Binding IsInEditMode}" Grid.Column="1"
Grid.Row="0" Margin="6,0,0,0" />
<TextBlock Text="E-mail:" Grid.Column="0" Grid.Row="1"
Margin="0,6,0,0" />
<TextBox Text="{Binding Email, UpdateSourceTrigger=PropertyChanged}"
IsEnabled="{Binding IsInEditMode}" Grid.Column="1"
Grid.Row="1" Margin="6,6,0,0" />
<TextBlock Text="Phone Number:" Grid.Column="0" Grid.Row="2"
Margin="0,6,0,0" />
<TextBox Text="{Binding PhoneNumber, UpdateSourceTrigger=PropertyChanged}"
IsEnabled="{Binding IsInEditMode}" Grid.Column="1" Grid.Row="2"
Margin="6,6,0,0" />
<TextBlock Text="Relationship:" Grid.Column="0" Grid.Row="3"
Margin="0,6,0,0" />
<TextBox Text="{Binding Relationship, UpdateSourceTrigger=PropertyChanged}"
IsEnabled="{Binding IsInEditMode}" Grid.Column="1" Grid.Row="3"
Margin="6,6,0,0" />
</Grid>
<Grid Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Button Content="{Binding CurrentEditModeName}"
Command="{Binding MakeEditableOrRevertCommand}"
Grid.Column="0" HorizontalAlignment="Left"
Width="75" />
<Button Content="Save" Command="{Binding SaveCommand}"
Grid.Column="1" Width="75" />
<Button Content="Cancel" Command="{Binding CancelCommand}"
Grid.Column="2" Width="75" Margin="6,0,0,0" />
</Grid>
</Grid>
</Window>
I did a lot of work here. First, the static stuff:
*
*I changed the title of the form to match the Rolodex idea
*I added labels for the fields, since I now know what they apply to
*I changed the minimum width/height, since I noticed controls were getting cut off
Next the data-binding:
*
*I bound all the text fields to the appropriate properties on the view model
*I made the text fields update the view model on every keypress (UpdateSourceTrigger=PropertyChanged). This isn't necessary for this app, but could be helpful in the future. I added it to spare you from looking it up when you need it :)
*I bound the IsEnabled field of each text box to the IsInEditMode property
*I bound the buttons to their respective commands
*I bound the edit button's name (Content property) to the corresponding property on the view model
Here's the result
Now all the UI logic works, except those we left a Todo comment on. I left those unimplemented because they have to do with a specific application architecture, and I didn't want to get into that for this demo.
Also, vanilla WPF doesn't have a very clean MVVM way to close a form that I know of. You can use code-behind to do it, or you can use one of the dozens of WPF add-on libraries that provide their own cleaner way of doing it.
Dependency Properties
You may have noticed that I didn't create a single custom Dependency Property in my code. The dependency properties I used were all on existing controls (e.g. Text, Content and Command). This is how it usually works in WPF, because data binding and styling (which I didn't get into) gives you a lot of options. It lets you completely customize the look, feel, and actions of built-in controls.
In previous Windows GUI frameworks, you'd often have to subclass existing controls or create custom controls to get a custom look and feel. The only reasons to make custom controls in WPF are to combine patterns of multiple controls in a reusable way, or to create a completely new control from scratch.
E.g. if you were making an auto-complete text box that is paired with a popup control to display the values it is auto-completing from. In such a case you might want to make a custom control, with custom dependency properties (such as the auto-completion source). That way you can reuse the control throughout your application, and other applications.
If you aren't making custom controls, or making special non-UI classes that can directly instantiate and use in XAML and data bind with, you probably won't need to create dependency properties.
A: The poster has requested that I repost my comment as an answer. Happy to oblige :-)
*
*The video presentation I referred to: http://blog.lab49.com/archives/2650
*Bonus link: awesome WPF article in MSDN: http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
*And in case you didn't know about it, there's a chapter in the online documentation: http://msdn.microsoft.com/en-us/library/ms752914.aspx
Also I've found this book very helpful: http://www.amazon.com/WPF-4-Unleashed-Adam-Nathan/dp/0672331195
My own experience with WPF involves going back between a bunch of different resources as I try to get my program to work. There's so much stuff in WPF it's really hard to keep it all in your head as you are learning it.
A: A simple way of looking at them is that they are properties that point to another property.
They're actually a definition of a property, that defines the property name, type, default value, etc, but the actual value of the property is not stored with the property definition.
So you can say a Button's Enabled property is going to point to a property on a specific class, or it it is going to point to CheckBoxA.IsChecked property, or you can even say it is simply going to be pointing to a boolean value of False.
// Value points to the current DataContext object's CanSaveObject property
<Button IsEnabled="{Binding CanSaveObject}" />
// Value points to the IsChecked property of CheckBoxA
<Button IsEnabled="{Binding ElementName=CheckBoxA, Path=IsChecked}" />
// Value points to the value False
<Button IsEnabled="False" />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592013",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Got ExceptionInInitializerError when mocking constructor of a class with Powermock. How to fix it? Here is my case. I have a AbstractController class. It has a sub class Controller. In one of AbstractController's methods a new ApplicationLock is instantiated. I'd like to mock ApplicationLock when writing ut for Controller. I wrote a test case like below.
@test
public void testMethod(){
ApplicationLock mockLock=PowerMockito.mock(ApplicationLock.class);
PowerMockito.when(mockLock.tryObtain()).thenReturn(true);
PowerMockito.whenNew(ApplicationLock.class).withArguments(argThat(new IsFile()),anyString()).thenReturn(mockLock);
}
I've added necessary annotations to the test class.
@RunWith(PowerMockRunner.class)
@PrepareForTest({AbstractController.class})
But I got the following error when running this test case. That is a static initializer in AbstractController.
Caused by: java.lang.NullPointerException
at com.acompany.controller.common.AbstractController.(AbstractController.java:65)
private static final String DEFAULT_FOLDER = AbstractController.class.getProtectionDomain().getCodeSource()
.getLocation().getPath();
Full stack trace is as below.
java.lang.ExceptionInInitializerError at
java.lang.Class.forName0(Native Method) at
java.lang.Class.forName(Class.java:169) at
javassist.runtime.Desc.getClassObject(Desc.java:44) at
javassist.runtime.Desc.getClassType(Desc.java:153) at
javassist.runtime.Desc.getType(Desc.java:123) at
javassist.runtime.Desc.getType(Desc.java:79) at
com.acompany.controller.portfolio.ControllerTest.testIncrementalFail(ControllerTest.java:195)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597) at
org.junit.internal.runners.TestMethod.invoke(TestMethod.java:66) at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:307)
at
org.junit.internal.runners.MethodRoadie$2.run(MethodRoadie.java:86)
at
org.junit.internal.runners.MethodRoadie.runBeforesThenTestThenAfters(MethodRoadie.java:94)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.executeTest(PowerMockJUnit44RunnerDelegateImpl.java:294)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTestInSuper(PowerMockJUnit47RunnerDelegateImpl.java:112)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit47RunnerDelegateImpl$PowerMockJUnit47MethodRunner.executeTest(PowerMockJUnit47RunnerDelegateImpl.java:73)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$PowerMockJUnit44MethodRunner.runBeforesThenTestThenAfters(PowerMockJUnit44RunnerDelegateImpl.java:282)
at
org.junit.internal.runners.MethodRoadie.runTest(MethodRoadie.java:84)
at org.junit.internal.runners.MethodRoadie.run(MethodRoadie.java:49)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.invokeTestMethod(PowerMockJUnit44RunnerDelegateImpl.java:207)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.runMethods(PowerMockJUnit44RunnerDelegateImpl.java:146)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl$1.run(PowerMockJUnit44RunnerDelegateImpl.java:120)
at
org.junit.internal.runners.ClassRoadie.runUnprotected(ClassRoadie.java:34)
at
org.junit.internal.runners.ClassRoadie.runProtected(ClassRoadie.java:44)
at
org.powermock.modules.junit4.internal.impl.PowerMockJUnit44RunnerDelegateImpl.run(PowerMockJUnit44RunnerDelegateImpl.java:118)
at
org.powermock.modules.junit4.common.internal.impl.JUnit4TestSuiteChunkerImpl.run(JUnit4TestSuiteChunkerImpl.java:102)
at
org.powermock.modules.junit4.common.internal.impl.AbstractCommonPowerMockRunner.run(AbstractCommonPowerMockRunner.java:53)
at
org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)
at
org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at
org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.NullPointerException at
com.acompany.controller.common.AbstractController.(AbstractController.java:65)
... 35 more
A: You could use then:
@SuppressStaticInitializationFor({AbstractController.class})
And then, in your test case, set manually all static fields that need to be initialized, including the DEFAULT_FOLDER:
Whitebox.setInternalState(Controller.class, "DEFAULT_FOLDER", "abcd");
Whitebox.setInternalState(Controller.class, "OTHER_FIELD", new Object());
The method Class<?>.getProtectionDomain() depends too much on class loader used, so you probably won't get it to work in JUnit/PowerMock, which use their own.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592018",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Bitrate limitation on AVFoundation screen capture on OSX Lion I'm using AVFoundation on OSX Lion to do screen capture. Accomplished as follows:
self->screenInput = [[AVCaptureScreenInput alloc] initWithDisplayID:self->screen];
self->dataOutput = [[AVCaptureVideoDataOutput alloc] init];
self->session = [[AVCaptureSession alloc] init];
self->assetWriter = [[AVAssetWriter alloc] initWithURL:url
fileType:AVFileTypeQuickTimeMovie
error:&error];
self->writerInput = [[AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo
outputSettings:nil] retain];
self->dataOutput.videoSettings=videosettings;
- (void)captureOutput:(AVCaptureOutput *)captureOutput
didOutputSampleBuffer:(CMSampleBufferRef)sampleBuffer
fromConnection:(AVCaptureConnection *)connection
{
if(!self->startedWriting)
{
[self->assetWriter startSessionAtSourceTime:CMSampleBufferGetPresentationTimeStamp(sampleBuffer)];
self->startedWriting = YES;
}
if(self->writerInput.readyForMoreMediaData)
{
[self->writerInput appendSampleBuffer:sampleBuffer]
}
}
This results in a framerate roughly 1 Mbps -> 3 Mbps. The problem with this is that in video settings I've specified:
NSMutableDictionary * compressionSettings = [[[NSMutableDictionary alloc] initWithCapacity:1] autorelease];
[compressionSettings setObject:[NSNumber numberWithInt:512000] forKey:AVVideoAverageBitRateKey];
[videosettings setObject:compressionSettings forKey:AVVideoCompressionPropertiesKey];
are for 512K, and having a higher bitrate causes the files to be too big (we need to upload these files after all).
When I remove the line
self->dataOutput.videoSettings=videosettings;
and instead apply the video settings to the writerinput via
self->writerInput = [[AVAssetWriterInput assetWriterInputWithMediaType:AVMediaTypeVideo
outputSettings:videosettings] retain];
I get a bitrate that is too low (usually 100 Kbps => 300 Kbps). I assume this is because the encoding is taking place via software instead of hardware (it is happening after the data is returned from the AVCaptureSession).
What can I do to force the capture to go down from 1-3 Mbps and down to just 512K? If it can go higher, I can't imagine why it wouldn't be able to just cap the rate it's using.
Thanks,
-G
A: From the docs for the AVCaptureVideoDataOutput videoSettings property
Currently, the only supported key is kCVPixelBufferPixelFormatTypeKey. Supported pixel formats are
kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange, kCVPixelFormatType_420YpCbCr8BiPlanarFullRange and kCVPixelFormatType_32BGRA,
except on iPhone 3G, where the supported pixel formats are kCVPixelFormatType_422YpCbCr8 and kCVPixelFormatType_32BGRA.
Setting compression settings on this class is meaningless. This means your compression settings for AVAssetWriterInput are nil. Thus you will get whatever default rate for the device.
While there could definitely be a bug in the OS-X AVFoundaton implementation, the bitrate you are receiving could be right. For instance how much motion is there in the video? How complex is the scene? Also keep in mind that H264/AVC is not a constant bitrate codec.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Debugging/bypassing BSOD without source code Hello and good day to you.
Need a bit of assitance here:
Situation:
I have an obscure DirectX 9 application (name and application details are irrelevant to the question) that causes blue screen of death on all nvidia cards (GeForce 8400GS and up) since certain driver version. I believe that the problem is indirectly caused by DirectX 9 call or a flag that triggers driver bug.
Goal:
I'd like to track down offending flag/function call (for fun, this isn't my job/homework) and bypass error condition by writing proxy dll. I already have a finished proxy dll that provides wrappers for IDirect3D9, IDirect3DDevice9, IDirect3DVertexBuffer9 and IDirect3DIndexBuffer9 and provides basic logging/tracing of Direct3D calls. However, I can't pinpoint function which causes crash.
Problems:
*
*No source code or technical support is available. There will be no assitance, and nobody else will fix the problem.
*Memory dump produced by kernel wasn't helpful - apparently an access violation happens within nv4_disp.dll, but I can't use stacktrace to go to IDirect3DDevice9 method call, plus there's a chance that bug happens asynchronously.
*(Main problem) Because of large number of Direct3D9Device method calls, I can't reliably log them into file or over network:
*
*Logging into file causes significant slowdown even without flushing, and because of that all last contents of the log are lost when system BSODs.
*Logging over network (using UDP and WINSOck's sendto)also causes significant slowdown and must not be done asynchronously (asynchronous packets are lost on BSOD), plus packets (the ones around the crash) are sometimes lost even when sent synchronously.
*When application is "slowed" down by logging routines, BSOD is less likely to happen, which makes tracking it down harder.
Question:
I normally don't write drivers, and don't do this level of debugging, so I have impression that I'm missing something important there's a more trivial way to track down the problem than writing IDirect3DDevice9 proxy dll with custom logging mechanism. What is it? What is the standard way of diagnosing/handling/fixing problem like this (no source code, COM interface method triggers BSOD)?
Minidump analysis(WinDBG):
Loading User Symbols
Loading unloaded module list
...........
Unable to load image nv4_disp.dll, Win32 error 0n2
*** WARNING: Unable to verify timestamp for nv4_disp.dll
*** ERROR: Module load completed but symbols could not be loaded for nv4_disp.dll
*******************************************************************************
* *
* Bugcheck Analysis *
* *
*******************************************************************************
Use !analyze -v to get detailed debugging information.
BugCheck 1000008E, {c0000005, bd0a2fd0, b0562b40, 0}
Probably caused by : nv4_disp.dll ( nv4_disp+90fd0 )
Followup: MachineOwner
---------
0: kd> !analyze -v
*******************************************************************************
* *
* Bugcheck Analysis *
* *
*******************************************************************************
KERNEL_MODE_EXCEPTION_NOT_HANDLED_M (1000008e)
This is a very common bugcheck. Usually the exception address pinpoints
the driver/function that caused the problem. Always note this address
as well as the link date of the driver/image that contains this address.
Some common problems are exception code 0x80000003. This means a hard
coded breakpoint or assertion was hit, but this system was booted
/NODEBUG. This is not supposed to happen as developers should never have
hardcoded breakpoints in retail code, but ...
If this happens, make sure a debugger gets connected, and the
system is booted /DEBUG. This will let us see why this breakpoint is
happening.
Arguments:
Arg1: c0000005, The exception code that was not handled
Arg2: bd0a2fd0, The address that the exception occurred at
Arg3: b0562b40, Trap Frame
Arg4: 00000000
Debugging Details:
------------------
EXCEPTION_CODE: (NTSTATUS) 0xc0000005 - The instruction at "0x%08lx" referenced memory at "0x%08lx". The memory could not be "%s".
FAULTING_IP:
nv4_disp+90fd0
bd0a2fd0 39b8f8000000 cmp dword ptr [eax+0F8h],edi
TRAP_FRAME: b0562b40 -- (.trap 0xffffffffb0562b40)
ErrCode = 00000000
eax=00000808 ebx=e37f8200 ecx=e4ae1c68 edx=e37f8328 esi=e37f8400 edi=00000000
eip=bd0a2fd0 esp=b0562bb4 ebp=e37e09c0 iopl=0 nv up ei pl nz na po nc
cs=0008 ss=0010 ds=0023 es=0023 fs=0030 gs=0000 efl=00010202
nv4_disp+0x90fd0:
bd0a2fd0 39b8f8000000 cmp dword ptr [eax+0F8h],edi ds:0023:00000900=????????
Resetting default scope
CUSTOMER_CRASH_COUNT: 3
DEFAULT_BUCKET_ID: DRIVER_FAULT
BUGCHECK_STR: 0x8E
LAST_CONTROL_TRANSFER: from bd0a2e33 to bd0a2fd0
STACK_TEXT:
WARNING: Stack unwind information not available. Following frames may be wrong.
b0562bc4 bd0a2e33 e37f8200 e37f8200 e4ae1c68 nv4_disp+0x90fd0
b0562c3c bf8edd6b b0562cfc e2601714 e4ae1c58 nv4_disp+0x90e33
b0562c74 bd009530 b0562cfc bf8ede06 e2601714 win32k!WatchdogDdDestroySurface+0x38
b0562d30 bd00b3a4 e2601008 e4ae1c58 b0562d50 dxg!vDdDisableSurfaceObject+0x294
b0562d54 8054161c e2601008 00000001 0012c518 dxg!DxDdDestroySurface+0x42
b0562d54 7c90e4f4 e2601008 00000001 0012c518 nt!KiFastCallEntry+0xfc
0012c518 00000000 00000000 00000000 00000000 0x7c90e4f4
STACK_COMMAND: kb
FOLLOWUP_IP:
nv4_disp+90fd0
bd0a2fd0 39b8f8000000 cmp dword ptr [eax+0F8h],edi
SYMBOL_STACK_INDEX: 0
SYMBOL_NAME: nv4_disp+90fd0
FOLLOWUP_NAME: MachineOwner
MODULE_NAME: nv4_disp
IMAGE_NAME: nv4_disp.dll
DEBUG_FLR_IMAGE_TIMESTAMP: 4e390d56
FAILURE_BUCKET_ID: 0x8E_nv4_disp+90fd0
BUCKET_ID: 0x8E_nv4_disp+90fd0
Followup: MachineOwner
A: nv4_disp+90fd0
bd0a2fd0 39b8f8000000 cmp dword ptr [eax+0F8h],edi
This is the important part. Looking at this, it is most probable that eax is invalid, hence attempting to access an invalid memory address.
What you need to do is load nv4_disp.dll into IDA (you can get a free version), check the image base that IDA loads nv4_disp at and hit 'g' to goto address, try adding 90fd0 to the image base IDA is using, and it should take you directly to the offending instruction (depending on section structure).
From here you can analyze the control flow, and how eax is set and used. If you have a good kernel level debugger you can set a breakpoint on this address and try and get it to hit.
Analysing the function, you should attempt to figure out what the function does, what eax is meant to be pointing to at that point, what its actually pointing to, and why. This is the hard part and is a great part of the difficulty and skill of reverse engineering.
A: Found a solution.
Problem:
Logging is unreliable since messages (when dumped to file) disappear during bsod, packets are sometimes lost when logging over network, and there's slowdown due to logging.
Solution:
Instead of logging to file or over network, configure system to produce full physical memory dump on BSOD and log all messages into any memory buffer. It'll be faster. Once system crashed, it'll dump entire memory into file, and it'll be possible to either view contents of log-file buffer using WinDBG's dt (if you have debug symbols) command, or you'll be able to search and locate logfile stored in memory using "memory" view.
I used circular buffer of std::strings to store messages and separate array of const char* to make things easier to read in WinDBG, but you could simply create huge array of char and store all messages within it in plaintext.
Details:
Entire process on winxp:
*
*Ensure that minimum page file size is equal or larger than total amount of RAM + 1 megabytes. (Right Click "My Computer"->Properties->Advanced->Performance->Advanced->Change)
*Configure system to produce complete memory dump on BSOD (RIght click "My Computer'->Properties->Advanced->Startup and Recovery->Settings->Write Debugging Information . Select "Complete memory dump" and specify path you want).
*Ensure that disk (where the file will be written) has required amount of free space (total amount of RAM on your system.
*Build app/dll (the one that does logging) with debug symbol, and Trigger BSOD.
*Wait till memory dump is finished, reboot. Feel free to swear at driver developer while system writes memory dump and reboots.
*Copy MEMORY.DMP system produced to a safe place, so you won't lose everything if system crashes again.
*Launch windbg.
*Open Memory Dump (File->Open Crash Dump).
*If you want to see what happened, use !analyze -v command.
*Access memory buffer that stores logged messages using one of those methods:
*
*To see contents of global variable, use dt module!variable where "module" is name of your library (without *.dll), and "variable" is name of variable. You can use wildcards. You can use address without module!variable
*To see contents of one field of the global variable (if global variable is a struct), use dt module!variable field where "field" is variable member.
*To see more details about varaible (content of arrays and substructures) use dt -b module!variable field or dt -b module!variable
*If you don't have symbols, you'll need to search for your "logfile" using memory window.
At this point you'll be able to see contents of log that were stored in memory, plus you'll have snapshot of the entire system at the moment when it crashed.
Also...
*
*To see info about process that crashed the system, use !process.
*To see loaded modules use lm
*For info about thread there's !thread id where id is hexadecimal id you saw in !process output.
A: It looks like the crash may either be caused by a bad pointer, or heap corruption. You can tell this because the crash occurs in a memory-freeing function (DxDdDestroySurface). Destroying surfaces is something that you absolutely need to do - you can't just stub this out, the surface will still get freed when the program exits, and if you disable it inside the kernel, you'll run out of on-card memory very quickly and crash that way, as well.
You can try to figure out what sequence of events leads up to this heap corruption, but there's no silver bullet here - as fileoffset suggested, you'll need to actually reverse engineer the driver to see why this happens (it may help to compare drivers before and after the offending driver version as well!)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592025",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Node.js + socket.io + node-amqp and queue binginds when "re" connecting thru socket.io I have one scenario which is very close to this sample:
One main screen:
*
*this screen (client side) will connect to the socket.io server thru server:9090/scope (io.connect("http://server:9090/scope)) and will send one event "userBindOk" (socket.emit("userBindOk", message)) to the socket.io server;
*the server receives the connection and the "userBindOk". At this moment, the server should get the active connection to rabbitmq server and bind the queue to the respective user that just connected to the application thru socket.io. sample:
socket.on("connection", function(client){
//client id is 1234
// bind rabbitmq exchange, queue, and:
queue.subscribe(//receive callback);
})
*So far, no problem - I can send/receive messages thru socket.io without problems.
*BUT, If I refresh the page, all those steps will be done again. As consequence, the binding to the queue will occur, but this time related to another session of the socket.io client. This means that if I send a message to the queue which is related to the first socket.io session (before the page refresh), that bind should (I think) receive the message and send it to a invalid socket.io client (page refresh = new client.id on the socket.io context). I can prove this behaviour because every time I refresh the page I need to send x times more messages. For instance: I`ve connected for the first time: - so, 1 message - one screen update; refresh the page: I need to send 2 messages to the queue and only the second message will be received from the "actual" socket.io client session - this behaviour will occur as many as I refresh the page (20 page refreshs, 20 messages to be sent to a queue and the server socket.io "last" client will send the message to the client socket.io to render into the screen).
The solutions I believe are:
*
*Find a way to "unbind" the queue when disconnecting from the socket.io server - I didn`t see this option at the node-amqp api yet (waiting for it :D)
*find a way to reconnect the socket.io client using the same client.id. This way I can identify the client that is coming and apply some logic to cache the socket.
Any ideas? I tried to be very clear... But, as you know, it`s not so eaey to expose your problem when trying to clarify something that is very specific to some context...
tks
A: I solved it like this:
I used to declare the rabbitMq queue as durable=true,autoDelete=false,exclusive=false and in my app there was 1 queue/user and 1 exchange(type=direct) with the routing_key name=queueName, my app also used the queue for other client diffent to browsers like android app or iphone app as push fallback, so i use to crear 1 queue for earch user.
The solution to this problem was to change my rabbitMQ queue and exchange declaration. Now i declare the exchange/user as fanout and autoDelete=True, and the user is going to have N queues with durable=true, autoDelete=true, exclusive=true (No. queue = No. clients) and all the queues are bind to the user-exchange(multicast).
NOTE: my app is wirten in django, and i use node+socket+amqp to be able to comunicate with the browser using web.scokets, so i use node-restler to query my app api to get the user-queue info.
thats the rabbitMQ side, for the node+amqp+socket i did this:
server-side:
*
*onConnect: the declaration of the user exchange as fanout, autoDelete, durable. then declaration of the queue as durable, autodelete and exclusive, then the queue.bind to the user-exchange and finaly the queue.subscribe and the socket.disconnect will destroy the queue so there are going to exist queue as client connected the app and this solve the problem of the refresh and allow the user to have more than 1 window-tab with the app:
Server-side:
/*
* unCaught exception handler
*/
process.on('uncaughtException', function (err) {
sys.p('Caught exception: ' + err);
global.connection.end();
});
/*
* Requiere libraries
*/
global.sys = require('sys');
global.amqp = require('amqp');
var rest = require('restler');
var io = require('socket.io').listen(8080);
/*
* Module global variables
*/
global.amqpReady = 0;
/*
* RabbitMQ connection
*/
global.connection = global.amqp.createConnection({
host: host,
login: adminuser,
password: adminpassword,
vhost: vhost
});
global.connection.addListener('ready',
function () {
sys.p("RabbitMQ connection stablished");
global.amqpReady = 1;
}
);
/*
* Web-Socket declaration
*/
io.sockets.on('connection', function (socket) {
socket.on('message', function (data) {
sys.p(data);
try{
var message = JSON.parse(data);
}catch(error){
socket.emit("message", JSON.stringify({"error": "invalid_params", "code": 400}));
var message = {};
}
var message = JSON.parse(data);
if(message.token != undefined) {
rest.get("http://dev.kinkajougames.com/api/push",
{headers:
{
"x-geochat-auth-token": message.token
}
}).on('complete',
function(data) {
a = data;
}).on('success',
function (data){
sys.p(data);
try{
sys.p("---- creating exchange");
socket.exchange = global.connection.exchange(data.data.bind, {type: 'fanout', durable: true, autoDelete: true});
sys.p("---- declarando queue");
socket.q = global.connection.queue(data.data.queue, {durable: true, autoDelete: true, exclusive: false},
function (){
sys.p("---- bind queue to exchange");
//socket.q.bind(socket.exchange, "*");
socket.q.bind(socket.exchange, "*");
sys.p("---- subscribing queue exchange");
socket.q.subscribe(function (message) {
socket.emit("message", message.data.toString());
});
}
);
}catch(err){
sys.p("Imposible to connection to rabbitMQ-server");
}
}).on('error', function (data){
a = {
data: data,
};
}).on('400', function() {
socket.emit("message", JSON.stringify({"error": "connection_error", "code": 400}));
}).on('401', function() {
socket.emit("message", JSON.stringify({"error": "invalid_token", "code": 401}));
});
}
else {
socket.emit("message", JSON.stringify({"error": "invalid_token", "code": 401}));
}
});
socket.on('disconnect', function () {
socket.q.destroy();
sys.p("closing socket");
});
});
client-side:
*
*The socket intance with options 'force new connection'=true and 'sync disconnect on unload'= false.
*The client side use the onbeforeunload and onunload windows object events to send socket.disconnect
*The client on socket.connect event send the user token to node.
*proces message from socket
var socket;
function webSocket(){
//var socket = new io.Socket();
socket = io.connect("ws.dev.kinkajougames.com", {'force new connection':true, 'sync disconnect on unload': false});
//socket.connect();
onSocketConnect = function(){
alert('Connected');
socket.send(JSON.stringify({
token: Get_Cookie('liveScoopToken')
}));
};
socket.on('connect', onSocketConnect);
socket.on('message', function(data){
message = JSON.parse(data);
if (message.action == "chat") {
if (idList[message.data.sender] != undefined) {
chatboxManager.dispatch(message.data.sender, {
first_name: message.data.sender
}, message.data.message);
}
else {
var username = message.data.sender;
Data.Collections.Chats.add({
id: username,
title: username,
user: username,
desc: "Chat",
first_name: username,
last_name: ""
});
idList[message.data.sender] = message.data.sender;
chatboxManager.addBox(message.data.sender, {
title: username,
user: username,
desc: "Chat",
first_name: username,
last_name: "",
boxClosed: function(id){
alert("closing");
}
});
chatboxManager.dispatch(message.data.sender, {
first_name: message.data.sender
}, message.data.message);
}
}
});
}
webSocket();
window.onbeforeunload = function() {
return "You have made unsaved changes. Would you still like to leave this page?";
}
window.onunload = function (){
socket.disconnect();
}
And that's it, so no more round-robing of the message.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592030",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to display the same file over the browser even if the file has been changed on the server? I am uploading a file(Image) on the server, and saving it with one unique name. Now previewing it on the browser where file fetched from the server.
Now, I changed the file(image), but save with that previous unique name only. But, while previewing it, browser is showing previous file.
I figured it out as a cookie problem. So after deleting cookie from the browser manually, I were able to see the new file.
A: It is a caching issue, not cookie. You might have cleared your browser cache as well when you cleared your cookie, so the new image appeared.
You might want to check your server configuration for caching expiration header.
If you don't know how to change it (I can't show you how because it depends on your server environment), pressing Ctrl + F5 on your browser to perform a no-cache refresh might help you see your new image right away.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Fix width for table with Display Tag I want to fix the table width using Display Tag.
.displayTable table {
border: 1px solid #666;
width: 100%;
margin: 20px 0 20px 0 !important;
}
.displayTable th, .displayTable td {
padding: 2px 4px 2px 4px !important;
text-align: left;
vertical-align: top;
width: 100%
}
.displayTable thead tr {
background-color: #9999CC;
}
.displayTable th.sorted {
background-color: #9999CC;
}
.displayTable th a,.displayTable th a:visited {
color: black;
}
.displayTable th a:hover {
text-decoration: underline;
color: black;
}
.displayTable th.sorted a,.displayTable th.sortable a {
background-position: right;
display: block;
width: 100%;
}
.displayTable th.sortable a {
background: url(../img/arrow_off.png) no-repeat right center ;
}
.displayTable th.order1 a {
background: url(../img/arrow_down.png) no-repeat right center ;
}
.displayTable th.order2 a {
background: url(../img/arrow_up.png) no-repeat right center;
}
.displayTable tr.odd {
background-color: #fff
}
.displayTable tr.tableRowEven,.displayTable tr.even {
background-color: #fff
}
.displayTable div.exportlinks {
background-color: #eee;
border: 1px dotted #999;
padding: 2px 4px 2px 4px;
margin: 2px 0 10px 0;
width: 79%;
}
.displayTable span.export {
padding: 0 4px 1px 20px;
display: inline;
display: inline-block;
cursor: pointer;
}
.displayTable span.excel {
background-image: url(../img/ico_file_excel.png);
}
.displayTable span.csv {
background-image: url(../img/ico_file_csv.png);
}
.displayTable span.xml {
background-image: url(../img/ico_file_xml.png);
}
.displayTable span.pdf {
background-image: url(../img/ico_file_pdf.png);
}
.displayTable span.rtf {
background-image: url(../img/ico_file_rtf.png);
}
.displayTable span.pagebanner {
background-color: #eee;
border: 1px dotted #999;
padding: 2px 4px 2px 4px;
width: 79%;
margin-top: 10px;
display: block;
border-bottom: none;
}
.displayTable span.pagelinks {
background-color: #eee;
border: 1px dotted #999;
padding: 2px 4px 2px 4px;
width: 79%;
display: block;
border-top: none;
margin-bottom: -5px;
}
Depends on the data loaded, the table width varies. So, I want to make it look better by fixing the width of table. But I can't. How can I make it to fix the table width?
I try to wrap the Display with Div and set the css class of Div too. But It still doesn't work (for both display:table-cell or display:inline-block;. Thanks.
.commonList{
overflow: hidden;
background: #c0c0c0;
display: table-cell
text-align: center;
width: 100%;
height: 100%;
}
Edited: When I try to wrap the display table with Div of the above css setting, table width become 100% . but as each of the column of table has various width, it becomes so ugly because the first column becomes so wide (which only display id ,1 ,2 ,3 etc) And even my display tag pagination gone. How can I solve it? Thanks.
A: .displayTable table {
table-layout:fixed;
}
Specify table layout as fixed and that will solve ur problem
A: Here is my solution. for each columns, specify a certain class and use in Display Tag.
.displayTable {
border: 1px solid #666;
width: 100%;
margin: 20px 0 20px 0 !important;
}
.colId{
width: 2%;
}
<display:column class="colId">
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592034",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Web Deploy Error with Azure I'm trying to deploy my web app to Azure using this method, but periodically, i get this error. Any ideas? I rebooted the instance, still happens.
Start Web Deploy Publish the Application/package to https://xxx.cloudapp.net:8172/MsDeploy.axd?site=myapp.Web_IN_0_myapp.Web ...
Updating setAcl (myapp.Web_IN_0_myapp.Web).
Updating setAcl (myapp.Web_IN_0_myapp.Web).
Updating filePath (myapp.Web_IN_0_myapp.Web\bin\myapp.Web.dll).
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets(3847,5): Warning : An error was encountered when processing operation 'Create File' on 'myapp.Web.dll'.
Retrying operation 'Update' on object filePath (myapp.Web_IN_0_myapp.Web\bin\myapp.Web.dll). Attempt 1 of 2.
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets(3847,5): Warning : An error was encountered when processing operation 'Create File' on 'myapp.Web.dll'.
Retrying operation 'Update' on object filePath (myapp.Web_IN_0_myapp.Web\bin\myapp.Web.dll). Attempt 2 of 2.
C:\Program Files (x86)\MSBuild\Microsoft\VisualStudio\v10.0\Web\Microsoft.Web.Publishing.targets(3847,5): Error : Web deployment task failed.((9/28/2011 8:00:56 PM) An error occurred when the request was processed on the remote computer.)
(9/28/2011 8:00:56 PM) An error occurred when the request was processed on the remote computer.
An error was encountered when processing operation 'Create File' on 'myapp.Web.dll'.
The error code was 0x80070020.
The process cannot access 'E:\approot\bin\myapp.Web.dll' because it is being used by another process.
Publish failed to deploy.
========== Build: 3 succeeded or up-to-date, 0 failed, 0 skipped ==========
========== Publish: 0 succeeded, 1 failed, 0 skipped ==========
A: The answer is to create a bootstrap csproj for your web role, that does nothing. This will be the DLL that gets locked by WaIISHost.
Then create the real web projects as separate sites using the option in the csdef file. Once you've done this, you can deploy any of your sites using web deploy and they will work, as long as they have no reference to your bootstrap dll (since they won't copy that file)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592043",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How Do I lazily load DataTypes other than Lists in Haskell I'm starting to understand the power of Haskell and how lazy loading can be exploited in ways such as
main = do
s <- getContents
let r = map processIt (lines s)
putStr (unlines r)
But the trouble i'm having is extending this kind of "Say whats in the data structure up front but get it when you need it" functionality for other datatypes.
For instance I have a graph type.
type Key = String
data Node = Node { key :: Key, links :: [Node] }
I want to write pure code that acts on this graph (Strait forward searching algorithms) no matter how it is built but I want the Nodes to lazily fill themselves when I get to them.
I think I need a way to specify up front what is in the graph and how to fill it (Some sort of recursive definition) but I'm having trouble seeing how.
Something like
loadGraph :: Key -> Node
loadGraph k =
let (key,edges) = getNodeAndEdgesFromInternetOrDatabase k in
Node key (map loadGraph edges)
I feel like this is close but I'm not quite sure how to do it. Help and Tips would be appreciated. (especially things like the type of getNodeAndEdgesFromInternetOrDatabase)
A: Lazy IO is generally implemented using unsafeInterleaveIO, which delays the side effects of an IO action until its result is demanded.
For your example, it would go something like this.
loadGraph :: Key -> IO Node
loadGraph k = unsafeInterleaveIO $ do
(key, edges) <- getNodeAndEdgesFromInternetOrDatabase k
edges' <- mapM loadGraph edges
return (Node key edges')
Since unsafeInterleaveIO is wrapping every call to loadGraph, this will only load that subgraph when you try evaluating it.
Lazy IO is frowned upon by some, as it makes it difficult to reason about the order in which the side effects happen. However, I think for your application it might be suitable, as long as you're careful in how you implement getNodeAndEdgesFromInternetOrDatabase.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592044",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: understanding effect of jquery statement I was looking for an easy way to get the contents of a jquery element and came across this page: http://jquery-howto.blogspot.com/2009/02/how-to-get-full-html-string-including.html
It has the following code
var html = $('<div>').append($('#top').clone()).remove().html();
Their explanation is as follows:
1) Cloning selected div
2) Creating a new div DOM object and appending created clone of the div
3) Then getting the contents of wrapped div (which would give us all HTML)
4) Finally removing the created DOM object, so it does not clutter our DOM tree.
My question are as follows:
1) it looks like the first thing this does is create a new div that is not attached to the dom, so why does it need to have the "remove" call?
2) I understand why it doesn't come up for this example, but in general is there much difference between doing
A: $('<div>').append('<span>foobar</span>')
B: $('<div><span>foobar</span></div>)
A: I'm not a jQuery expert, but after messing with WebKit's Web Inspector with the code you mentioned, it seems that you're right: remove() isn't necessary as the returned variable isn't added to the DOM and doesn't even seem to be a jQuery object.
As for part 2), the only difference I would think is part A is creating an element and using a DOM innerHTML and appendChild call, whereas part B is just creating an element and doing an innerHTML call.. haven't looked at the jQuery source but that's my guess. Performance-wise it doesn't make a difference with small strings as those, but I prefer the readability of A.
A: In order, it does this:
*
*Create a new empty DIV object (not in the DOM yet)
*Find the "#top" object in your page
*Clone that "#top" object.
*Append this clone to the previously created DIV object
*Remove the whole DIV object from the DOM and clean up any jQuery related data to any of the objects
*Get the innerHTML of the DIV object
The one thing that the .remove() does here is clean up any jQuery data associated with any objects in the tree that wouldn't otherwise happen at this point.
In your examples A and B, there is technically not supposed to be a difference between the two. In practice, I've found a few bugs in older versions of IE with option B. jQuery seems to follow a code path involving document fragments and I've seen some problems with that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Automatically filling in 0 and 0% in Excel blank cells I am trying to automatically enter 0 and 0% values in blank cells in Excel. I have a report in Excel that gets automatically filled up from SAS. After I save this report, I want the blank cells get automatically filled as 0 in numeric columns and 0% in percent columns.
What would the macro or VBA code be for that?
A: If the cells are truly blank (ie empty) then there are two ways to fill the cells immediately using SpecialCells, either manually, or with quick code avoiding loops.
David Mcritchie has written this up in detail here.
manual route
*
*Make a selection
*PressF5 ... Special .. Goto blanks
*in the formula bar add 0
*then press Ctrl + Enter
code route
Sub Quickfull()
'reset usedrange
ActiveSheet.UsedRange
On Error Resume Next
ActiveSheet.Cells.SpecialCells(xlBlanks).Value = 0
End Sub
A: If you just want to add 0 to a blank cell, there are several ways to do that - here's one using range A1:D10 as an example. Note that if a cell is formatted as percentage, the "%" is automatically appended to the 0. :
Sub test()
Dim cell As Range
For Each cell In Range("A1:D10")
If Len(cell.Value) = 0 Then
cell.Value = 0
End If
Next
End Sub
Please note that if you are doing this on a large range of cells (actually it's good practice to do this all the time), you want to make sure you add Application.ScreenUpdating = False at the start of the code and Application.ScreenUpdating = True at the end. That will make it run much faster.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Am I Using JDBC Connection Pooling? I am trying to determine if I am actually using JDBC connection pooling. After doing some research, the implementation almost seems too easy. Easier than a regular connection in fact so i'd like to verify.
Here is my connection class:
public class DatabaseConnection {
Connection conn = null;
public Connection getConnection() {
BasicDataSource bds = new BasicDataSource();
bds.setDriverClassName("com.mysql.jdbc.Driver");
bds.setUrl("jdbc:mysql://localhost:3306/data");
bds.setUsername("USERNAME");
bds.setPassword("PASSWORD");
try{
System.out.println("Attempting Database Connection");
conn = bds.getConnection();
System.out.println("Connected Successfully");
}catch(SQLException e){
System.out.println("Caught SQL Exception: " + e);
}
return conn;
}
public void closeConnection() throws SQLException {
conn.close();
}
}
Is this true connection pooling? I am using the connection in another class as so:
//Check data against database.
DatabaseConnection dbConn = new DatabaseConnection();
Connection conn;
ResultSet rs;
PreparedStatement prepStmt;
//Query database and check username/pass against table.
try{
conn = dbConn.getConnection();
String sql = "SELECT * FROM users WHERE username=? AND password=?";
prepStmt = conn.prepareStatement(sql);
prepStmt.setString(1, user.getUsername());
prepStmt.setString(2, user.getPassword());
rs = prepStmt.executeQuery();
if(rs.next()){ //Found Match.
do{
out.println("UserName = " + rs.getObject("username") + " Password = " + rs.getObject("password"));
out.println("<br>");
} while(rs.next());
} else {
out.println("Sorry, you are not in my database."); //No Match.
}
dbConn.closeConnection(); //Close db connection.
}catch(SQLException e){
System.out.println("Caught SQL Exception: " + e);
}
A: Assuming that it's the BasicDataSource is from DBCP, then yes, you are using a connection pool. However, you're recreating another connection pool on every connection acquirement. You are not really pooling connections from the same pool. You need to create the connection pool only once on application's startup and get every connection from it. You should also not hold the connection as an instance variable. You should also close the connection, statement and resultset to ensure that the resources are properly closed, also in case of exceptions. Java 7's try-with-resources statement is helpful in this, it will auto-close the resources when the try block is finished.
Here's a minor rewrite:
public final class Database {
private static final BasicDataSource dataSource = new BasicDataSource();
static {
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/data");
dataSource.setUsername("USERNAME");
dataSource.setPassword("PASSWORD");
}
private Database() {
//
}
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
}
(this can if necessary be refactored as an abstract factory to improve pluggability)
and
private static final String SQL_EXIST = "SELECT * FROM users WHERE username=? AND password=?";
public boolean exist(User user) throws SQLException {
boolean exist = false;
try (
Connection connection = Database.getConnection();
PreparedStatement statement = connection.prepareStatement(SQL_EXIST);
) {
statement.setString(1, user.getUsername());
statement.setString(2, user.getPassword());
try (ResultSet resultSet = preparedStatement.executeQuery()) {
exist = resultSet.next();
}
}
return exist;
}
which is to be used as follows:
try {
if (!userDAO.exist(username, password)) {
request.setAttribute("message", "Unknown login. Try again.");
request.getRequestDispatcher("/WEB-INF/login.jsp").forward(request, response);
} else {
request.getSession().setAttribute("user", username);
response.sendRedirect("userhome");
}
} catch (SQLException e) {
throw new ServletException("DB error", e);
}
In a real Java EE environement you should however delegate the creation of the DataSource to the container / application server and obtain it from JNDI. In case of Tomcat, see also for example this document: http://tomcat.apache.org/tomcat-6.0-doc/jndi-resources-howto.html
A: Doesn't seem like it's pooled. You should store the DataSource in DatabaseConnection instead of creating a new one with each getConnection() call. getConnection() should return datasource.getConnection().
A: Looks like a DBCP usage. If so, then yes. It's already pooled. And here is the default pool property value of the DBCP.
/**
* The default cap on the number of "sleeping" instances in the pool.
* @see #getMaxIdle
* @see #setMaxIdle
*/
public static final int DEFAULT_MAX_IDLE = 8;
/**
* The default minimum number of "sleeping" instances in the pool
* before before the evictor thread (if active) spawns new objects.
* @see #getMinIdle
* @see #setMinIdle
*/
public static final int DEFAULT_MIN_IDLE = 0;
/**
* The default cap on the total number of active instances from the pool.
* @see #getMaxActive
*/
public static final int DEFAULT_MAX_ACTIVE = 8;
A: As a follow up to BalusC's solution, below is an implementation that I can be used within an application that requires more than one connection, or in a common library that would not know the connection properties in advance...
import org.apache.commons.dbcp.BasicDataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.concurrent.ConcurrentHashMap;
public final class Database {
private static final ConcurrentHashMap<String, BasicDataSource> dataSources = new ConcurrentHashMap();
private Database() {
//
}
public static Connection getConnection(String connectionString, String username, String password) throws SQLException {
BasicDataSource dataSource;
if (dataSources.containsKey(connectionString)) {
dataSource = dataSources.get(connectionString);
} else {
dataSource = new BasicDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl(connectionString);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSources.put(connectionString, dataSource);
}
return dataSource.getConnection();
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "33"
}
|
Q: How to build apple's opensource libc? I'm trying to build apple's opensource libc (from http://www.opensource.apple.com/source/Libc/Libc-763.11/) on my OS X 10.6.8 laptop. This is in an attempt to essentially get a locally generated replica of /usr/lib/libSystem.B.dylib, which I intend to experiment on further.
I see a couple basic roadblocks though (unless, obviously, I'm missing something basic):
*
*No instructions on how to do the build. There are a couple of Makefiles in the URL I reference above, but they fail to build when I try to do straightforward makes:
$make -f Makefile
Makefile:14: *** missing separator. Stop.
*
*I suspect the source available for download is incomplete. Not incomplete in the sense that Apple isn't revealing all of the changes, but incomplete in the sense that there are source files that were (presumably) not modified by Apple, so isn't included in the collection. For example, I don't see the implementation of the "open" call (which, in the gnu libc hierarchy, is available at io/open.c)
The closest reference I could find after some googling was this: http://www.projectosx.com/forum/index.php?showtopic=1922&st=0&p=12457&#entry12457 but it still isn't close enough for my taste!
Any pointers?
Thanks!
A: Only some general pointers (although some links are discussing older OSX versions):
*
*http://darwinbuild.macosforge.org/trac/ticket/6
*http://sources.gentoo.org/cgi-bin/viewvc.cgi/gentoo-projects/darwin/overlay/sys-libs/libc-darwin/libc-darwin-391.ebuild?view=markup&sortby=log
*http://althenia.net/wiki/darwin#standard_library_libc
*http://dev.gentoo.org/~vapier/CROSS-COMPILE-GUTS
*http://www.raccoonfink.com/fink/darwin-cross/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: is there limit on concurrent connection number when browser downloading html resources? Generally, in order to speed up overwhole loading, browser would open serval concurrent connection to download the resource files parallelly.
I want to know, for a certain browser, is there a limit on the concurrent connection number?
A: Since you don't provide much detail only some general pointers:
The HTTP standard defines a connection limit per client<->server.
In Windows for example there is a registry setting which can be used to change that... Not all browsers/browsers versions and/or OS/OS versions implement the standard-defined limit(s) and/or take the registry setting into account...
A: It's browser dependent.
For example,
FireFox has a default of 30 global max, and 15 per server, which can be increased to 65535.
FAQs:_About:config_Entries">http://kb.mozillazine.org/Firefox_:FAQs:_About:config_Entries
And apparently Chrome's limits are lower (6) with no ability to configure.
Google for more information
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jquery change text on div I need to change only the text inside the div, where there is other elements inside it. I tried the text method but it changed the whole content of the div.
Example div:
<div class="mydiv">
MY TEXT HERE
<ul>
<li>BLAH</li>
<li>BLAH</li>
</ul>
</div>
This is what I have tried for now: $(".mydiv").text("MY NEW TEXT");
A: $.fn.extend({
text2: function(t){
return this.each(function(a,b){
$(b).contents().map(function(c,d){
return (d.nodeType === 3 ? d : null);
}).get(0).data = t;
});
}
});
There's my solution. Only effects the first text node found within the selector, then replaces it with the supplied text. Using this, $('.mydiv').text2('MY NEW TEXT'); should work flawlessly.
A: Put the text of the div into another element, then select and replace the element with jQuery.
$('.mydiv div.text').text("MY NEW TEXT")
<div class="mydiv">
<div class="text">MY TEXT HERE</div>
<ul>
<li>BLAH</li>
<li>BLAH</li>
</ul>
</div>
A: Just use the .html() method:
$(".mydiv").html("MY NEW TEXT");
Demo: http://jsfiddle.net/andresilich/mtH27/
A: Try this for that particular situation: http://jsfiddle.net/mtH27/10/
$(".mydiv")[0].firstChild.nodeValue = "Is this what you want?"
A: This method is easier: instead of trying to work with text node manipulation, remove all tags from the element, replace the inner text, and append the tags:
http://jsfiddle.net/NFEgE/1/
This will get a lot more complicated if you have multiple text nodes to worry about.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592074",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: ZEDGraph cannot change axis color Hi I am new to Zedgraph and I can only find few examples and information.
What I need to do is simple just change the color of the axes from default black to white.This is because I want to use black fill for my panes.
So I try the following
pane.XAxis.Type = AxisType.DateAsOrdinal;
pane.XAxis.Color = Color.White; ;
pane.Y2Axis.Color = Color.White;
Strangely this seems to have no effect and my axis lines are still invisible(lost in the black fill).
thanks
A: Your approach is right, but the axes are overlain by the chart border. So you have two options:
Either make the border invisible:
pane.Chart.Border.IsVisible = false;
Or set also the color of the border to white:
pane.Chart.Border.Color = Color.White;
But be aware, that
pane.XAxis.Color = Color.White;
only effects the axis-line. For coloring all elements of the axis, you also have to set the Colors of Title, Scale, MajorTic, MinorTic, MajorGrid, and MinorGrid of each axis (see ZEDGraph API).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Trying to 'grep' links from downloaded html pages in bash shell environment without cut, sed, tr commands (only e/grep) In Linux shell, I am trying to return links to JPG files from the downloaded HTML script file. So far I only got to this point:
grep 'http://[:print:]*.jpg' 'www_page.html'
I don't want to use auxiliary commands like 'tr', 'cut', 'sed' etc...'lynx' is okay!
A: Using grep alone without massaging the file is doable but not recommended as many have pointed out in the comments.
If you can loosen up your requirements a bit then you can use html tidy to massage the downloaded HTML file so that each html entities are on a single line so that the regular expression can be simpler like you wanted, something like this:
$ tidy file.html|grep -o 'http://[[:print:]]*.jpg'
Note the use of "-o" option to grep to print only the matching part of the input
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Redirect mail.example.com to example.com/webmail Is there any way to redirect HTTP requests that go to mail.example.com (which is my mail server) to go to the webmail interface, example.com/webmail? I've tried to create a subdomain called mail.example.com, but it conflicts with my mail server and cPanel won't allow me to create it. Any ideas?
A: there are bunch of sub-domains CPanel creates for each domain. for example if you register example.com , CPanel creates:
*
*ftp.example.com
*mail.example.com
*cpanel.example.com
*vhm.example.com
by default all these sub-domains point at current server, so If you want to use FTP, there is no difference between example.com or ftp.example.com. Both will work.
So, for your mail sub-domain you can set a document root for it(e.g your webmail interface directory). and because SMTP and POP3 are on diffrent ports, it will work fine with mail clients like Thunderbird.
For setting document root to mail.example.com login to your CPanel and go to Advanced DNS editing part and delete mail.example.com. Then create sub-domain with this name.
You can set document root to webmail interface or redirect users to example.com/webmail.
that's your call.
Note: I haven't tested it my self but I tested such thing for FTP. Let me know if it fails.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Sending email with smtp.secureserver.net with C# and GoDaddy this is driving me absolutely crazy. I am trying to send an email through a web service written in C# through GoDaddy's servers (smtp.secureserver.net) but for some reason it's not working. Here's my code:
public static void SendMessage(string mailFrom, string mailFromDisplayName, string[] mailTo, string[] mailCc, string subject, string body)
{
try
{
using (SmtpClient client = new SmtpClient("smtpout.secureserver.net"))
{
client.Credentials = new NetworkCredential("myemail@mydomain.com", "mypassword");
client.EnableSsl = true;
//client.Credentials = CredentialCache.DefaultNetworkCredentials;
//client.DeliveryMethod = SmtpDeliveryMethod.Network;
string to = mailTo != null ? string.Join(",", mailTo) : null;
string cc = mailCc != null ? string.Join(",", mailCc) : null;
MailMessage mail = new MailMessage();
mail.From = new MailAddress(mailFrom, mailFromDisplayName);
mail.To.Add(to);
if (cc != null)
{
mail.CC.Add(cc);
}
mail.Subject = subject;
mail.Body = body.Replace(Environment.NewLine, "<BR>");
mail.IsBodyHtml = true;
client.Send(mail);
}
}
catch (Exception ex)
{
// exception handling
}
}
string[] mailTo = { "mytestaddress@gmail.com" };
SendMessage("myemail@mydomain.com", "Test Email", mailTo, null, "Secure Server Test", "Testing... Sent at: " + DateTime.Now);
A: GOT IT!!! Need to remove the line "client.EnableSsl = true;" because godaddy does not accept secure connections.
A: I had a similar issue. In my case setting the value of client object's .Port public property was the problem.
Right now, I am not setting that value at all and emails arrive quickly, even with attachments.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592093",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Dict construction with elements in a list I have a list ['a','b','c','d']. I need to construct a dict out of this list with all the elements of the list as keys in the dict with some default value for all the elements such as None.
How to do that? Should I need to write a function for that or is there a constructor available?
A: See dict.fromkeys().
dict.fromkeys(['a','b','c','d']) will return a dictionary with None for all of its values.
dict.fromkeys(['a','b','c','d'], foo) will return a dictionary with foo for all of its values.
A: You can use a generator to quickly convert it to a dictionary:
dict((x, None) for x in L)
(Where L is your list)
That results in:
{'a': None, 'c': None, 'b': None, 'd': None}
A: You can try:
dict.fromkeys(data, default_value)
If you omit default_value, it defaults to None.
A: lst = ['a','b','c','d']
# using list comprehension
d = dict([(x, None) for x in lst])
# using fromkeys
d = dict.fromkeys(lst)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How can I find the references of a class, method, variable in Emacs with Etags? I'd like to find all the references to a class, method, variable in Emacs, the same way I'm able to do it in Eclipse with Ctrl+Shift+G (or Cmd+Shift+G on the Mac) once I've setup my project's ETags.
I can navigate the code fine, but finding references to things is key to understanding large code bases, I'm sure this must be possible in Emacs but I can't find anything about it, maybe an Emacs expert will know right away.
Thanks.
A: I think your best bet is an M-x rgrep . The TAGS file lists the definition of the tags only, not who references it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to use the MATLAB plot function inside a for loop I have this for loop below:
for Vsb = 0:1:5
Vtn = Vto+y*(sqrt(SurfPot + Vsb) + sqrt(SurfPot));
end
I want to plot Vtn vs Vsb for all the values of Vsb. I was trying to use the plot function but it does not seem to work.
A: the Vtn variable should be an array with 6 elements.
Vtn=[];
for Vsb = 0:1:5
Vtn(Vsb) = Vto+y*(sqrt(SurfPot + Vsb) + sqrt(SurfPot));
end
then just plot the Vtn as a function of Vsb with the following
figure
plot(0:5,Vtn,'*r');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592102",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: UIAlert to popup after the UIPicker is closed I have a UIPicker that triggers a UIAlert when a row is selected. I'm trying to have the alert popup after the UIPicker "done" button is pressed and the UIPicker is closed. At the moment the alert triggers when the row is selected. So, as someone scrolls through each row in the picker a UIAlert keeps popping.
thanks for any help
here's the 'done' button code:
-(IBAction)done{
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
CGAffineTransform transform = CGAffineTransformMakeTranslation(0, 480);
pickerView.transform = transform;
[UIView commitAnimations];
}
here's a sample of the picker UIAlert code showing 'case 0' along with the alert message:
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
UIColor *newColor;
switch (row) {
case 0:
newColor = [UIColor yellowColor];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"alert" message:@"message" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:nil];
[alert show];
[alert release];
myLabel.text = @"sometext";
break;
}
A: //Init the done button with an action to show an alert
// and the target as self
self.myBarBtnItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemDefault target:self action:@selector(showAlert:)]
Then your action:
// Show the alert with the currently selected row index of the picker
- (void)showAlert:(id)sender {
NSUInteger selectedIndex = [myPickerView selectedRowInComponent:0];
UIAlertView *alert = [[[UIAlertView alloc] initWithTitle:[NSString stringWithFormat@"Row %f selected!", selectedIndex + 1] message:[NSString stringWithFormat:@"Row %d / %d selected.", selectedIndex + 1, [self pickerView:myPickerView numberOfRowsInComponent:0]] autorelease];
[alert show];
}
A: -(IBAction)done{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"alert" message:@"message" delegate:nil cancelButtonTitle:@"cancel" otherButtonTitles:nil];
[alert show];
[alert release];
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDuration:0.5];
CGAffineTransform transform = CGAffineTransformMakeTranslation(0, 480);
pickerView.transform = transform;
[UIView commitAnimations];
}
- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
UIColor *newColor;
switch (row) {
case 0:
newColor = [UIColor yellowColor];
myLabel.text = @"sometext";
break;
}
}
A: Elegant way :
Add delegate to your view animation see UIView.h
*
*(void)setAnimationDidStopSelector:(SEL)selector
[UIView beginAnimations:nil context:nil];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(animationFinished:finished:context:)
[UIView setAnimationWillStartSelector:self];
[UIView setAnimationDuration:0.5];
CGAffineTransform transform = CGAffineTransformMakeTranslation(0, 480);
pickerView.transform = transform;
[UIView commitAnimations];
and implement this method:
-(void)animationFinished:(NSString *)animationID finished:(BOOL)finished context:(void *)context
voilà
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: jquery animate onStart callback Does jquery animate method have a onStart callback. I know about the complete callback but don't see anywhere to use other callbacks like onStart or initialize .
I want onStart callback because when I am calling animate(), it may not start immediately but queued due to previous animation not finished.
A: .animation() have a undocumented start options
$('.box').animate({left:100},{
duration:500,
start:function(){
console.log('start');
},
complete:function(){
console.log('end');
}
});
A: I've used this method in the past and it seems to work pretty well. Hopefully it can work for you.
Edit (2016/12/06 - Better example of what OP requested)
HTML:
<div class="tile">X</div>
CSS:
body {
position: relative;
}
.tile {
position: absolute;
display: block;
padding: 20px;
background: aqua;
text-align: center;
font-size: 32px;
font-family: sans-serif;
}
JavaScript:
function doMe() {
console.log('We called a callback function!');
}
$('#tiles .tile').animate({
'left': '+=500px'
}, {
duration: 6000,
step: function(now, fx) {
var data = $(this).data('anistart');
if (!data) {
console.log('We started!');
$(this).data('anistart', {
start: fx.start,
end: fx.end
});
doMe();
}
console.log('We\'re stepping...');
},
complete: function() {
var data = $(this).data('anistart');
if (data.end !== parseFloat($(this).css('left'))) {
$(this).css('left', data.end);
}
$(this).removeData('anistart');
console.log('We ended!');
}
});
On the step function, I'm testing to see if the object has previously set data. If not I set it and then we can call/handle any stuff (i.e. your callback)
On the complete function, I make sure the position is what it should be, if not, I set it. You could most likely do away with the test and just set it, but not sure which one is more of a performance hit (the check or the css set).
So no matter what the case, you set a variable on start, and if its not set then you know its the first time... i.e. its being initialized.
DEMO: Example of jQuery animate onStart callback
A: On start occurs when you fire your animation
function onStart(){
$('.box').animate({left:100},500,onComplete())
}
function onStart()
A: Easy Way
I am not very experienced but this is the way to go.
Just insert css method before animate.
Like this:
$(this).css({ "display": "block", "opacity": "0" })
.animate({ "opacity": "1" }, 200);
A: Once you call the animate method, it will run while your other javascript code is running. So the equivalent of having an onStart callback would be putting the code you want to run immediately after the animate method. Additionally, there is a 'step' function you can use.. http://api.jquery.com/animate/#step .. I haven't used it, but it seems like you can check for the initial CSS values you're working with and only execute code based on that. Could be a performance issue though if you're animating a lot of parts.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Iterate through memory editing each byte I'm writing assembly code that prompts the user for a string of lower-case characters then outputs the same string with all UPPER-CASE characters. My idea is to iterate through the bytes starting at a specific address and subtract 20H (turns a lower case to upper-case) from each one until I reach a byte with a specific value. I'm fairly inexperienced with Assembly so I'm not sure what the syntax for such a loop would look like.
Can anyone provide some sample code or direct me where I can find examples of such syntax?
Any help is greatly appreciated!
A: Typically, a string is terminated with a null (0x00 in hex). Assuming this is what you choose to do, here's some sample code. I'm not sure which assembler you're using, or even which syntax, but this x86 code that should work in MASM:
mov cl, 0 ; cl is the counter register, set it to
; zero (the first character in the string)
start: ; Beginning of loop
mov al, bytes[cl] ; Read the next byte from memory
cmp al, 0 ; Compare the byte to null (the terminator)
je end ; If the byte is null, jump out of the loop
sub al, 20h ; Convert to upper case
; A better solution would be: and al, 0DFh
; Output the character in al
add cl, 1 ; Move to the next byte in the string
jmp start ; Loop
end:
A: Well, one concise (but not optimal for performance on current processors) choice would be:
*
*have a counter of some type to control the loop
*point ds:si and es:di at the beginning
*do a lodsb, and al, dfh, stosb sequence in the loop
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592115",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android Viewpager with asynctasks (spinner while page is loading) I want a Viewpager that shows loading while content is coming in from the background. Basically I expect the first View to be loaded, but View+1 and View-1 will still be loading. If the user swipes to either side I want them to be presented with a spinning dialog while it loads
Would I just add AsyncTasks into the ViewPager with some conditions determining when they will run? I dont want too many AsyncTasks to be loading as the viewpager will have many views off to the sides.
I think the Trulia app does this, it is similar to what I am looking for. Apartment image viewing shows a loading screen while the images are loading in that viewpage.
Also for the record, can I just treat viewpagers like onCreate functions of an activity? That would really clear things up
Insight appreciated
A: Have a look at the supplied FragmentPagerAdapter if you want to perform more Activity-like lifecycle management of each page.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Need of Virtual memory? I was recently asked a question that in a computer system, if the primary memory(RAM) is comparable to the secondary memory (HDD) then is there a need for virtual memory to be implemented in such a computer system ?
Since paging and segmentation require context switching, which is purely processing overhead, would the benefits of virtual memory overshoot the processing overhead it requires ?
Can someone help me with this question ?
Thanku
A: It is true that with virtual memory, you are able to have your programs commit (i.e. allocate) a total of more memory that physically available. However, this is only one of many benefits if having virtual memory and it's not even the most important one. Personally, when I use a PC, I periodically check task manager to see how close I come to using my actual RAM. If I constantly go over, I go and I buy more RAM.
The key attribute of all OSes that use virtual memory is that every process has its own isolated address space. That means you can have a machine with 1GB of RAM and have 50 processes running but each one will still have 4GB of addressable memory space (32-bit OS assumed). Why is it important? It's not that you can "fake things out" and use RAM that isn't there. As soon as you go over and swapping starts, your virtual memory manager will begin thrashing and performance will come a halt. A much more important implication of this is that if each program has it's own address space, there's no way it can write to any random memory location and affect another program.
That's the main advantage: stability/reliability. In Windows 95, you could write an application that would crash entire operating system. In W2K+, it is simply impossible to write a program that paves all over its own address space and crashes anything other than self.
There are few other advantages as well. When executables and DLLs are loaded into RAM, virtual memory manager can detect when the same binary is loaded more than once and it will make multiple processes share the same physical RAM. At virtual memory level, it appears as if each process has its own copy, but at a lower level, it all gets mapped to one spot. This speeds up program startup and also optimizes memory usage since each DLL is only loaded once.
Virtual memory managers also allow you to perform file I/O by simply mapping files to pages in the virtual address space. In addition to introducing interesting alternative to working with files, this also allows for implementations of shared memory segments which is when physical RAM with read/write pages is intentionally shared between processes for extremely efficient inter-process communications (IPC).
With all these benefits, if we consider that most of the time you still want to shoot for having more physical RAM than total commit size and consider that modern CPUs have support for virtual address mapping built directly into the hardware, the overhead of having virtual memory manager is actually very minimal. On the other hand, in environments where many applications from many different vendors run concurrently, process address space is priceless.
A: Virtual memory working
It may not ans your whole question. But it seems the ans to me
A: I'm going to dump my understanding of this matter, with absolutely no background credentials to back it up. Gonna get downvoted? :)
First up, by saying primary memory is comparable to secondary memory, I assume you mean in terms of space. (Afterall, accessing RAM is faster than accessing storage).
Now, as I understand it,
Random Access Memory is limited by Address Space, which is the addresses which the operating system can store stuff in. A 32bit operating system is limited to roughly 4gb of RAM, while 64bit operating systems are (theoretically) limited to 2.3EXABYTES of RAM, although Windows 7 limits it to 200gb for Ultimate edition, and 2tb for Server 2008.
Of course, there are still multiple factors, such as
*
*cost to manufacture RAM. (8gb on a single ram thingie(?) still in the hundreds)
*dimm slots on motherboards (I've seen boards with 4 slots)
But for the purpose of this discussion let us ignore these limitations, and talk just about space.
Let us talk about how applications nowadays deal with memory. Applications do not know how much memory exists - for the most part, it simply requisitions it from the operating system. The operating system is the one responsible for managing which address spaces have been allocated to each application that is running. If it does not have enough, well, bad things happen.
But, surely with theoretical 2EXABYTES of RAM, you'd never run out?
Well, a famous person long ago once said we'd never need more than 64kBs of RAM.
Because most Applications nowadays are greedy (they take as much as the operating system is willing to give), if you ran enough applications, on a powerful enough computer, you could theoretically exceed the storage limits of the physical memory. In that case, Virtual Memory would be required to make up the extra required memory.
So to answer your question: (in my humble opinion formed from limited knowledge on the matter,) yes you'd still need to implement virtual memory.
Obviously take all this and do your own research. I'm turning this into a community wiki so others can edit it or just delete it if it is plain wrong :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592119",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How long can a php cron job run for / am I doing it right? I have created a php/mysql scraper, which is running fine, and have no idea how to most-efficiently run it as a cron job.
There are 300 sites, each with between 20 - 200 pages being scraped. It takes between 4 - 7 hours to scrape all the sites (depending on network latency and other factors). The scraper needs to do a complete run once daily.
Should I run this as 1 cron job which runs for the entire 4 - 7 hours, or run it every hour 7 times, or run it every 10 minutes until complete?
The script is set up to run from the cron like this:
while($starttime+600 > time()){
do_scrape();
}
Which will run the do_scrape() function, which scrapes 10 urls at a time, until (in this case) 600 seconds has passed. The do_scrape can take between 5 - 60 seconds to run.
I am asking here as I cant find any information on the web about how to run this, and am kind of wary about getting this running daily, as php isnt really designed to be run as a single script for 7 hours.
I wrote it in vanilla PHP/mysql, and it is running on cut down debian VPS with only lighttpd/mysql/php5 installed. I have run it with a timeout of 6000 seconds (100 minutes) without any issue (the server didnt fall over).
Any advice on how to go about this task is appreciated. What should I be watching out for etc..? or am i going about executing this all wrong?
Thanks!
A: There's nothing wrong with running a well-written PHP script for long periods. I have some scripts that have literally been running continuously for months. Just watch your memory usage, and you should be fine.
That said, your architecture is pretty basic, and is unlikely scale very well.
You might consider moving from a big monolithic script to a divide-and-conquer strategy. For instance, it sounds like your script is making synchronous requests for every URL is scrapes. If that's true, then most of that 7 hour run time is spent idly waiting for a response from some remote server.
In an ideal world, you wouldn't write this kind of thing PHP. Some language that handles threads and can easily do asynchronous http requests with callback would be much better suited.
That said, if I were doing this in PHP, I'd be aiming at having a script that kicks of N children who grab data from URLs, and stick the response data in some kind of work queue, and then another script that pretty much runs all the time, processing any work it finds in the queue.
Then you just cron your fetcher-script-manager to run once an hour, it manages some worker processes that fetch the data (in parellel, so latency doesn't kill you), and stick the work on the queue. Then the queue-cruncher sees the work on the queue and crunches it.
Depending on how you implement the queue, this could scale pretty well. You could have multiple boxes fetching remote data, and sticking it on some central queue box (with a queue implemented in mysql, or memcache, or whatever). You could even conceivably have multiple boxes taking work from the queue and doing the work.
Of course, the devil is in the details, but this design is generally more scalable and usually more robust than a single-threaded fetch-process-repeat script.
A: You shouldn't have a problem running it once a day to completion. That's the way I would do it. Timeouts are a big issue if php is being served through a web server, but since you are interpreting directly through the php executable this is ok. I would advise you to use python or something else that is more task-friendly, though.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592126",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: Program is generating same random numbers on each run? I just finished coding a Minesweeper type game, and everything's good except for that each time I run the application, it generates the same number (I ran it 3 different times, saved the output to 3 text files and used the diff command in Linux, it didn't find any differences). It's seeded by time(NULL) so it should change every time, right?
Here's my code:
main.cpp
#include <iostream>
#include <cstdlib>
#include <time.h>
#include <string>
#include "Minesweeper/box.h"
#include <cstdio>
int main(int argc, char** argv){
using namespace std;
bool gameOver = false;
int x, y, score = 0;
const int HEIGHT = 10;
const int WIDTH = 10;
unsigned int Time = time(0);
cout << "Welcome to Minesweeper. " << endl;
//setup grid
Box grid[10][10];
for(int i = 0; i < WIDTH; i++)
for(int n = 0; n < HEIGHT; n++){
unsigned int value = rand() %100 + 1;
cout << value << endl;
if(value <= 38){
grid[i][n].setFill(MINE);
//cout << i << "," << n << " is mined." << endl;
}
else
grid[i][n].setFill(EMPTY);
}
for(int r = 0; r < WIDTH; r++)
for(int l = 0; l < HEIGHT; l++)
if(grid[r][l].getFill() == EMPTY)
cout << r << "," << l << " - EMPTY." << endl;
else if (grid[r][l].getFill() == MINE)
cout << r << "," << l << " - MINE." << endl;
while(!gameOver){
cout << "Enter coordinates (x,y): ";
scanf("%i,%i",&x,&y);
if(grid[x][y].getFill() == MINE)
gameOver = true;
else{
cout << "Good job! (You chose " << x << "," << y << ")" << endl;
score++;
}
}
cout << "You hit a mine! Game over!" << endl;
cout << "Final score: " << score << endl;
getchar();
return EXIT_SUCCESS;
}
A:
It's seeded by time(NULL)
If it is, I can't see it. In fact, a search for it in your code returns nothing. The default behaviour, if you don't explicitly seed, is the same as if you had seeded it with the value 1.
You need to explicitly state something like:
srand (time (NULL));
at the start of main somewhere (and make sure you do this once and once only).
Though keep in mind this makes it dependent on the current time - if you start multiple jobs in the same second (or whatever your time resolution is), they'll start with the same seed.
From the C standard (on which C++ is based for these compatibility features):
The srand function uses the argument as a seed for a new sequence of pseudo-random numbers to be returned by subsequent calls to rand. If srand is then called with the same seed value, the sequence of pseudo-random numbers shall be repeated. If rand is called before any calls to srand have been made, the same sequence shall be generated as when srand is first called with a seed value of 1.
A: You need to seed randomizer. Call srand() at the beginning.
A: To add to the answers by others, you can use the Mersenne Twister Algorithm, which is a part of the C++11 library. Its fast becoming a standard in many common softwares to generate random numbers.
For example, this is the function I wrote, which I use often to generate random numbers in my other codes:
std::vector<double> mersennetwister(const int& My,const int& Mz,
const int& Ny,const int& Nz)
{
int ysize = (My + 2*Ny + 1);
int zsize = (Mz + 2*Nz + 1);
int matsize = ysize*zsize;
unsigned seed = std::chrono::system_clock::now().time_since_epoch().count();
// Seeding the generator with the system time
std::mt19937_64 generator (seed);
// Calling the Mersenne-Twister Generator in C++11
std::uniform_real_distribution<double> distribution(0,1);
// Specifying the type of distribution you want
std::vector<double> randarray(matsize,0);
// Saving random numbers to an array
for (int i=0;i<matsize;++i)
{
randarray[i] = distribution(generator); // Generates random numbers fitting the
// Distribution specified earlier
}
return(randarray);
}
Bottomline: C++11 has some excellent features for numerical operations and it would be a good idea to look into them. As for the Mersenne Twister, http://en.wikipedia.org/wiki/Mersenne_twister
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to write rspec get statements for customized routes? I have defined a user resource, and each user has several items. Now I want to add a route for /user/:id/items(.:format), instead of defining items as nested resource, I use member route:
resources :user do
member do
match "/items" => "items#index", :via => [:get]
end
end
The problem is when I try to write rspec for the controller, I don't know what action should I use to access items#index. I tried
describe ItemsController do
it "denies access to item index without login" do
sign_out @user
get "index", :user_id => @user.id, :format => :json
response.code.should == "401"
end
# ...
end
But after executing rake spec:controllers it says
Failure/Error: get "index", :user_id => @user.id, :format => :json
ActionController::RoutingError:
No route matches {:user_id=>"1", :format=>"json", :controller=>"items"}
I am using Rails 3.1. How can I use rspec to test this member route? Thanks.
A: Pretty sure it needs to be:
get :index, :id => @user.id, :format => :json
You need to pass :id, not :user_id
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7592136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.