text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Sum of 3 variables: strange behavior
Possible Duplicate:
Is JavaScript's Math broken?
Why can't decimal numbers be represented exactly in binary?
What will be result of next code:
if(0.3 == ( 0.1 + 0.1 + 0.1 ))
{
alert(true);
}
else
{
alert(false);
}
It is strange, but result will be false.
Reason is that result of
0.1+0.1+0.1
will be
0.30000000000000004
How can be explained this behavior?
A: It's the same reason 1/3 + 1/3 + 1/3 may not give you exactly 1 in decimal. If you use 1/3 as .33333333, then 1/3 + 1/3 + 1/3 will give you .9999999 which isn't exactly one.
Unless you know exactly what you're doing, don't compare non-integer numeric types for equality.
A: The explanation is pretty simple - read about Floating Point Numbers Problems
A: It's due to the nature of floats stored in computers. There is no such thing as an exact way to store an arbitrary floating point number. What you typically do when you compare floats is to see if the difference is smaller than some small number epsilon, like this:
function equals(f1, f2){
var epsilon = 0.00001; //arbitrary choice
return (f1-f2 < epsilon && f2-f1 < epsilon);
}
so in your case, change if(0.3 == ( 0.1 + 0.1 + 0.1 )) to if(equals 0.3, (0.1 + 0.1 + 0.1))
A: What you're experiencing is a basic floating point rounding error.
We can't precisely represent 0.1 without some error due to the nature of binary numbers. WolframAlpha reports decimal 0.1 to equal binary ~0.00011001100110011... Notice how it can't be finitely represented in the binary number system? This means we have to decide on a cut off point at which to stop calculating this number otherwise we'd be here forever.
This introduces an error. And this error has accumulated as the code adds the numbers together which results in an incredibly small quantity added to the end of your sum. This ensures that the sum will never be EXACTLY 0.3, which is what the IF test is looking for.
Some decimal numbers, however, can be represented accurately in binary such as dec 0.5 = bin 0.1 and dec 0.25 = bin 0.01.
We can demonstrate this similarly to your original code by using 0.5 = (0.25 + 0.25).
For further reading on this I recommend The Floating-Point Guide.
It provides a good overview of the concept of floating point numbers and how errors in calculation can arise. There is also a section on Javascript which demonstrates how to overcome the rounding errors you're experiencing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: jQuery get the next sibling hidden value on click I'm trying to get the hidden field value on click event of a link. Here's where those elements are:
<p>
<a class="showCommentAttachment cboxElement" href="#">Attachments</a>
<input type="hidden" value="13" id="ctl00_ContentPlaceHolder1_lvComment_ctrl3_hfCommentId" name="ctl00$ContentPlaceHolder1$lvComment$ctrl3$hfCommentId">
</p>
Here the complete mark-up:
<div id="divComment" class="comment-text">
<div class="comment-author">
David Chart
</div>
<span class="comment-date-time">Sep 29, 2011 08:12:42 PM</span>
<p>
Some comment text goes here. Some comment text goes here.
</p>
<p>
<a class="showCommentAttachment cboxElement" href="#">Attachments</a>
<input type="hidden" value="13" id="ctl00_ContentPlaceHolder1_lvComment_ctrl3_hfCommentId" name="ctl00$ContentPlaceHolder1$lvComment$ctrl3$hfCommentId">
</p>
</div>
Here's the jQuery:
$("#divComment a.showCommentAttachment").click(function() {
var nextSibling = $(this).next().find('input:hidden').val();
$("#showCommentId").html(nextSibling + "<-- Here's the comment ID ");
});
what I get back from nextSibling is undefined. I tried with nexAll like this
var nextSibling = $(this).nextAll().find('input:hidden').val();
still got undefined.
Thank you.
A: You should use simply $(this).next() since the next element is surely the hidden input field. Also with $(this).next().find() you are querying the children elements of the hidden input element. This is from jQuery API documentation:
.find()
Get the descendants of each element in the current set of matched elements, filtered by a selector, jQuery object, or element.
So you need $(this).next().val().
A: .next() gives you the next sibling which is the input field itself. Calling .find() is then searching for descendants of this field (there aren't any).
You just want $(this).next().val()
A: please try:
$(this).next().val();
or
$("#divComment a.showCommentAttachment").next().val();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608191",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Facebook user Authentication process I am trying out this example http://thinkdiff.net/facebook/new-javascript-sdk-oauth-2-0-based-fbconnect-tutorial/
But I am getting xml error which says permission denied.
I have changed the application ID also. I am bit confused about the new UI of developers.facebook.com I was comfortable with the old UI.
I am not sure where I dont mention my call back url.
Kindly help me out.
<div id="fb-root"></div>
<script type="text/javascript">
var button;
var userInfo;
window.fbAsyncInit = function() {
FB.init({ appId: '273713715982249', //change the appId to your appId
status: true,
cookie: true,
xfbml: true,
});
showLoader(true);
function updateButton(response) {
button = document.getElementById('fb-auth');
userInfo = document.getElementById('user-info');
if (response.authResponse) {
//user is already logged in and connected
FB.api('/me', function(info) {
login(response, info);
});
button.onclick = function() {
FB.logout(function(response) {
logout(response);
});
};
} else {
//user is not connected to your app or logged out
button.innerHTML = 'Login';
button.onclick = function() {
showLoader(true);
FB.login(function(response) {
if (response.authResponse) {
FB.api('/me', function(info) {
login(response, info);
});
} else {
//user cancelled login or did not grant authorization
showLoader(false);
}
}, {scope:'email,user_birthday,status_update,publish_stream,user_about_me'});
}
}
}
// run once with current status and whenever the status changes
FB.getLoginStatus(updateButton);
FB.Event.subscribe('auth.statusChange', updateButton);
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol
+ '//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
function login(response, info){
if (response.authResponse) {
var accessToken = response.authResponse.accessToken;
userInfo.innerHTML = '<img src="https://graph.facebook.com/' + info.id + '/picture">' + info.name
+ "<br /> Your Access Token: " + accessToken;
button.innerHTML = 'Logout';
showLoader(false);
document.getElementById('other').style.display = "block";
}
}
function logout(response){
userInfo.innerHTML = "";
document.getElementById('debug').innerHTML = "";
document.getElementById('other').style.display = "none";
showLoader(false);
}
//stream publish method
function streamPublish(name, description, hrefTitle, hrefLink, userPrompt){
showLoader(true);
FB.ui(
{
method: 'stream.publish',
message: '',
attachment: {
name: name,
caption: '',
description: (description),
href: hrefLink
},
action_links: [
{ text: hrefTitle, href: hrefLink }
],
user_prompt_message: userPrompt
},
function(response) {
showLoader(false);
});
}
function showStream(){
FB.api('/me', function(response) {
//console.log(response.id);
streamPublish(response.name, 'I like the articles of Thinkdiff.net', 'hrefTitle', 'http://thinkdiff.net', "Share thinkdiff.net");
});
}
function share(){
showLoader(true);
var share = {
method: 'stream.share',
u: 'http://thinkdiff.net/'
};
FB.ui(share, function(response) {
showLoader(false);
console.log(response);
});
}
function graphStreamPublish(){
showLoader(true);
FB.api('/me/feed', 'post',
{
message : "I love thinkdiff.net for facebook app development tutorials",
link : 'http://ithinkdiff.net',
picture : 'http://thinkdiff.net/iphone/lucky7_ios.jpg',
name : 'iOS Apps & Games',
description : 'Checkout iOS apps and games from iThinkdiff.net. I found some of them are just awesome!'
},
function(response) {
showLoader(false);
if (!response || response.error) {
alert('Error occured');
} else {
alert('Post ID: ' + response.id);
}
});
}
function fqlQuery(){
showLoader(true);
FB.api('/me', function(response) {
showLoader(false);
//http://developers.facebook.com/docs/reference/fql/user/
var query = FB.Data.query('select name, profile_url, sex, pic_small from user where uid={0}', response.id);
query.wait(function(rows) {
document.getElementById('debug').innerHTML =
'FQL Information: '+ "<br />" +
'Your name: ' + rows[0].name + "<br />" +
'Your Sex: ' + (rows[0].sex!= undefined ? rows[0].sex : "") + "<br />" +
'Your Profile: ' + "<a href='" + rows[0].profile_url + "'>" + rows[0].profile_url + "</a>" + "<br />" +
'<img src="' + rows[0].pic_small + '" alt="" />' + "<br />";
});
});
}
function setStatus(){
showLoader(true);
status1 = document.getElementById('status').value;
FB.api(
{
method: 'status.set',
status: status1
},
function(response) {
if (response == 0){
alert('Your facebook status not updated. Give Status Update Permission.');
}
else{
alert('Your facebook status updated');
}
showLoader(false);
}
);
}
function showLoader(status){
if (status)
document.getElementById('loader').style.display = 'block';
else
document.getElementById('loader').style.display = 'none';
}
This is the code I am using I am not to logiin but I am not getting the user information.
A: function fblogin() {
FB.login(function(response) {
if(response.session && response.perms){
FB.api('/me', function(response) {
});
}
}, {perms:''});//set the permissions
}
</script>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : '',//giv ur app id
status : true, // check login status
cookie : true, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
(function() {
var e = document.createElement('script');
e.src = 'https://connect.facebook.net/en_US/all.js';
e.async = true;
document.getElementById('fb-root').appendChild(e);
}());
</script>
A: Facebook has introduced Auth Dialog feature in Facebook application Setting page. Now you don’t need to write code to for user permissions. You can do it by configuring the right values in Application settings. get more details at http://iforapple.org/?p=436
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608192",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error after updating to the latest version Azure SDK After I updated to the newest version the Azure SDK I have started to get this error several times each day when I press build in Visual Studio. The only way for me to fix it at the moment is to restart my visual studio.
The error I get is:
Windows Azure Tools: Invalid access to memory location
Is there someone else that have got this error? And also what did you do to fix it?
Thanks in advance!
Update 2012-08-28: The same error still exist in VS2012 and Azure 1.7 SDK. However the frequency have gone down with VS2012.
A: I've had the same problem as you, and I've tried it all.
Upgrading, downgrading, reboot, re-install. Getting all windows updates and so on.
But I finaly found what was causing my problems. It was the database, or I should say my sql express database that was causing the problem.
Azure SDK will by default create the DB that it needs on a express edition. After changing what DB azure should use, everything works perfectly.
Details on how to switch to another DB:
A: that was fixed in Windows 8.1, however for older versions of Windows there is a hotfix available
A: Not sure when you installed the SDK, but a hotfix has been issued. You can't tell by going to the download page. Just reinstall the SDK.
A: I had de same problem and after try everything, i search and install all the windows updates available, thid include, vs2010 sp1, windows 7 sp1, and a lot more.
after that everything start to work fine.
hope it helps.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608194",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Android fill_parent to match_parent What was the reason behind introducing match_parent and deprecating fill_parent since both mean the same thing. won't this change be a hindrance to backward compatibility?
A: Android Doc says:
FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which means that the view wants to be as big as its parent (minus padding)
fill_parent: The view should be as big as its parent (minus padding).
This constant is deprecated starting from API Level 8 and is replaced
by match_parent.
So They are the same as their values are both -1. But if you worry about the backward compatibility, you can go here: platfrom version
this give you a better idea on when you should change all your fill_parent to match_parent.
as of now, it seems 50% ppl are using API Level 8 or above. So it's up to you to change it.
A: Using match_parent instead of fill_parent will NOT make the generated APK unrunnable in older versions because in the generated APK the occurrence of match_parent's and fill_parent's will be replaced with their corresponding Constant Value, which is same in this case (both are -1), so same APK can run on older versions of Android platform as well.
But while compiling the code if you switch to older version (version 7 or below) then you will get a compilation error (since match_parent is not defined in version 7 or below).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608196",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Ajax styled file upload & session there are two things which is important
*
*send any file from client to server & save it somewhere in the server location
*get the saved location of uploaded file and send back to client. e.g.
context name : project
predefined folder : upload -> /project/upload
response : /project/upload/file_exaple.jpg
Ajax can't handle file upload so my idea is to send the file using form with target and save the file into server, also get the file path /project/upload/file_exaple.jpg. this part has been done & working.
form action="upload" enctype="multipart/form-data" method="post" target="IFrame">
once the first part succeed, in second part i can use AJAX to get the uploaded file location but the problem i am getting when multiple client's are uploading at same time. file upload succeed but file path couldn't find somehow.
I need to manage the file path with session and linked with AJAX somehow but i am not able to do that [the second part]. Any idea on it?
A: I ran in too similar questions, i've found this ajax-uploader suited for all of my needs, might be helpful to you:
Valums.com/ajax-upload
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Compilation error in one case but not the other, when all expressions have same types I have a pieces of code:
The method is as follows:
public IEnumerable<c> Test(){
var collection = new a();
IEnumerable<c> bs = collection.Where(item => item.Id > 10).Select(item => item);
return from item in collection
where item.Id > 10
select item;
}
(the first two lines compiles fine)
It doesn't compile and fails with:
Cannot implicitly convert type System.Collections.Generic.IEnumerable<Stackoverflow.b> to System.Collections.Generic.IEnumerable<Stackoverflow.c>
however the code below compiles just fine:
return from item in collection
where item.Id > 10
select new b(null);
since the type of the expression in the select clause is the same I'd expect it to compile in both cases or fail in both.
if I use method syntax instead of query comprehesion and write:
collection.Where(item => item.Id > 10).Select(item => item)
that too compiles
my question is "Is there something wrong with the universe" (is this a compiler bug) or am I missing something?
EDIT
I have no using System.Linq so the normal select and where methods is not in play only those below
The code is part of an academic exercise to try and stretch the pattern-based method overload resolution of LINQ. The signatures are deliberately weird/surprising and the where includes a projection though I believe this would generally be a pretty bad idea.
EDIT
The definitions of the classes in question and the select extension method
public static class Enumerable {
public static IEnumerable<c> Select(this IEnumerable<b> self, Func<b,b> selector){
return null;
}
}
public class a{
public IEnumerable<b> Where(Predicate<a> predicate){
return null;
}
public int Id { get; set; }
}
public class b{
}
public class c{
}
A: That's all about query expressions translation. You might want to look at C# Language Specification 4.0 7.16.2 (or 7.15.2 for C# 3.0) for more details, but in short, expressions like:
from x in c
where f(x)
select x
Are translated just to
c.Where(x => f(x))
so your Enumerable.Select wouldn't be called and you'll get IEnumerable<b> as a result instead of IEnumerable<c>. Exactly what compiler is complaining about.
A: As it stands in the error message.
You are not returning the same value as the method signature is.
If you read the error message it stands that it expect C but get B
A: Try
return from item in collection
where item.Id > 10
select (c)item;
Seems like all you're missing is a cast from b to c. It might be that using the .Select extension method the compiler can work out this cast automatically. I've seen the compiler using the correct generic method based on the return type. So instead of saying MyItem item = GenericMethod<MyItem>(input) one can say MyItem item = GenericMethod(input) and the compiler knows which type to use.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is it faster/better way to force authentication with NSURLConnection rather then using delegate method? If I know that authentication is required for my server API, is it faster/better to directly force authentication using http header instead of waiting for the server to return 401 response and then respond to it inside NSURLConnection delegate method connection:didReceiveAuthenticationChallenge:?
A: The "easier way" to provide authentication credentials to a server is to use NSURLConnection delegate method
didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge
where you can provide credentials similar to this
- (void)connection:(NSURLConnection *)connection didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge {
if ([challenge previousFailureCount] == 0) {
NSURLCredential *newCredential;
newCredential = [NSURLCredential credentialWithUser:userName password:password persistence:NSURLCredentialPersistenceNone];
[[challenge sender] useCredential:newCredential forAuthenticationChallenge:challenge];
} else {
[[challenge sender] cancelAuthenticationChallenge:challenge];
}
}
What will happen is that you first call server with your GET/POST request and if the server requires authentication, and credentials were not provided inside HTTTP header, it will (hopefully) respond with 401 response. The above method will trigger and provide supplied credentials.
But if you know that your server will always require authentication, it is not efficient to make this extra round of client/server communication and you will be better off to provide your credentials straight away inside the HTTP header.
The method of providing credentials inside HTTP header is simple apart from the fact that iOS doesn't come with a method to encode to BASE64.
NSMutableURLRequest *aRequest = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:30];
// first create a plaintext string in the format username:password
NSMutableString *loginString = (NSMutableString *)[@"" stringByAppendingFormat:@"%@:%@", userName, password];
// encode loginString to Base64
// the Base64 class is not provided and you will have to write it!
NSString *encodedLoginData = [Base64 encode:[loginString dataUsingEncoding:NSUTF8StringEncoding]];
// prepare the header value
NSString *authHeader = [@"Basic " stringByAppendingFormat:@"%@", encodedLoginData];
// add the authentication credential into the HTTP header
[request addValue:authHeader forHTTPHeaderField:@"Authorization"];
// provide additional HTTP header properties (optional)
[aRequest setValue:@"application/json" forHTTPHeaderField:@"Accept"];
[aRequest setValue:@"application/json" forHTTPHeaderField:@"Content-Type"];
[aRequest setHTTPMethod:@"GET"];
// and finally create your connection for above request
NSURLConnection *aConnection = [[NSURLConnection alloc] initWithRequest:aRequest delegate:self];
// don't forget to release the request and nsurlconnection when appropriate...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608213",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: accesoryView out of the screen on iPad We have the same code for a UITableView on iPhone and on IPad.
For every row we show an accesory view with an specific icon.
In iphone works perfectly, but in iPad ... for some reason the accessory doesn't appears, and when you select one of the rows, you could see them in the transition ... Is like them are out of the screen.
Any suggestions?
Thank you,
Ivan
A: Solved.
I found a mistake in the tableview.frame on viewDidLoad ...
:S
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Code works in an HTML page but not in an ASP.NET page I'm using a dateplustimepicker control which works fine on an HTML page but does not work when used on an ASP.NET page. Here's the code I'm using on the ASP.NET page:
<div>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<link href="css/jquery-ui.css" rel="stylesheet" type="text/css"/>
<link href="css/jquery-dateplustimepicker.min.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="js/jquery-ui.min.js"></script>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="Scripts/jquery-dateplustimepicker.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#limit-dateplustimepicker').dateplustimepicker({
minTime: { hours: 8, minutes: 30 },
maxTime: { hours: 20 }
});
});
</script>
<input type="text" id="limit-dateplustimepicker" name="limit-dateplustimepicker" />
</div>
Why does it work as an HTML page but not as an ASP.NET aspx page?
A: A couple of things:
(1) Swap the order you include jQuery and jQuery UI:
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery-ui.min.js"></script>
(2) Move the <meta> tag to <head>.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Autorun the Application using C# I want to create an application that's automatically run after booting the machine.
Can anyone help me on how can I do it on C#.
A: Create a windows service for your application register that windows service and set startup property as automatic .
Now your service will start automatically when ever windows starts
and
see this link:
http://www.geekpedia.com/tutorial151_Run-the-application-at-Windows-startup.html
A: This is how you add an app to startup:
// The path to the key where Windows looks for startup applications
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (!IsStartupItem())
// Add the value in the registry so that the application runs at startup
rkApp.SetValue("My app's name", Application.ExecutablePath.ToString());
And to remove it:
// The path to the key where Windows looks for startup applications
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if(IsStartupItem())
// Remove the value from the registry so that the application doesn't start
rkApp.DeleteValue("My app's name", false);
And the IsStartupItem function in my code:
private bool IsStartupItem()
{
// The path to the key where Windows looks for startup applications
RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (rkApp.GetValue("My app's name") == null)
// The value doesn't exist, the application is not set to run at startup
return false;
else
// The value exists, the application is set to run at startup
return true;
}
A: Most of the ways programs achieve this is through an installer, which can do many things including modifying the registry to ensure their program is started upon startup, however you should always give your users the option to disable this behaviour.
A: I think a better way rather than adding a key in the registry is too add a shortcut in the Windows StartUp folder: it is more transparent to the user and you let the choice to the user to delete the shortcut if he doesn't want your application to start at Windows boot.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Will an object live while there is reference to interface which It implements? I have a class implementing an interface. I don't need a reference to objects of that class - only reference to their interfaces. It looks like:
interface A {}
class B : A {}
//in code:
A a = (A) new B();
My question is: Will instance of B to live (not collecting by GC) while I have a reference to A of that B?
A: Yes, because you still have a reference to that new B() although you can see only the part that implements that interface A.
A: The reference is the same actual value no matter whether your variable is typed as the class or the interface. So yes: it will stay alive.
A: yes the instance of the object is the same, you can cast the object to any of its implemented interface, but the instance is one.
A: Yes, because a reference to an object through an interface is still a reference to that object.
Casting an object to an interface does not create a new object, it just alters the "portal" you use to talk to the object through.
You can easily test this in LINQPad:
void Main()
{
A a = (A)new B();
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
GC.KeepAlive(a);
Debug.WriteLine("Got here");
}
public interface A
{
}
public class B : A
{
~B()
{
Debug.WriteLine("B was finalized");
}
}
When executed, you'll get:
Got here
And then, optionally:
B was finalized
But notice that B survived the full GC cycle, even though you had a reference to it through A.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608226",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Preprocessor token pasting in GCC’s _Pragma operator I’m trying to do something similar to another question, namely, conditionally include OpenMP pragmas in my program. However, I want to go one step further and avoid that the user needs to specify omp every time they use the pragma. In other words, I want the following code to compile:
#include <cstdio>
#include <omp.h>
#ifdef _OPENMP
# define LIB_PRAGMA_OMP(x) _Pragma("omp " #x)
#else
# define LIB_PRAGMA_OMP(x)
#endif
int main() {
LIB_PRAGMA_OMP(parallel) {
std::printf("Hello from thread %d\n", omp_get_thread_num());
}
}
Unfortunately, this doesn’t work. The compiler complains:
error: _Pragma takes a parenthesized string literal
If I use the following form, it works, though:
#define LIB_PRAGMA_OMP(x) _Pragma(#x)
…
LIB_PRAGMA_OMP(omp parallel) …
However, I’d really like to avoid this redundancy. How can I paste the (stringified) tokens correctly inside the _Pragma operator?
A: After much trial and error, it turns out that the simplest solution works:
#ifdef _OPENMP
# define LIB_PRAGMA_OMP(x) DO_PRAGMA(omp x)
# define DO_PRAGMA(x) _Pragma ( #x )
#else
# define LIB_PRAGMA_OMP(x)
#endif
With -DOPENMP, I get:
# 12 "test_op.cpp"
#pragma omp parallel
# 12 "test_op.cpp"
And without it, nothing.
A: #define MAKE_STRING(x) #x
#define LIB_PRAGMA_OMP(x) _Pragma(MAKE_STRING(omp x))
Also works, if you prefer that. I like it better because it minimizes the amount of work this helper function does.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: DB select two Tables I've searched around and can't seem to understand how to get this to work. At least, not the way my code is written. What im having trouble doing is changing this:
// ...
$sql3 = new db;
$sql3->db_Select(DB_TABLE_ROSTER_TEAM_MEMBERS, "*", "team_id = ".intval($row1['team_id'])." ORDER BY member_team_order");
while($row3 = $sql3->db_Fetch()) {
// ...
...to something that orders by the column status_order, which is located in a different table DB_TABLE_ROSTER_MEMBER_STATUS. So essentially I'm trying to include 2 tables in the same SELECT query, so that I can change the ORDER BY. Can anyone explain how this is done? Any help would be greatly appreciated. Thank you.
UPDATE
I'm going to try and explain this as much as I can. Hopefully someone will be able to explain to me in a way I can understand.
By default, this code is meant to grab the users and place them in their respective "team_id", then order them by a selectable drop down box that allows me to change the order. However, the part that orders the members is not working, so I decided I wanted to have it automatically order by the member status that is located in the other table. The other table holds the team names and team order, along with other data that is not needed right now. I didnt even know if this was possible.
There is another code a little further down that may help as well, as it shows the structure of the table. It's what gives the names color as seen on the site I mentioned.
Hopefully I've helped explain it a bit more.
And some more requested by Johan
Here is the structure of the two tables.
roster_team_members fields:
member_id
member_name
team_id
team_name
game_id
game_name
member_team_status
text_color
member_team_order
roster_member_status fields:
status_id
status_name
text_color
status_order
display
Iv decided to fix the manual member order. iv found an error while debugging. if i cant figure out how to fix it il pot another question. thank you all for your help. iv just decided to go another route that should prove to be easier.
A: What does your db_select() method look like? Are you using Drupal?
Your raw SQL query would look something like this:
SELECT table1.* FROM table1, table2 WHERE table1.link_column = table2.link_column AND table1.team_id = 'Your team ID' ORDER BY table2.member_team_order
Without knowing exactly how your db_select() method works I can't tell you exactly how to do this.
A: Try this query:
select a.*,b.rank
from DB_TABLE_ROSTER_TEAM_MEMBERS a INNER JOIN DB_TABLE_ROSTER_MEMBER_STATUS b
ON a.member_id = b.member_id
order by b.rank;
I've had to make a guess that the linking column between DB_TABLE_ROSTER_TEAM_MEMBERS and DB_TABLE_ROSTER_MEMBER_STATUS is called 'member_id' and that the column that you wish to rank by in the DB_TABLE_ROSTER_MEMBER_STATUS is called 'rank'.
A: In order to join two tables you use a join clause.
Something like:
SELECT booking.`date`, customer.name
FROM booking
INNER JOIN customer ON (customer.id = booking.customer_id)
WHERE customer.name = 'Sarge'
ORDER BY booking.`date` DESC
If you have to tables with the same layout you can use a UNION.
SELECT customer_USA.name, customer_USA.country
FROM customer_USA
UNION ALL
SELECT customer_NL.name, customer_NL.country
FROM customer_NL
This will merge all records for both tables in one big resultset.
I'd give you the proper query for your case, but I have no idea what you want and the links you've provided require too much study, killing the fun of the puzzle.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608234",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Intercepting GWT RequestFactory requests Is there a way to intercept RequestFactory requests on client side?
I want to intercept calls like this:
dummyRequest.dummyOperation().fire( new Receiver<String>() {
@Override
public void onSuccess(String response) {
}
});
The idea is to show some loading indication when communicating with server.
A: You can override the default transport implementation and pass it during RF initialization:
SampleRequestFactory factory = GWT.create( SampleRequestFactory.class );
factory.initialize( new SimpleEventBus(), new DefaultRequestTransport() );
You can inherit from DefaultRequestTransport and override the method
send(String payload, TransportReceiver receiver)
Do some processing before calling the super-implementation and wrap the TransportReceiver with a delegate to handle the result.
A: final DefaultRequestTransport requestTransport = new DefaultRequestTransport() {
@Override
public void send(final String payload, final TransportReceiver receiver) {
GWT.log("making rpc");
final TransportReceiver proxy = new TransportReceiver() {
@Override
public void onTransportFailure(final ServerFailure failure) {
GWT.log("rpc returned");
receiver.onTransportFailure(failure);
}
@Override
public void onTransportSuccess(final String payload) {
GWT.log("rpc returned");
receiver.onTransportSuccess(payload);
}
};
super.send(payload, proxy);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: Smooth scrolling in Delphi For years I have been using smooth-scrolling plugins in my browsers (firefox/chrome).
They give a precise feel both for the eye and for navigating.
No line by line flickering.
Is this functionality possible in the Delphi editor ?
Or for that matter in any of the VCL controls TMemo/TStringGrid/TTreeView etc ?
I know that in TVirtualTreeView it is possible to scroll by pixels.
A: The RichView package offers some options that you may like such as TRichView. Also, with XE2 you can set items to be Double Buffered ExampleItem.DoubleBuffered := True; which helps smooth things out.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608242",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Jquery Show/Hide In a .net Datalist I have a .net Datalist returning news articles what I want to happen is for only the headlines to show and then when you click the headline link the body to show.
This is what I have so far
HTML
<asp:DataList ID="dlNewsArticles" DataSourceID="SqlDataSourceNewsArticles" runat="server">
<ItemTemplate>
<div class="news">
<strong><a class="trigger" href="#"><%#Eval("Headline") %></a> </strong><br />
<div class="newsarticle"><%#Eval("ArticleBody") %></div>
<br /><br /><br />
</div>
</ItemTemplate>
</asp:DataList>
Javascript
(function ($) {
$(document).ready(function () {
$('.newsarticle').hide();
$('a.trigger').click(function () {
$(this).next("div").slideToggle();
});
});
})(jQuery);
The only part that seems to work is the hiding of the .newsarticle divs on load.
Am a complete Noob when it comes to Jquery so any pointers will be gratefully recieved
Cheers
A: Your selector is not quite right. Try -
(function ($) {
$(document).ready(function () {
$('.newsarticle').hide();
$('a.trigger').click(function () {
$(this).parents(".news").children(".newsarticle").slideToggle();
});
});
})(jQuery);
That should find the parent 'div' of the clicked link that has a news class, then find the child item of that din that has the 'newsarticle' class.
A: The next() function will return the next element after the a. I assume that it is finding the <br/>, which doesn't match the "div" selector and so nothing is returned.
I would use something like
$(this).parent().siblings("div").slideToggle();
That would go to the parent element of the link, strong in this case, then find the siblings of the strong element that are divs, which would find the one that you are looking for
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608244",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Not able to overwrite kml file I generate KML files on-the-fly.After generating, I call Google maps like this :
http://maps.google.com/maps?q=http://<my ip>:8081/<location>/<name>.kml . The name of the file I use is based on the lat/long of the starting location entered by the user. Obviously, when the location is same, a new kml file is generated starting from the same location. Under such circumstances, the old one should be overwritten, which it is. But, when its given to google maps, Google maps shows the old file . Am attaching snippets from two sample files and python code to illustrate the situation :
import sys
import simplekml
kml=simplekml.Kml()
data=open(sys.argv[1],'r')
for line in data:
points=line.split(' ')
#speed=float(points[9])*3.6
poly=kml.newpolygon(description=("Segment number"+str(points[0])),outerboundaryis=[(float(points[2]),float(points[1])),(float(points[4]),float(points[3])),(float(points[6]),float(points[5])),(float(points[8]),float(points[7]))])
poly.polystyle.outline=0
kml.save("overwrite1.kml")
I call this code sample twice, with two different files, snippets of which are posted below.
File 1:
90 17.44868272235051 78.35992655187812 17.448697277638573 78.35983344811831 17.448738277640214 78.35984044810797 17.44872372234887 78.35993355188845
91 17.4486465880062 78.35986774305402 17.448733411989906 78.35989225695096 17.448203411899485 78.36194225741018 17.448116588096628 78.36191774259473
92 17.44811737513277 78.36191508602762 17.44820262486316 78.3619449139783 17.447872624807378 78.36297491419779 17.447787375188554 78.36294508580814
93 17.44778593144203 78.36295056347981 17.447874068554235 78.36296943652408 17.44777406853705 78.36347943664289 17.44768593145922 78.36346056336097
94 17.447725298386487 78.3635168529482 17.44773470160246 78.36342314704976 17.448464701620733 78.36350314686737 17.448455298368216 78.36359685313049
95 17.44844964150418 78.36359591532924 17.44847035848529 78.36350408466528 17.44916035852647 78.36367408449023 17.449139641463 78.36376591550432
96 17.44914388953053 78.36376671292972 17.44915611045848 78.36367328706736 17.450066110488546 78.36380328683892 17.45005388950045 78.36389671315817
97 17.45007148384362 78.36389560619496 17.450048516146023 78.36380439381118 17.45084851609243 78.36358439360971 17.450871483897217 78.36367560639643
98 17.4508625677922 78.36367697298195 17.450857432196702 78.3635830270191 17.451527432187646 78.36354302685181 17.451532567801255 78.36363697314921
99 17.45152818002525 78.3636369943884 17.45153181996366 78.36354300561091 17.454841819995337 78.36368300478371 17.45483817999356 78.36377699521559
File 2:
17473 17.44436514856338 78.47057386682884 17.444454851433058 78.47056613316957 17.444460851434094 78.470642133188 17.444371148562336 78.4706498668104
17474 17.496817749620345 78.3936639958953 17.496902250375502 78.39369600411102 17.496642250331544 78.39444600426742 17.49655774966431 78.39441399573903
17475 17.471726433843678 78.56706897439275 17.471793566150335 78.5671310256177 17.471353566083877 78.56765102565059 17.47128643391013 78.5675889743598
17476 17.47585253344295 78.56776331893766 17.47588746654784 78.56767668105347 17.476727466633236 78.56804668087453 17.476692533357554 78.56813331911657
17477 17.47712250351409 78.56712330514262 17.477157496476696 78.56703669484854 17.47860749662435 78.56767669454003 17.47857250336645 78.5677633054511
17478 17.478630673594786 78.56773989598412 17.47854932640072 78.56770010402349 17.478849326351025 78.5670301041477 17.478930673644467 78.56706989586
17479 17.478886419731488 78.56709693560659 17.478893580257395 78.56700306439186 17.479253580264213 78.56703306430197 17.479246419724667 78.56712693569652
17480 17.47929464334328 78.56708587636851 17.47920535665311 78.56707412363394 17.479505356601035 78.5645841242342 17.479594643395355 78.5645958757682
17481 17.48534674355407 78.56693717788423 17.485433256442004 78.56696282212097 17.485083256382193 78.56825282240784 17.484996743613884 78.56822717759738
17482 17.485021447069396 78.56828279163804 17.485058552921615 78.56819720835271 17.485248552941915 78.56828720831444 17.4852114470491 78.56837279167631
Snippet from first kml file:
<tessellate>0</tessellate>
<extrude>0</extrude>
<coordinates>78.363676973,17.4508625678,0.0 78.363583027,17.4508574322,0.0 78.3635430269,17.4515274322,0.0 78.3636369731,17.4515325678,0.0</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
<styleUrl>#stylesel_98</styleUrl>
<visibility>1</visibility>
<open>0</open>
<description>Segment number98</description>
</Placemark>
<Placemark id="feat_200">
<Polygon id="geom_198">
<tessellate>0</tessellate>
<extrude>0</extrude>
<outerBoundaryIs>
<LinearRing>
<tessellate>0</tessellate>
<extrude>0</extrude>
<coordinates>78.3636369944,17.45152818,0.0 78.3635430056,17.45153182,0.0 78.3636830048,17.45484182,0.0 78.3637769952,17.45483818,0.0</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
<styleUrl>#stylesel_99</styleUrl>
<visibility>1</visibility>
<open>0</open>
<description>Segment number99</description>
</Placemark>
</Document>
</kml>
Snippet from 2nd kml file:
<tessellate>0</tessellate>
<extrude>0</extrude>
<coordinates>78.5669371779,17.4853467436,0.0 78.5669628221,17.4854332564,0.0 78.5682528224,17.4850832564,0.0 78.5682271776,17.4849967436,0.0</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
<styleUrl>#stylesel_98</styleUrl>
<visibility>1</visibility>
<open>0</open>
<description>Segment number17481</description>
</Placemark>
<Placemark id="feat_200">
<Polygon id="geom_198">
<tessellate>0</tessellate>
<extrude>0</extrude>
<outerBoundaryIs>
<LinearRing>
<tessellate>0</tessellate>
<extrude>0</extrude>
<coordinates>78.5682827916,17.4850214471,0.0 78.5681972084,17.4850585529,0.0 78.5682872083,17.4852485529,0.0 78.5683727917,17.485211447,0.0</coordinates>
</LinearRing>
</outerBoundaryIs>
</Polygon>
<styleUrl>#stylesel_99</styleUrl>
<visibility>1</visibility>
<open>0</open>
<description>Segment number17482</description>
</Placemark>
</Document>
</kml>
Snapshot of the kml file generated , same in both cases :( : [I cleared the cache even,before making the 2nd request]:
Thanks . ( sorry for the long description. But, I hope they make things clear)
A: A google query on Google Maps Caching KML seems to indicate that Google are caching KML files for about 5 minutes.
A simple solution is to add a random query to your URL, so instead of linking to http://maps.google.com/maps?q=http://<my ip>:8081/<location>/<name>.kml, you would link to http://maps.google.com/maps?q=http://<my ip>:8081/<location>/<name>.kml?rnd=<somerandomvalue>
Your web server will ignore it, but Google will think it's a new URL and refetch it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608246",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is dp the same as dip?
Possible Duplicate:
Difference of px, dp, dip and sp in android
I've found several topics on this. But none really answers my question.
Dp and dip in android. What is the difference? Is it the same thing?
A: Yes, they are the same. There is no difference, its just an alias.
Documentation:
The compiler accepts both "dip" and "dp", though "dp" is more consistent with "sp".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608251",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "101"
}
|
Q: C++ populating vectors inside class constructors I have troubling addressing elements inside objects of Class3, please look at this simplified classes:
class Class1 {
public:
std::vector<Class2> c2v;
Class1();
};
class Class2 {
Class1 *instance;
int id;
public:
std::vector<Class3> c3v;
Class2 ( Class1 *instance, int id );
};
class Class3 {
Class1 *instance;
int id;
public:
Class3 ( Class1 *instance, int id );
};
And their constructors:
Class1::Class1()
{
for ( int i = 0; i < noi; ++i ) {
c2v.push_back ( Class2 ( this, i ) );
}
}
Class2::Class2 ( Class1 *instance, int id )
{
this->instance = instance;
this->id = id;
for ( int k = 0; k < nok; ++k ) {
c3v.push_back ( Class3 ( this->instance, k ) );
}
}
In main() an object of Class1 is instantiated with its default constructor. Therefore it creates a vector c2v and fills it with 'noi' objects of Class2.
At the same time, when the objects of Class2 are being put into c2v vector, they're instantiated and each one creates a vector c3v and fills it with 'non' objects of Class3.
The code compiles fine but at runtime when accessing public attributes of Class2 from Class3 objects (via this->instance->c2v[0].getSomeAttribute()) the program stops with a EXC_BAD_ACCESS.
Inspecting with a debugger shows that the pointer to c2v[0] gets corrupted (its value becomes 0x0).
I'm a newbie of C++ I was wondering what is the error when trying to instantiate vectors this way. Should I only declare the vectors and populate them in a separate function called after the creation of all instances of Class2 and Class3 is finished?
I'm adding some actual code, hope it won't be too long to read (please understand I've omitted some forward declarations and preprocessor directives):
// global variables
extern char *filename; //not used
extern int nodes;
extern int numProdotti;
extern int classe; //not used
extern int maxNumRange; //not used
extern int *numRanges;
extern int *list ;
extern int *typeProdMarket;
extern int totalQtyDemand; //not used
extern int totNumRanges; //not used
extern struct product {
int qty;
int cost;
} **prodMarket;
extern struct range {
int discount;
int startOfRange;
} **rangeMarket; //not used
int main ( int argc, char *argv[] )
{
Ctqd instance;
instance.runOpt();
}
class Ctqd {
void greedySimple();
void greedySimpleReverse();
void greedyFromY();
void greedyByNiceness1();
void greedyByNiceness2();
void greedyByStepTier1();
void greedyByStepTier2();
void randomLocalSearch1();
void LocalSearch2opt();
public:
std::vector<Item> items;
std::vector<Supplier> suppliers;
Solution *solution;
Ctqd();
~Ctqd();
void runOpt();
};
class Supplier {
Ctqd *instance;
int id;
int refTotQty;
int refDiscount;
int refDiscountTier;
double refTotPrice;
double refUnitPrice;
double niceness;
int purTotQty;
int purDiscount;
int purDiscountTier;
public:
std::vector<Offer> offers;
Supplier ( Ctqd *instance, int id );
int getId();
int getRefTotQty();
int getRefDiscount();
int getRefDiscountTier();
double getRefTotPrice();
double getRefUnitPrice();
double getNiceness();
int getPurTotQty();
int getPurDiscount();
int getPurDiscountTier();
void updateStats();
};
class Offer {
Supplier *supplier;
int id;
int refQty;
double refPrice;
double niceness;
int purQty;
public:
Offer ( Supplier *supplier, int id );
int getId();
int getRefQty();
double getRefPrice();
double getNiceness();
int getPurQty();
void setPurQty ( int qty );
int remainingQty();
};
Ctqd::Ctqd()
{
// constructing items vector
for ( int k = 0; k < numProdotti; ++k ) {
items.push_back ( Item ( this, k ) );
}
// constructing suppliers vector
for ( int i = 0; i < nodes; ++i ) {
suppliers.push_back ( Supplier ( this, i ) );
}
// building solution
solution = new Solution ( this );
}
Supplier::Supplier ( Ctqd *instance, int id )
{
this->instance = instance;
this->id = id;
// computing total reference quantity
refTotQty = 0;
for ( int k = 0; k < numProdotti ; ++k ) {
refTotQty += std::min ( list[ k ] , prodMarket[ this->id ][ k ].qty );
}
// computing reference discount coefficients
refDiscount = 0;
refDiscountTier = 0;
for ( int r = 0; r < numRanges[ this->id ]; ++r ) {
if ( refTotQty < rangeMarket[ this->id ][ r ].startOfRange ) {
break;
}
else {
refDiscount = rangeMarket[ this->id ][ r ].discount;
refDiscountTier = r;
}
}
//computing total reference price
refTotPrice = 0;
for ( int k = 0; k < numProdotti ; ++k ) {
refTotPrice += prodMarket[ this->id ][ k ].cost * std::min ( list[ k ] , prodMarket[ this->id ][ k ].qty );
}
refTotPrice = refTotPrice * ( 1.000 - refDiscount / 100.000 );
//computing reference unit price
refUnitPrice = refTotPrice / refTotQty;
//computing supplier niceness
niceness = refTotQty / refUnitPrice;
purTotQty = 0;
purDiscount = 0;
purDiscountTier = 0;
// building offers vector
for ( int k = 0; k < numProdotti; ++k ) {
offers.push_back ( Offer ( this, k ) );
}
}
Offer::Offer ( Supplier *supplier, int id )
{
this->supplier = supplier;
this->id = id;
// computing reference quantity
refQty = std::min ( list[ this->id ] , prodMarket[ this->supplier->getId() ][ this->id ].qty );
// computing reference price
refPrice = prodMarket[ this->supplier->getId() ][ this->id ].cost * ( 1.000 - this->supplier->getRefDiscount() / 100.000 );
// computing niceness of the offer
niceness = refQty / ( ( prodMarket[ this->supplier->getId() ][ this->id ].cost + refPrice ) / 2 );
// init purQty to 0
purQty = 0;
}
This is where I get the EXC_BAD_ACCESS:
int Offer::remainingQty()
{
return prodMarket[ supplier->getId() ][ id ].qty - purQty;
}
I've done some experiments:
Changed the vectors in the Ctqd class and in the Supplier class to vectors of pointer to objects.
Problem was solved only partially.
Still had a EXC_BAD_ACCESS when constructing the offers objects.
The constructor for Offer class needs data from the Supplier object that created it.
I thought that accessing that data while the suppliers vector was still being populated could lead to problems, so I created a little initialize() function in the supplier:
void Supplier::initialize()
{
// constructing offers vector
for ( int k = 0; k < numProdotti; ++k ) {
offers.push_back ( new Offer ( this->instance, id, k ) );
}
}
And added this at the end of the Ctqd class constructor:
// init newly built objects
for ( int i = 0; i < nodes; ++i ) {
suppliers[i]->initialize();
}
Now things seem to be working fine. But i still didn't figure out what the problem exactly was.
A: By far the easiest (and best) fix for this is to use std::deque instead of std::vector. You do not need to use pointers; you can stick with your original plan of pushing objects.
With a deque, push_back is guaranteed not to invalidate references to its elements. Same for push_front, actually. And it still supports constant-time random access (foo[n]).
A deque is usually what you want when incrementally building a container full of objects.
As a general rule, std::deque is probably the best data structure you have never used.
A: You're not obeying the rule of 3. You should implement a destructor, copy constructor and assignment operator for all your classes.
Consider the line:
c2v.push_back ( Class2 ( this, i ) );
This will create a temporary object, make a copy of it and put it in the vector. The copy and the temporary object will point via the instance member to the same location. However, when the temporary object is destroyed (right before the next line), that memory is freed and available to use. So now you will have inside your vector an object of type Class2 with an invalid field.
This is just my guess. Please post the code in main if this doesn't help.
A: Change
std::vector<Class2> c2v;
to
std::vector<Class2 *> c2v;
and
std::vector<Class3> c3v;
to
std::vector<Class3*> c3v;
The problem is that you are taking adresses of local objects inside vector. When vector need more space it reallocates his memory and therefore Class2 and Class3 objects having their adresse changed.
class Class1 {
public:
std::vector<Class2 *> c2v;
Class1();
};
class Class2 {
Class1 *instance;
int id;
public:
std::vector<Class3 *> c3v;
Class2 ( Class1 *instance, int id );
};
class Class3 {
Class1 *instance;
int id;
public:
Class3 ( Class1 *instance, int id );
};
Class1::Class1()
{
for ( int i = 0; i < noi; ++i ) {
c2v.push_back ( new Class2 ( this, i ) );
}
}
Class2::Class2 ( Class1 *instance, int id )
{
this->instance = instance;
this->id = id;
for ( int k = 0; k < nok; ++k ) {
c3v.push_back ( new Class3 ( this->instance, k ) );
}
}
And don't forget to cleanup in Class1' and Class2' destructors.
EDIT:
Why such strange behaviour occured:
Step 1
Ctqd::Ctqd()
{
for ( int i = 0; i < nodes; ++i ) {
suppliers.push_back ( Supplier ( this, i ) ); // <-- Supplier's constructor is invoked here
// to construct automatic object of Supplier class
}
}
Step 2. We are inside of the automatic object's constructor:
Supplier::Supplier ( Ctqd *instance, int id )
{
for ( int k = 0; k < numProdotti; ++k ) {
offers.push_back ( Offer ( this, k ) ); // consider that we are passing this to
// Offer's constructor. this is a pointer to
// automatic variable
}
}
Step 3. Back to step 1. But now we have automatic object Supplier created
Ctqd::Ctqd()
{
for ( int i = 0; i < nodes; ++i ) {
suppliers.push_back ( Supplier ( this, i ) ); // <-- automatic object of class Supplier
// is created. Now as long as push_back() taking
// parameter by value yo are passing copy of
// automatic object to push_back();
// as long as you didn't define copy constructor
// for Supplier compiler adds default for you.
}
}
Step 4. Copy of automatic object is saved to suppliers vector. New object (copy of automatic object) has vector offers with exactly same values as our automatic object had (thx to vector's copy constructor). So each object has member supplier that points to... (geass what :)) correct! they all point to automaic object.
Ctqd::Ctqd()
{
for ( int i = 0; i < nodes; ++i ) {
suppliers.push_back ( Supplier ( this, i ) ); // <-- magic here
}
}
Step 5. Automatic object has been destructed(remember how you passed point to this object to Offer's constructor?). Oops you say.
Ctqd::Ctqd()
{
for ( int i = 0; i < nodes; ++i ) {
suppliers.push_back ( Supplier ( this, i ) );
// <-- automatic doesn't exist no more
}
}
So what will happen if one of the supplier's methods gonna try to access Supplier object via supplier member (that we, smart kids, know points to dead object... so sad... QQ). Guess. I believe it will die by realising he sees dead object first time in his life ;).
A: For starters, your code won't compile: when the compiler encounters the
declaration of Class1::c2v, Class2 is an unknown symbol. If I add
the forward declarations (and a definition of noi), it still contains
undefined behavior, and doesn't compile with g++, at least not with the
usual options. It's illegal to instantiate a standard template with an
incomplete type. Since your types have a cyclic dependency, you're
going to have to use pointers somewhere.
Also, what happens to the pointers in Class2 and Class3 when the
objects are copied (and std::vector will copy). From the comment you
made (Class2 represents suppliers, and Class3 represents offers),
these classes should probably be noncopyable. This depends a lot on the
design, but in most cases, entity classes, which model the problem
domain, should be noncopyable. This too leads to using pointers to
them, rather than copies. (Reference semantics, rather than value
semantics.)
Of course, using pointers does introduce issues of object lifetime.
You'll have to decide when and how suppliers and offers come into
existence, and when they cease to exist. This should be part of your
design.
A: Whereas the relocation of the vector's contents and the copying of Class2 or Class3 objects shouldn't give any problems (in contrast to what other answers may state), the problem arises when you create a local object of Class1 and copy this around. When you now try to access the original Class1 object by one of the instance pointers, this object may already have been destroyed and therefore the access to one of its members causes a segfault.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608256",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to persist child entity in SEAM using EnitityHome persist method? I have two entity with a relationship of one-to-one namely Customer and CustomerDetails mapped on their specific tables.
I have a form in the page that captures each values to the property of each Entity.
How am i going to persist this in SEAM?
since my command button only points to one action method which the CustomerHome.persist()
What i did is to assign the value in my form to the property of CustomerDetails like
value="#{customerHome.intance.customerDetails.address}"
but i am getting error that customerDetails resolve to null.
another work arround is to have two persist method in my CustomerHome persist method that persist both entities but i am getting another error that the ID of the CustomerDetails must be assign first before call to save.
Is there anyone who can make this things clear to me?
I am completely new SEAM.
A: If you've copied that code directly from your IDE, then the typo is probably the cause of your problems:
value="#{customerHome.intance.customerDetails.address}"
should be
value="#{customerHome.instance.customerDetails.address}"
A: Do you use seam-gen?
Try to look at project generated by seam-gen
They use a "wire" method to initialize relations.
Basically on creating your instance you make sure that all relations point to their respective fooHome.instance objects.
Then in your persist method you call first the persist method of the relation's EntityHome.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608257",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Searchbutton click event When I press enter it works great. However I also want to perform search by clicking the searchbutton in the text box. I added oncommand attribute, it performed the search however after search ended, searchbutton changed into a cross. I clicked the cross it performed the search again. I checked the documentation however could not find any information about how to associate my searchbutton click with search event.
<textbox id="txt1" type="search" searchbutton="true" editable="true"
onkeypress="keyHandler(event);" />
A: First a side-note: Do not process clicks or key presses directly, always use the command event - this makes sure the behavior of the element is consistent with what the user expects.
<textbox type="search"> assumes that performing the same search twice makes no sense. So after performing the search the search button changes into a cross, clicking that cross clears the search text (and triggers a new command event of course). If instead of clicking the cross you change the search text you will get the usual search button again. So your command handler should look at the search text: show default results if the text is empty (search text cleared either manually or by pressing the cross) and perform a new search if the text is non-empty.
A: This solution is mayn't corresponding to your problem but this will give an idea to finsh your task.
XUL Textbox:
<textbox id="textbox" type="search" oncommand="SearchKeyword(this)"/>
Js:
function SearchKeyword(oElem) // Function for search for the characters
{
var filter = document.getElementById("textbox");
filter.setAttribute("value", oElem.value);
document.getElementById("myTodoListTree").builder.rebuild();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608258",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to achieve start sync and stop sync using post method in android? I want to upload array of pictures , array of videos to server which I want do in synchronization. I want to manage this sync as start whenever i needed and stop it whenever i don't want or WiFi or net connection is disconnected.
Please help on this.
Thanks.
A: Your question is not clear enough. I hope this will serve your purpose
http://developer.android.com/reference/android/os/AsyncTask.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608265",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to create label and check box dynamically in javascript? I want to create label and check box dynamically.
when i enter text in text box and give submit button,a check box and label with the text i entered in text box should be created..How to create ?
A: For the label try this:
var newlabel = document.createElement("Label");
newlabel.setAttribute("for",id_from_input);
newlabel.innerHTML = "Here goes the text";
parentDiv.appendChild(newlabel);
A: I think you want this..
//html
<div id="container">
<input id="test" type="text" >
<input value="add" type="button" onClick="add()">
</div>
//js
<script>
var i=0;
function add(){
if (document.getElementById('test').value!='')
{
i++;
var title =document.getElementById('test').value;
var node = document.createElement('div');
node.innerHTML = '<input type="checkbox" id="check' + i + '" name="check' + i + '"><label for="check' + i + '">'+ title +'</label>';
document.getElementById('container').appendChild(node);
}
}
</script>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608266",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "25"
}
|
Q: A fully open-source software LAMP-like stack for GPGPU? There is a lot of open-source options for web developers. For example, the LAMP stack is fully open-source and if you build you software on it you are not dependent on different vendors, proprietary licenses, etc.
Does something similar exist for general-purpose computing on graphics processing units?
CUDA is definitely not open-sourced, OpenCL is just an open standard, but the compiler is proprietary (right?).
Brook? Deprecated Sh?
Anything else?
Does any 'Linux - gcc - video_driver - ?GPGPU' open-source software stack exist?
A: There is PTX backend for LLVM, but to get runnable binary you still need proprietary NVCC compiler, and proprietary nVidia video driver to run it.
BrookGPU and Sh both use shaders as their backend, so they are far from having all capabilities of "real" GPGPU platforms (like CUDA or OpenCL) and, I guess, have poorer performance. And, at least Brook, requires proprietary drivers to run. Also, latest update to Brook project on SourceForge is dated Feb. 2010, so this project is quite dead too.
OpenCL, despite being open standard, indeed have proprietary compilers (in case of nVidia the compiler is bundled with driver, for AMD/ATI and Intel it can be downloaded separately). Of course one can develop free compiler, but as far as I know, right now there is no open hardware GPGPU architecture (at last wide used one: both nVidia and ATI keep their architecture details unavailable to public). And we can be sure that command set is quite different between different architectures, so for each architecture one want to support, one would have to reverse engineer it (and I guess it might violate license agreement, not sure though). I've heard some attempts were made by nouveau team, but with no any visible results.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Images sometimes falling to the bottom of the page in IE I have an issue with images sometimes falling to the bottom of the page when viewing in Internet Explorer.
http://www.comptonandwoodhouse.co.uk/jewellery
http://www.comptonandwoodhouse.co.uk/figurines
home-decor
collectables
bears
fashion
<< also try these links
*
*if you go to one of these pages in IE - just try them all, and then try them again a few times if you don't see it - the images will sometimes have fallen to the bottom of the page. I'm wondering if anyone knows what the problem might be?
Thanks,
Theo.
A: My guess is that the main column gets too wide to float next to the sidebar, which pushes it to the bottom of the page.
I'm not sure why it only happens randomly...could be a css or javascript file doesn't load in time, or maybe your ecommerce system doesn't resize the thumbnails in time.
You could try adding a conditional stylesheet for IE7 and lower that makes the main column a little narrower to compensate:
<![if lt IE 8]>
.product_listing_rt {
float: left;
width: 700px; /* normally 711px */
}
<![endif]>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608276",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I validate that a string value is in the format "\/Date(1239018869048)\/"? How do I validate that a string/JSON value is in the format "\/Date(1239018869048)\/"?
I'm iterating through a JSON object, I know I may have a serialized JSON date string but because the JSON object is dynamic, I don't know which property is the serialized JSON date.
So I want to know if a JSON property value will validate to the format of a JSON serialized date.
Update #1
It would be nice to check if it's an instance of a string before you use the regular expression because an integer will throw an exception. This is in addition to the answer @vzwick gave. Thanks once again.
json_obj = { 'foo' : 'bar', 'baz' : '/Date(1239018869048)/' }
pattern = /^\/Date\((\d*)\)\/$/;
for(e in json_obj) {
if (json_obj[e].constructor === String) {
if (json_obj[e].match(pattern)) {
// date found
}
}
}
Update #2
After tryout different values, i discovered that we have negative numbers. So the pattern can
now look like;
pattern = /^\/Date\((-?\d*)\)\/$/;
A: Here you go, mate:
json_obj = { 'foo' : 'bar', 'baz' : '/Date(1239018869048)/' }
pattern = /^\/Date\((\d*)\)\/$/;
for(e in json_obj) {
if (json_obj[e].match(pattern)) {
// date found
}
}
A: If you mean validate that a string value will serialise into a date, you can use JavaScripts support for regular expressions.
See here http://www.w3schools.com/jsref/jsref_match.asp
If you mean validate that a de-serialised value is a date, you can use Javascripts instanceof operator.
See here https://developer.mozilla.org/en/JavaScript/Reference/Operators/Special/instanceof
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608289",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: use distinct keyword for 3 tables in sql server? I want to use distinct keyword for 3 different tables like intern_data_copy, fresher_data_copy, exp1_data.
These tables have three different columns. Now I want to use join in then and also use use distinct for that column.
select DISTINCT a.sec_s, b.sec_skill, c.sec_sk
from intern_data_copy a
JOIN fresher_data_copy b ON a.fflag = b.fflag
JOIN exp1_data c ON b.fflag = c.fflag
the output comes in distinct format but for every table. if "java" or ".net" is in 2 different table then it is showing 2 times.
if a data like "java" is available in all of three tables than i want to see it only once.
How can I achieve this.
thanks in advance
A: You could try (I am assuming a few things, so this is a guess):
SELECT fflag, a.sec_s
FROM intern_data_copy a
UNION
SELECT fflag, b.sec_skill
FROM fresher_data_copy b
UNION
SELECT fflag, c.sec_sk
FROM exp1_data c
but you must clarify your question if you want to see answers and not guesses.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608294",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iPad shows a wrong state of a website/app after app switch I found nothing related to my problem, maybe I use the wrong keywords. But let me explain:
I have a strange problem with the iPad. We have a little javascript app/website, nothing special. It runs in a native app container via UIWebView. The problem is:
When we open a link (e.g. pdf) in an external safari window and switch back to the app (via four finger gesture or the button) sometimes (not always) we see an old state of the website (e.g. an old div container that should be hidden) until the iPad repaints the window (after a second or something). After the repaint everything is ok, but until this repaint we see something wrong.
We cannot rebuild the problem. It occurs somehow sometimes.
For me it looks like the iPad stores a screenshot of the website until it redraws the DOM, because it does not listen to any events. And sometimes the iPad stores a wrong screenshot?
Is this a known behavior of the iPad/Safari/UIWebView? Or is really a problem with some code in the app container or the website?
A: I am using an iPad and iPhone sometime now with gestures, and this is something that got my attention as well. Even though I am not yet developing apps, I see this happening al the time.
Not only with uiWebView but also with apps like Spotify & TomTom. It always waits for a second or so and then repaints the app correctly, with sometimes an older state then it should have.
I guess this is how iOS works, and nothing really can be done about it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608297",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Custom Class in Zend Framework I'm using Zend Framework with Propel. It's easy enough to use Propel objects as my models for things that are stored in the database, but how do I go about creating a custom model such as a shopping cart that uses propel objects?
I'm thinking of creating a class called CartItem and Cart. If CartItem contains a propel Product class, and Cart contains an array of CartItems, this seems very expensive to store in a session. Normally I'd just use an array, but I'm trying to get better with OOP
A: You could use PHP's Interface Serializable: http://php.net/manual/de/class.serializable.php
You can use it to convert an instance of your cart into a more efficient value (you define, what exactly is stored), which is in your case a two-dimensional array.
Try something like this:
<?php
class Cart implements Serializable {
// your normal code for the Cart class
public function serialize() {
$cartData = array();
foreach($this->cartItems as $item) {
$cartData[] = array(
'count' => $item->getCount(),
'productId' => $item->getId()
);
}
return serialize($cartData);
}
public function unserialize($cartData) {
$this->cartItem = array();
foreach($cartData as $item) {
// replace this with the appropriate propel code
$product = loadProductWithPropelById($item['id']);
$this->cartItems[] = new CartItem($item['count'], $product);
}
}
}
?>
Then use serialize to store the cart in the session and retrieve it:
<?php
// Store cart to session
$_SESSION['cart'] = serialize($cart);
// get cart from session
$cart = unserialize($_SESSION['cart']);
?>
Good Luck with your Project!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608301",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Run a function each time a page loads in CodeIgniter I have previously only made web applications in Asp.Net MVC, and there you can use OnResultExecuted in an "ActionFilter" set on the BaseController to run a method each time an action method is executed (i.e. basically each time anyone visits any page in the application).
How would I do the same thing in CodeIgniter/PHP?
EDIT:
I tried using post_controller_constructor instead, according to one of the suggestions, but that doesn't help:
$hook['post_controller_constructor'] = array(
'class' => 'PreController',
'function' => 'getIp',
'filename' => 'preController.php',
'filepath' => 'hooks'
);
I still get Undefined property: PreController::$input (I just haven't renamed the class called, that shouldn't matter if it is still called PreController for the moment).
But the fact remains I do not have access to the input property... Obviously I don't have access to the Input Class, so how do I do that? I belive if I had done the same thing in a Controller it would have been ok, but from a hook? How do I do this?
A: You can use CodeIgniter hooks for that: http://www.codeigniter.com/user_guide/general/hooks.html
There are several "events" you can hook into, check the bottom of the documentation page.
In response to the comment:
Re-read your comment and edit... it seems that you're assuming that your hook class is the current controller -- it isn't. The current controller is whatever matches the URI/route mapping (for example, site.com/users/view/1 would be using the Users controller, and not your hook handler PreController class). The hook handler can be a simple PHP class not inheriting from CI_Controller.
The first thing you need to do in the hook handler is to get hold of the actual controller, that will contain the Input reference and others.
class HookHandler {
function post_controller_constructor() {
$ci =& get_instance();
// ... now you can use $ci->input and other controller members
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608304",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to get a specific string inside a String delimited by ";"?
Possible Duplicate:
How do I split strings in J2ME?
I have a String data which is like csv , that is there are ";" inside the String data. But in my case there is always a ";" at the end of the String. I want to create a method which gives a String at a certain number from this csv. For example :
String csv = "145557;123456789012;Michael Robert;1000000;200000;;12/05/2011;;" ;
In this String there are 8 "columns". I say "column" the data between two ";" ( the first column is not enclosed by two ";" but only the one at its right ).
In this example the data "Michael Robert" has the number 2 ( or 3 if we start at 1 for the first column ).
So how to get the data ( column ) at a specified number ?
NB : I use Java ME
A: In J2ME you can write a method like this:
public class Main {
public static void main(String[] args) {
String csv = "145557;123456789012;Michael Robert;1000000;200000;;12/05/2011;;" ;
System.out.println(getColumnAt(csv, 0));
System.out.println(getColumnAt(csv, 1));
System.out.println(getColumnAt(csv, 2));
}
public static String getColumnAt(String csv, int column) {
int fromIndex = 0;
int col = 0;
while (col < column) {
fromIndex = csv.indexOf(";", fromIndex) + 1;
col++;
}
int toIndex = csv.indexOf(";", fromIndex);
return csv.substring(fromIndex, toIndex);
}
}
UPDATE: By the way, due to the way that substring is implemented it is better to return new String(csv.substring(fromIndex, toIndex));, otherwise the substring will hold a reference to the original string and then as long as the substring is not GC-able, the original String won't be GC-able as well.
A: just use StringTokenizer:
StringTokenizer tok = new StringTokenizer(yourString,";");
column1 = tok.nextToken();
column2 = tok.nextToken();
...
Here you can find a more complex example.
Regards,
Luca
A: csv.split(";")[2]; // returns "Michael Robert"
This uses the String.split(String delimiter) method, which splits the string around the delimiter, returning an array containing the resulting substrings.
A: Do you mean like this:
public TestClass()
{
String csv = "145557;123456789012;Michael Robert;1000000;200000;;12/05/2011;;" ;
System.out.println(splitString(csv,2));
}
public String splitString(String s, int getValueAt)
{
return s.split(";")[getValueAt];
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608305",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to create xml file for animation in android for diferrent screen size I had created a Transform animation in android using xml.I am running it on larger screen. I had set the value for x and y coordinates in the xml itself.It is running fine on larger screen but when I run it on small screen it works according to the coordinates set for larger screen.How do I set my coordinates so that it works for all the screen size.
A: You should then put a modified version xml with the same name under drawable-mdpi or drawable-ldpi. Android will find its way to use them.
--drawable-hdpi
-- anim.xml
--drawable-mdpi
-- anim.xml
--drawable-ldpi
-- anim.xml
:)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608307",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: security check in matlab I've finished a matlab GUI development.
Now the distribution is under discussion.
Concerning the security, we want to have a authentication prior to running the GUI, to see if the user is in the valid network. Our first proposal is to check network domain/user account as an option.
How can it be achieved with matlab?
Any suggestions are welcome.
Thank you!
A: You can get this kind of informations with getenv, winqueryreg and maybe system and hostid. More generally see Operating System Interface.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608309",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: OSX/Cocoa : Listening for system wide mouse drag events Hi I am new to cocoa programming and would like to know how to create a listener for system wide events (such as mouse drag). I've added this to my app (I saw it on another post):
static CGEventRef eventFunction(CGEventTapProxy proxy, CGEventType type, CGEventRef event, void *refcon)
{
printf("event triggered\n");
return event;
}
But it is never called and im not sure where I am meant to register a call back.
A: The easiest way to watch global mouse events is to use the NSEvent class method addGlobalMonitorForEventsMatchingMask:handler:
Example:
[NSEvent addGlobalMonitorForEventsMatchingMask:NSLeftMouseDraggedMask
handler:^(NSEvent *event) {
NSLog(@"Dragged...");
}];
Note that this only works in other applications, to get those events in your own app, you have to add an additional local event handler.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608314",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: jQuery or other JS to get server time and sync ticking clock and set event launch on exact time I need to fetch exact time from server to client side by jQuery,
tha best approach maybe would be to read the GET headers where the date is formatted like this
HTTP/1.1 200 OK =>
Server => nginx
Date => Fri, 30 Sep 2011 09:10:23 GMT
...
anyone has idea how to read this to jQuery and show client the synced clock running ?
ideally with option to add an event to be launched on defined time exactly ?
please no server side php, just pure JS or jQuery
A: JavaScript cannot access the HTTP headers of the page it is running on, but it can however read the response headers of an XMLHttpRequest object. You can therefore make a GET request to anywhere really, and then access the headers of the response. With jQuery, it's nice and simple:
$.get(document.location, function(data, text, xhr) {
var headers = xhr.getAllResponseHeaders();
});
From there, you will be able to parse the headers to get the date as required.
A: I think it's imposible because javascript are executing on the client side and it's no ability to read response headers in it. So, only server side coding can help you:
*
*You can put this time in hidden field and than show time to user base on fields value.
*Make AJAX call to some handler whitch will return time value. But it's still server side work.
Here is discussion about headers: Accessing the web page's HTTP Headers in JavaScript
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608317",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Crash when parsing protobuf message containing a string using C++ and Android NDK I have two programs, both running on an Android 2.3.4 platform - one is a C++ binary in a daemon form, compiled with cmake, the other is a apk with jni part compiled with ndk-build. I'm using android-ndk-r6. I'm using protobuf messages and local unix sockets to pass data between them. I'm using the SerializeAsString and ParseFromString methods.
Here is a snippet
AbstractMessage protobuff_msg;
protobuff_msg.set_id ( 1 ); //TODO: for now hardcoded, later can be used for request-response pairs
protobuff_msg.set_type ( AbstractMessage_MessageType_REQUEST );
protobuff_msg.set_method ( AbstractMessage_MethodName_LOAD_DEFINITION );
AbstractMessage_Parameter* param = protobuff_msg.mutable_param()->Add();
param->set_name(AbstractMessage_ParameterName_FILEPATH);
param->set_value(filepath);
std::string msg = protobuff_msg.SerializeAsString();
client_->write_protobuf_message ( msg, MAGIC_NUMBER );
AbstractMessage is the protobuf message,
AbstractMessage_MessageType_REQUEST,LOAD_DEFINITION,FILEPATH are enums, AbstractMessage_Parameter is a repeated nested message. The param value is a string, all other types are int-s. client is a custom library for the socket communication.
int Foo::write_protobuf_message(std::string protobuf_msg, int magic_number)
{
int send_int = 0;
send_int = htonl(magic_number);
int n = write_to_socket((void *)&send_int, sizeof(int));
if(n<0)
return -1;
send_int = htonl(protobuf_msg.size());
n = write_to_socket((void *)&send_int, sizeof(int));
if(n<0)
return -1;
n = write_to_socket((void *)protobuf_msg.c_str(),protobuf_msg.size());
return n;
}
The parsing:
void foo ( void* buffer, int buff_size, int error)
{
std::string buffstr;
if (error == 0)
{
buffstr.assign ( ( char* ) buffer, buff_size );
AbstractMessage proto_msg;
bool res = proto_msg.ParsePartialFromString(buffstr);
if (res)
{
//TODO handle ok parsing
return;
}
else
{
//TODO handle failed parsing
return;
}
}
}
This scenario is tested with two c++ daemon binaries as test tools and it works. However when I try the real deal with the apk I get the following crash:
09-30 11:43:28.335: INFO/DEBUG(1044): *** *** *** *** *** *** *** *** *** *** *** *** *** *** *** ***
09-30 11:43:28.335: INFO/DEBUG(1044): Build fingerprint: 'foobar/voles/sholes/sholes:2.2.1/FRG83D/75603:user/release-keys'
09-30 11:43:28.335: INFO/DEBUG(1044): pid: 3991, tid: 4001 >>> com.foo.bar <<<
09-30 11:43:28.335: INFO/DEBUG(1044): signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr deadbaad
09-30 11:43:28.335: INFO/DEBUG(1044): r0 00000027 r1 deadbaad r2 a0000000 r3 00000000
09-30 11:43:28.335: INFO/DEBUG(1044): r4 00000001 r5 00000000 r6 80422d0c r7 0000a000
09-30 11:43:28.342: INFO/DEBUG(1044): r8 44156eb0 r9 44156eb4 10 000ab44c fp 000001f0
09-30 11:43:28.342: INFO/DEBUG(1044): ip afd46668 sp 44156c80 lr afd193b1 pc afd15e80 cpsr 60000030
09-30 11:43:28.342: INFO/DEBUG(1044): d0 6472656767756265 d1 696e6a2f6c6c6173
09-30 11:43:28.342: INFO/DEBUG(1044): d2 4194fc184194fb65 d3 4194fc804194fc74
09-30 11:43:28.342: INFO/DEBUG(1044): d4 4194fce84194fcb4 d5 4194fd504194fd1c
09-30 11:43:28.342: INFO/DEBUG(1044): d6 4194fdb84194fd84 d7 4194fe204194fdec
09-30 11:43:28.342: INFO/DEBUG(1044): d8 0000000000000000 d9 0000000000000000
09-30 11:43:28.350: INFO/DEBUG(1044): d10 0000000000000000 d11 0000000000000000
09-30 11:43:28.350: INFO/DEBUG(1044): d12 0000000000000000 d13 0000000000000000
09-30 11:43:28.350: INFO/DEBUG(1044): d14 0000000000000000 d15 0000000000000000
09-30 11:43:28.350: INFO/DEBUG(1044): d16 00000000405122d8 d17 3fe999999999999a
09-30 11:43:28.350: INFO/DEBUG(1044): d18 42eccefa43de3400 d19 3fbc71c71c71c71c
09-30 11:43:28.350: INFO/DEBUG(1044): d20 4008000000000000 d21 3fd99a27ad32ddf5
09-30 11:43:28.350: INFO/DEBUG(1044): d22 3fd24998d6307188 d23 3fcc7288e957b53b
09-30 11:43:28.350: INFO/DEBUG(1044): d24 3fc74721cad6b0ed d25 3fc39a09d078c69f
09-30 11:43:28.350: INFO/DEBUG(1044): d26 0000000000000000 d27 0000000000000000
09-30 11:43:28.350: INFO/DEBUG(1044): d28 0000000000000000 d29 0000000000000000
09-30 11:43:28.350: INFO/DEBUG(1044): d30 0000000000000000 d31 0000000000000000
09-30 11:43:28.350: INFO/DEBUG(1044): scr 60000010
09-30 11:43:28.514: INFO/DEBUG(1044): #00 pc 00015e80 /system/lib/libc.so (__libc_android_abort)
09-30 11:43:28.514: INFO/DEBUG(1044): #01 pc 00013834 /system/lib/libc.so (dlfree)
09-30 11:43:28.514: INFO/DEBUG(1044): #02 pc 00014726 /system/lib/libc.so (free)
09-30 11:43:28.514: INFO/DEBUG(1044): code around pc:
09-30 11:43:28.514: INFO/DEBUG(1044): afd15e60 2c006824 e028d1fb b13368db c064f8df
09-30 11:43:28.514: INFO/DEBUG(1044): afd15e70 44fc2401 4000f8cc 49124798 25002027
09-30 11:43:28.514: INFO/DEBUG(1044): afd15e80 f7f57008 2106ebce ed7af7f6 460aa901
09-30 11:43:28.514: INFO/DEBUG(1044): afd15e90 f04f2006 95015380 95029303 e8a0f7f6
09-30 11:43:28.514: INFO/DEBUG(1044): afd15ea0 462aa905 f7f62002 f7f5e8ac 2106ebba
09-30 11:43:28.514: INFO/DEBUG(1044): code around lr:
09-30 11:43:28.514: INFO/DEBUG(1044): afd19390 4a0e4b0d e92d447b 589c41f0 26004680
09-30 11:43:28.514: INFO/DEBUG(1044): afd193a0 686768a5 f9b5e006 b113300c 47c04628
09-30 11:43:28.514: INFO/DEBUG(1044): afd193b0 35544306 37fff117 6824d5f5 d1ef2c00
09-30 11:43:28.514: INFO/DEBUG(1044): afd193c0 e8bd4630 bf0081f0 0002816c ffffff88
09-30 11:43:28.522: INFO/DEBUG(1044): afd193d0 b086b570 f602fb01 9004460c a804a901
09-30 11:43:28.522: INFO/DEBUG(1044): stack:
09-30 11:43:28.522: INFO/DEBUG(1044): 44156c40 afd42664
09-30 11:43:28.522: INFO/DEBUG(1044): 44156c44 000a9908
09-30 11:43:28.522: INFO/DEBUG(1044): 44156c48 00000015
09-30 11:43:28.522: INFO/DEBUG(1044): 44156c4c afd18479 /system/lib/libc.so
09-30 11:43:28.522: INFO/DEBUG(1044): 44156c50 afd4270c
09-30 11:43:28.522: INFO/DEBUG(1044): 44156c54 afd426b8
09-30 11:43:28.522: INFO/DEBUG(1044): 44156c58 00000000
09-30 11:43:28.522: INFO/DEBUG(1044): 44156c5c afd193b1 /system/lib/libc.so
09-30 11:43:28.522: INFO/DEBUG(1044): 44156c60 00000001
09-30 11:43:28.530: INFO/DEBUG(1044): 44156c64 44156c94
09-30 11:43:28.530: INFO/DEBUG(1044): 44156c68 80422d0c
09-30 11:43:28.530: INFO/DEBUG(1044): 44156c6c 0000a000
09-30 11:43:28.530: INFO/DEBUG(1044): 44156c70 44156eb0
09-30 11:43:28.530: INFO/DEBUG(1044): 44156c74 afd186d3 /system/lib/libc.so
09-30 11:43:28.530: INFO/DEBUG(1044): 44156c78 df002777
09-30 11:43:28.530: INFO/DEBUG(1044): 44156c7c e3a070ad
09-30 11:43:28.530: INFO/DEBUG(1044): #00 44156c80 00000023
09-30 11:43:28.530: INFO/DEBUG(1044): 44156c84 001533b8
09-30 11:43:28.530: INFO/DEBUG(1044): 44156c88 80422d0c
09-30 11:43:28.530: INFO/DEBUG(1044): 44156c8c 44156cec
09-30 11:43:28.530: INFO/DEBUG(1044): 44156c90 80422d0c
09-30 11:43:28.530: INFO/DEBUG(1044): 44156c94 fffffbdf
09-30 11:43:28.530: INFO/DEBUG(1044): 44156c98 44156eb0
09-30 11:43:28.530: INFO/DEBUG(1044): 44156c9c afd46450
09-30 11:43:28.530: INFO/DEBUG(1044): 44156ca0 44156cec
09-30 11:43:28.530: INFO/DEBUG(1044): 44156ca4 afd13839 /system/lib/libc.so
09-30 11:43:28.530: INFO/DEBUG(1044): #01 44156ca8 80422d0c
09-30 11:43:28.530: INFO/DEBUG(1044): 44156cac 44156cec
09-30 11:43:28.538: INFO/DEBUG(1044): 44156cb0 0000000b
09-30 11:43:28.538: INFO/DEBUG(1044): 44156cb4 00000000
09-30 11:43:28.538: INFO/DEBUG(1044): 44156cb8 44156eb0
09-30 11:43:28.538: INFO/DEBUG(1044): 44156cbc afd14729 /system/lib/libc.so
09-30 11:43:30.382: INFO/BootReceiver(1185): Copying /data/tombstones/tombstone_00 to DropBox (SYSTEM_TOMBSTONE)
If I try to parse only ints (I change the protobuf message to be without a string/bytes) all works great. If i add the string/bytes all fails. I tried also with required and optional string, also with bytes. Nothing works. I found that such a crash my be caused by an assert.
Any ideas?
A: What I can say about your error :
signal 11 (SIGSEGV), code 1 (SEGV_MAPERR), fault addr deadbaad
deadbaad usually means invalid address.. so you most probably have an invalid address in the parsing section..
I would suggest enabling dalvik.vm.checkjni=true and trying to see if you get any further info
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608318",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: How to execute a Method when a User close the Browser or visit another Page? I use c# asp.net 4 web.forms.
I have a page (lets called it X) I need execute a method on X in this situation only:
*
*When User visit another URL, directly input in the Browser or clicking another link on the Page.
*When User Log Out from my Web Application.
*When a User Close the Browser.
At the moment I'm trying Page_Unload Event but as for MSDN "Occurs when the server control is unloaded from memory" and I'm not able to make it works as expected.
Looking in the documentation I cannot find a suitable Event for my Page.
What are the possible alternative solutions? Thanks for your time on this.
A: This simply isn't possible.
HTTP requires browsers to request resources from the server first - without this the server cannot do anything. Closing your browser will not request anything from the server.
Your only option is to use session cookies, which are wiped when the user ends the browsers session, as per MSDN:
When the user closes the browser, the cookie is discarded.
So checking for these on each request will allow the server to know if the user has previously closed the browser.
There are nasty javascript solutions, but these are very much hacks.
A: Have a look at the javascript window.OnBeforeUnload handler :
How can I override the OnBeforeUnload dialog and replace it with my own?
This way you can execute some javascript before the user leaves your page.
A: *
*
When User visit another URL, directly input in the Browser or clicking
another link on the Page
you can do some client side scripting. javascript onbeforeunload Event might help you.
*
*
When User Log Out from my Web Application.
don't see why this is a problem. this sure is a server side event, isn't it?
*
*
When a User Close the Browser
that's a problem. what should happen in a case of power failure? or browser crash? or...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608320",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android - Cant access TextView within a Timer in a Service Im facing the following problem:
public class StatCounterService extends Service {
private TimerTask updateTask_ref = new TimerTask() {
//Get the element by Id as common practice in Android
TextView hungerValue_ref = (TextView)layout.findViewById(R.id.hungerValue);
@Override
public void run() {
//Every X Seconds, the Tamagotchi loses Hunger Points
int hunger = (int) (getHunger()-1);
//Updating Model (DataBase)
updateHunger(hunger);
//Now I want to update the TextView, but this hungerValue is Null
hungerValue_ref.setText(new Long(getHunger()).toString());
}
};
}
I think the problem is, Im looking for the ID of the View inside a Service, also inside a nested Class (the timertask). The Service is running, i just get a nullpointer on the "hungerValue". Any Ideas how I could solve this?
thanks a lot!
Daniel
EDIT: I now try to update the view in the Timer from the activity, here is the idea:
public class MainWindowActivity extends Activity {
Timer timer_ref;
TextView hungerValue_ref;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Change the View I want to change initally (getting Value from Database)
updateHungerView();
//Start Timer
timer_ref = new Timer("StatCounterTimer");
timer_ref.schedule(updateTask_ref, 1000L, 10000L);
}
//The Timer from within I want to change the View every X seconds
private TimerTask updateTask_ref = new TimerTask() {
@Override
public void run() {
//Line Throws Exception, see Method below
updateHungerView();
}
};
/**
* Important Part
*/
public void updateHungerView() {
hungerValue_ref = (TextView) findViewById(R.id.hungerValue);
hungerValue_ref.setText(new Long(getHunger()).toString());
}
when I try to change the view from my activity, I get this:
09-30 11:54:48.967: ERROR/AndroidRuntime(30476): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
A: You're trying to work with a component part of a layout from inside a service but you can only work with the layout from inside the associated Activity. The service has no knowledge of if the activity is on top when it executes its code - the Activity instance might not even exist yet.
The best approach for allowing a service to cause the display to update is to broadcast an Intent from the service:
Intent intent = new Intent();
intent.setAction("my.intent.action.name");
sendBroadcast(intent);
Then, in your Activity, you create a BroadcastReceiver instance to process the intent.
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("my.intent.action.name")) {
// do something with the UI here
}
}
};
You'll also need to register your broadcast receiver in your onResume() method:
IntentFilter filter = new IntentFilter("my.intent.action.name");
registerReceiver(receiver, filter);
And unregister it in your onPause() method:
unregisterReceiver(receiver);
You can't use a static inner class for your BroadcastReceiver instance because it won't be able to do things like:
MyActivity.this.getContext()
or
MyActivity.this.findViewById(R.id.my_ui_component)
Hope that helps!
A: Consider using an AsyncTask rather than Service. Since you cannot update UI in Background
http://developer.android.com/reference/android/os/AsyncTask.html
A: I think this is a common problem with android. The findViewById is relative to a layout and must be called after setContentView if I remember well. This could help you :
http://www.anddev.org/solved_why_does_findviewbyid_return_null-t557.html
A: To me it appears that you're trying to find and update a TextView which might not be visible/inflated (e.g. it's holding Activity has been destroyed/stopped/paused).
I'm guessing you want to use a service, because it can keep running even if your App gets pushed to the background or gets killed. I think however in your situation a change in the your design might be preferable.
Instead of having a Service running - save a timestamp as soon as your app gets paused (in the onPause()-method of the visible activity). Then when the user resumes the App (the onResume-method will be called) you calculate the time between the previously saved timestamp and current time and decrease the hpvalue based on this. Then update the TextView from the holding activity.
You could also consider using an AsyncTask - if the hpvalue only needs updating when the App is active.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608321",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Restrict installation to multitasking-capable devices? Is there a way to restrict the installation of my app to allow only multitasking-capable devices?
My app needs to do some background task (finish a download in the background when minimized).
I could work around it (abort the task and start over next time), but that would add complexity (and bugs), and I can do without supporting the iPhone 3G/equivalent iPod Touch.
The .plist file lets you set required device capabilities (OpenGL ES 2.0, etc.), but multitasking is nowhere to be found.
I could set the minimum deployment target to iOS 4.3, but I don't want to miss on iPhone 3GS/iPhone 4 users who aren't savvy enough to upgrade their OS and might still be on 4.2 or less.
Any ideas?
EDIT: I found this discussion
Exclude devices that do not support multitasking
...So it seems the best way is to limit support to only armv7 CPUs.
A: As suggested on my own edit, it seems that there is no 'required device capability' that corresponds exactly to multitasking-capable devices.
However, these very same devices just happen to be exactly the same ones that support OpenGL ES 2.0, and that is in the list of device capabilities you can specify in your Info.plist file. But this is at most a (perfect) work-around.
The correct thing to do would be to set a deployment target of 4.3, since only multitasking-capable devices can run that OS. However, it is possible that some multitasking-capable device might still be running iOS 4.2 or less. This is less of a concern as iOS 4 becomes older: in the verge of the iOS 6 release, a few months from now, dropping support for iOS 4.x altogether is a more viable option.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608323",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Javascript function and PHP session variable I have the following script in my Body Tag inside a PHP page:
<script type="text/javascript">
function goNext()
{
<?php
if(isset($_SESSION['current']))
{
?>
window.location="step2.php";
<?php
}
else
{
?>
alert('Please select one item to continue.');
<?php
}
?>
}
</script>
I am setting the session vaible in PHP.
So when I click a link on the page, the session is set.
After that, when I call this function, it still goes to the Alert.
If I refresh the page, then it skips the alert and forwards to the URL mentioned in the function.
Any idea why while I have not refreshed the page, it does not go to the URL?
Update
I am already setting the Session_start at the begining of the page.
The session is getting set properly, because when I refresh, I can see it working.
Thirdly, I am already using AJAX to set sessions without doing page refresh.
There are other elements on the screen that respond to session change and they are working.
Its only this function where the "issset" function is not detecting the session.
A: That is not how AJAX works. You have to keep your PHP and Javascript separate. Use PHP to write your page from the server. The javascript will make AJAX calls back to the server where you will answer them with the PHP. You'll need a tutorial to find out how to make the AJAX request - which will depend on whether you are using plain old javascript or a libarary such as jQuery or Mootools.
Edit: I am not sure exactly what you are trying to do, but I'm going to try to put what I think you want to do. (Note: I have never used jQuery so this is a big guess and is only pseudo-code - hopefully the idea is useful).
<script type="text/javascript">
function goNext()
{
// Get the session from the server (via an AJAX call).
$.get("getSession.php", function(sessionFromServer)
{
// Do stuff depending on the value of sessionFromServer
// However, it seems odd that the php isn't doing this with
// header("location: step2.php");
window.location = "step2.php";
});
}
</script>
getSession.php - something like this:
<?php
session_start();
echo json_encode($_SESSION);
?>
This gives you an idea of what i mean by separating them.
A: why don't you just simplify it with a header?
<?
if(isset($_SESSION['current'])) {header("location: step2.php"); exit;}
?>
A: Because the difference between serverside and clientside. Javascript executes in the browser, after the PHP script is executed on the server.
I don't exactly know what you're trying to do, but AJAX might be the answer.
A: You'll need to use an AJAX call to set and store the session value. You could then redirect within the PHP code using header('Location: step2.php').
A: dont forget session_start() at the top (or be sure that you have session auto start)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608334",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: 2-adic number of given integer i am reading section about A Binary Recursive Gcd Algorithm,where this definition is given
let v_2(a) denotes the 2-adic valuation of a, i.e. the number of consecutive zeroes in the least signicant bits of the binary representation of a ,so i am trying to find v_2(a) here is code for this
#include <iostream>
using namespace std;
int main()
{
int total=0;
int n,k;
cout << "enter value n ";
k=0;
cin >> n;
while(k!=1)
{
if (k==1)
{
break;
}
k=n%2;
n>>=1;
total++;
}
cout<<total<<" "<<endl;
return 0;
}
when i enter number 12 (in binary it is 1100) it should give me number 2 but it shows 3,what is wrong?please help me
A: You're breaking out of the while too late, since you're running total++ when k==1 has been reached.
Move the if (k==1) block after the k=n%2; line.
Note: The k variable isn't actually necessary. You could simplify the loop to:
while((n%2)==0) {
n>>=1;
total++;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608337",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Placing ads in my android app I am planning to create an android application that may contain some ads. The ads shall be pushed from a web site that hosted in my server. I can push different ads from my server and the users of the application can be able to like, dislike the ads. Based on the user's like/dislike input I can create a rating for the product.
Have anybody did the same things before.
Is there any specific controls in the android stack for this? Can I use Android App widget for this?
A: I dont think you need more than a custom ad view , a db and network calls.
The whole idea I think it would be:
*
*create the ad view with buttons.
*onButtonPressed() stores the like or dislike value to the db
*and fire the server sync.
Android Widget is limited, but it can do these simple things too.
:)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: AS3 - How can I dispacth an Event.CHANGE from an Array/Vector? I would like to subclass an Array or Vector to dispatch and Event.CHANGE when any elements value changes.
How would I go about doing this?
A: How about using an ArrayCollection and listen to the CollectionEvent (mx.events.CollectionEvent.COLLECTION_CHANGE)
/**
* Dispatched when the ICollectionView has been updated in some way.
*
* @eventType mx.events.CollectionEvent.COLLECTION_CHANGE
*
* @langversion 3.0
* @playerversion Flash 9
* @playerversion AIR 1.1
* @productversion Flex 3
*/
[Event(name="collectionChange", type="mx.events.CollectionEvent")]
A: There is two ways of approaching it, if you want to create your own collection:
1) Extend Array class, and use method like updata(index:int, value:*) to update data in it instead of array accessors (myArray[i] = newValue). And in update method you can dispatch change event. This might make your code less concise.
2) Extend Proxy and override setProperty and getProperty methods in flash_proxy namespace. This will allow you to use array access operators ([key]), downside is – Proxy is slow.
There is number of ready open source collections based on proxy out there.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Custom allocator fails to rebind to Other type All
I have code for my custom allocator that is written with intent to be a proxy for other allocators to be able for example to gather allocation statistics or whatever else
template<int Id, class T, class BaseAlloc>
class SelfTracingAllocator
: public BaseAlloc
{
typedef AllocationStatistics<Id> StatsType;
public:
typedef typename BaseAlloc base;
typedef typename base::raw_pointer raw_pointer;
typedef typename base::pointer pointer;
typedef typename base::const_pointer const_pointer;
typedef typename base::reference reference;
typedef typename base::const_reference const_reference;
typedef typename base::size_type size_type;
typedef typename base::value_type value_type;
typedef typename base::difference_type difference_type;
template<typename Other>
struct rebind
{
typedef SelfTracingAllocator<Id, Other, base> other;
};
SelfTracingAllocator()
{
}
SelfTracingAllocator( const SelfTracingAllocator& rhs )
{
}
template<typename Other>
inline SelfTracingAllocator( const SelfTracingAllocator<Id, Other, base>& rhs )
{
}
~SelfTracingAllocator()
{
}
template<typename Other>
inline SelfTracingAllocator& operator=( const SelfTracingAllocator<Id, Other, base>& rhs )
{
return (*this);
}
inline raw_pointer allocate(size_type count, const void* ptr)
{
StatsType::allocated_ += count * sizeof(value_type);
return base::allocate(count, ptr);
}
inline raw_pointer allocate(size_type count)
{
StatsType::allocated_ += count * sizeof(value_type);
return base::allocate(count);
}
inline void deallocate( pointer ptr, size_type count )
{
StatsType::deallocated_ += count * sizeof(value_type);
return base::deallocate(ptr, count);
}
};
template<class T, class U, int Id, class BaseAlloc>
inline bool operator==(const SelfTracingAllocator<Id, T, BaseAlloc>& lhs, const SelfTracingAllocator<Id, U, BaseAlloc>& rhs)
{
return true;
}
template<class T, class U, int Id, class BaseAlloc>
inline bool operator!=(const SelfTracingAllocator<Id, T, BaseAlloc>& lhs, const SelfTracingAllocator<Id, U, BaseAlloc>& rhs )
{
return false;
}
template<class T, int Id>
struct my_allocator
{
typedef SelfTracingAllocator<Id, T, some_allocator<T, MemMgr> > type;
};
When I use this allocator like below
typedef custom_string<wchar_t, char_traits<wchar_t>, my_allocator<int, 0>::type > string_t;
I get errors like below
error C2664: 'char_traits<T>::move' : cannot convert parameter 1 from 'int *' to 'wchar_t *'
1> with
1> [
1> T=wchar_t
1> ]
1> Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
1> D:\VRS_Branch\detail/dynamic_buffer.hpp(95) : while compiling class template member function 'void detail::dynamic_buffer<T,Alloc,Traits>::reserve(unsigned int)'
1> with
1> [
1> T=wchar_t,
1> Alloc=SelfTracingAllocator<0,int,some_allocator<int,MemMgr>>,
1> Traits=char_traits<wchar_t>
1> ]
Why does it happen? I have both rebind structure and rebinding copy constructor, so what goes wrong?
Thanks in advance,
Andriy
A: What about using
template<typename Other>
struct rebind
{
typedef SelfTracingAllocator<
Id
, Other
, typename base::template rebind<Other>::other
> other;
};
?
Right now if you have a SelfTracingAllocator<0, int, std::allocator<int> > then rebinding to wchar_t will yield SelfTracingAllocator<0, wchar_t, std::allocator<int> >. That doesn't seem right.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608342",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Cross-origin XMLHttpRequest does not process ASP.NET_SessionId cookies - what could be the case? I'm struggling with the problem in title for already couple of days with no success. I have an ASP.NET MVC 3 REST server which requires basic authentication. I want to write JS API accessing this server in AJAX way using XMLHHttpRequest.
For response to any http request including AJAX ones server adds "Set-Cookie: ASP.NET_SessionId=<session id here>; path=/; HttpOnly" header - that's ok. But it seems that Set-Cookie header is not processed by browser in any way - so even if I do next request with the same XMLHttpRequest object the cookie is not set properly and I can't maintain the session. What I might be doing wrong?
My script has been tested in Firefox 6 and Safari 5 and I have the same problem happening in both browsers.
A: Although I haven't found any relevant solution to the original problem, I've been able to overcome it by implementing my custom transport for ASP.NET session and authentication artifacts.
In general, in my solution all ASP.NET artifacts are transfered from server to clients as JSON string appended to response content, and from clients to server - as custom HTTP headers.
Not sure that I haven't reinvented the wheel by doing that, but at least it works...
A: Your subject mentions you are using CORS. If so, try adding the following header to your response:
Access-Control-Allow-Credentials: true
A: Make sure you don't have this icon in Chrome address bar. They started blocking cookies from other domains, so your session id is lost.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608344",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Storing image using NSDocumentDirectory not working? I'm developing this application for an iPad. My first screen will show 2 UIImageView (ImageView, ImageView2) and 2 UIButton (Confirm, Browse).
I will give a brief description of what my application does.
When the 'Browse' button is tapped, it will show photos from my iPad's photo gallery. When a photo is selected, the photo gallery will be dismissed and 'ImageView' will show the selected photo.
When the 'Confirm' button is tapped, it will store the image into my application's project by using the NSDocumentDirectory. After that, it will retrieve the photo which is saved and display it on 'ImageView2'.
Browse Button..
- (IBAction) browsePhoto:(id)sender
{
UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
imagePickerController.delegate = self;
imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
UIPopoverController *popover = [[UIPopoverController alloc] initWithContentViewController:imagePickerController];
[popover setPopoverContentSize:CGSizeMake(320,320)];
[popover presentPopoverFromRect:CGRectMake(200,200,-100,-100) inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
self.popoverController = popover;
[imagePickerController release];
}
Displaying selected image on ImageView..
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingImage:(UIImage *)selectedImage editingInfo:(NSDictionary *)editingInfo
{
[self.popoverController dismissPopoverAnimated:YES];
imageView.image = selectedImage;
}
Confirm Button..
- (IBAction) confirmPhoto:(id)sender
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDir = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDir stringByAppendingPathComponent:@"SavedImage.png"];
UIImage *image = imageView.image;
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
imageView2.image = [UIImage imageNamed:@"SavedImage.png"];
}
I'm able to view photos from the photo gallery, select a photo, and making the 'ImageView' show the selected photo. But when i tap on 'Confirm' button, 'ImageView2' doesn't display the photo. I have no idea where the problem lies at.
Is the photo even saved?
Or the way i used to retrieve the saved photo is wrong?
A: NSString *filePath=[NSString stringWithFormat:@"%@/%@",documentsDir,@"SavedImage.png"];
imageView2.image=[UIImage imageWithContentsOfFile:filePath];
A: Try to load the image with:
[UIImage imageWithContentsOfFile:imageFilePath]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608345",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is this query possible SELECT * FROM mytable WHERE ([myExpression]); i'v got a question about sql in access 2007.
it's possible to generate a query like this:
SELECT * FROM mytable WHERE ([myExpression]);
in [myexpression] should be something like date between date1 AND date2
or even id > 123.
if it's possible: how?
and if not.. shit happens ;)
A: This is only possible with VBA, where you can either create a recordset, or build or update a querydef.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: No notifications when sending apprequest
Possible Duplicate:
“apprequests” dialog reports success, recipients receive nothing
I am developing a facebook app, and one of the main functions, is to allow a user to send a apprequest to another user, notifying him that he has been challenged.
However, in the past couple of days, it seems something has gone wrong. For some reason, i can send the apprequest just fine, but the diamond does not show at the top of the screen. I checked in the Graph API Explorer, and sure enough, the apprequest are present in there, but the notification never pops up.
Also, the game request does add up on the left side of my mains facebook page, but when i click the game request, none of them are shown?
Is this caused by facebook messing around with the request 2.0 stuff? or could it be my code that creates a "wrong" request? this is an example taken form teh Graph Api Explorer
{
"id": "10150308326517343",
"application": {
"name": "appname",
"id": "277628332248286"
},
"to": {
"name": "Jacob Harpøth Hansen",
"id": "506232342"
},
"from": {
"name": "Jacob Harpøth Hansen",
"id": "506232342"
},
"message": "text",
"created_time": "2011-09-30T09:01:29+0000",
"type": "apprequest"
}
A: Do you have checked option "App on Facebook" in your applecation settings section "Select how your app integrates with Facebook"? Because you can't sending apprequest to just Tabbed application.
A: There is no notification for app-generated requests - only for user-generated.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608352",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Click button, display css class name When I click button (eg.input type="button" class="test"),
I want to display style sheet class name.
I already tried like this.
$(this).get(0).style.name
But i get only undefined message.
Please let me know how to get it.
@@Edit
Let me show you my coding.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="jquery-1.6.4.js"></script>
<script type="text/javascript" src="jquery-fieldselection.js"></script>
<script>
$(document).ready(function(){
var CurrentTextBoxID = "";
// toggles the keyboard to show or hide when link is clicked
$(":text").focus(function(e) {
CurrentTextBoxID = this.id;
var top = ($(window).height() - $('#keyboard').height()) - 25;
var left = ($(window).width() - $('#keyboard').width()) / 2;
//alert(CurrentTextBoxID + " focus In");
$('#keyboard').css(
{
"left": left+"px",
"top": top+"px"
}
).toggle();
$('#keyboard').show();
});
//$(":text").focusout(function() {
$(":text").focusout(function() {
alert($(this).attr('class'));
if($(this).attr('class') != "testClass"){
$('#keyboard').hide();
}
});
// function thats called when any of the keys on the keyboard are pressed
$("#keyboard input").bind("click", function(e) {
$('#'+CurrentTextBoxID).replaceSelection($(this).val(), true);
});
});
</script>
<style type="text/css">
#keyboard {
position: fixed;
background: #eee;
display: none;
border: 1px solid #ccc;
border-radius:7px;
width: 700px;
height: 240px;
padding: 5px;
cursor: move;
box-shadow: -5px -5px 5px 5px #888;
-moz-border-radius: -5px -5px 5px 5px #888;
-webkit-border-radius: -5px -5px 5px 5px #888;
}
.testClass{
width: 100px;
}
</style>
</head>
<body>
<form id="frmOnScreenKeyboard" name="frmOnScreenKeyboard">
<table border="0" cellpadding="0" cellspacing="0" >
<tr>
<td>
<input type="text" name="txtTest1" id="txtTest1"/>
</td>
</tr>
<tr>
<td>
<input type="text" name="txtTest2" id="txtTest2"/>
</td>
</tr>
<tr>
<td>
<input type="text" name="txtTest3" id="txtTest3"/>
</td>
</tr>
<tr>
<td>
<input type="button" name="butButton1" id="butButton1"/>
</td>
</tr>
<tr>
<td>
<input type="password" name="txtpassword1" id="txtpassword1"/>
</td>
</tr>
<table>
<table height="900px">
</table>
<div id="keyboard">
<table border=1 cellpadding=0 cellspacing=0>
<tr>
<td>
<div id="row2_shift">
<table border=1 cellpadding=0 cellspacing=0>
<tr>
<td><input name="a" type="button" value="A" class="testClass" /></td>
<td><input name="s" type="button" value="S" class="testClass" /></td>
<td><input name="d" type="button" value="D" class="testClass" /></td>
</tr>
</table>
</div>
</td>
</tr>
</table>
</div>
</form>
</body>
</html>
When I use this code,
alert($(this).attr('class'));
I still get undefined message.
Please guide me again, Thank to all.
A: Try this -
$(this).attr('class');
EDIT
This happens when the element does not have the class. You can check if the element has class as -
alert($(this).hasClass('classname'));
EDIT2
I added your code to JSFiddle and on focus out of first text box, you can see an alert with class name. Most important thing I observed is, none of your text inputs have a class attribute.
You can test at : http://jsfiddle.net/njJEg/4/
A: $('.test').click(function() {
alert($(this).attr('class'));
});
jQuery .attr('class') will get the value of class attribute. However if the element doesn't have class attribute it will return undefined so make sure you have the class attribute set otherwise you can always check first using the following code:
if($(this).hasClass('yourClassValue')) {
var myClass = $(this).attr('class');
// then do whatever you want with the class here
}
the alert(..) is just to prompt if you actually get the correct value, you can delete this usage of course when you get what you want.
A: $('.test').click(function() {
if($(this).hasClass('classnameyouarelookingfor')){
alert($(this).attr('class'));
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to draw smooth / rounded path? I am creating Paths and adding multi lines in each path by using path.moveTo(x, y) and path.lineTo(x, y). Then canvas.drawPath(path, paint) is drawing all paths. But there are 1-2 pixel space between lines in some paths. How can I remove these spaces? My code is something like that:
paint = new Paint();
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.FILL_AND_STROKE);
paint.setDither(false);
paint.setStrokeWidth(3);
paint.setAntiAlias(true);
for (int i = 0; i < length; i++) {
Path path = new Path();
path.moveTo(a, b);
path.lineTo(c, d);
path.moveTo(c, d);
path.lineTo(e, f);
canvas.drawPath(path, paint);
}
A: You probably don't want to lineTo(c, d) and then immediately moveTo(c, d) which is the same point. If you do this, you won't get a nice corner join on the two line segments, which may look like an ugly gap.
Try removing that moveTo.
A: Maybe this will create what you want
paint.setColor(color); // set the color
paint.setStrokeWidth(size); // set the size
paint.setDither(true); // set the dither to true
paint.setStyle(Paint.Style.STROKE); // set to STOKE
paint.setStrokeJoin(Paint.Join.ROUND); // set the join to round you want
paint.setStrokeCap(Paint.Cap.ROUND); // set the paint cap to round too
paint.setPathEffect(new CornerPathEffect(10) ); // set the path effect when they join.
paint.setAntiAlias(true); // set anti alias so it smooths
:)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608362",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "36"
}
|
Q: Selenium Grid: Identify WebDriver node where a test failure occured We use Selenium WebDriver for testing our web app, and we run the tests via Selenium Grid 2.
This usually works well, but some tests fail randomly when run via Selenium Grid. The error message usually is "error reading zip file".
We tracked this down to a problem on the WebDriver node that the test was using - usually it was some popup dialog being open which apparently blocked the test run.
To further diagnose this issue, it would be helpful to see on what WebDriver node a test failure occured. Unfortunately, while the standard error message from the RemoteWebDriver includes version and system information, it does not include the host name:
org.openqa.selenium.WebDriverException: error reading zip file;
duration or timeout: 83 milliseconds
Build info: version: '2.6.0', revision: '13840', time: '2011-09-13 16:51:41'
System info: os.name: 'Linux', os.arch: 'amd64',
os.version: '2.6.18-194.32.1.el5', java.version: '1.6.0_20'
Also, this is apparently only the information for the system where the Selenium test is running, not the system where the browser is running (i.e. the WebNode).
Is there some way to find out the name of the node where the failed test was run? Or should I consider filing an enhancement request with the Selenium project?
There is a related question: Selenium 2 Grid - Knowing which node your test is using, but it's a bit more general, asking how the test itself can find its machine when it's run.
A: It is possible to identify which node your test (browser) is running on.
Check out these links:
Java and c# bindings:
http://www.martin-walton.me.uk/2013/01/get-host-of-webdriver-grid-node/
Ruby bindings
http://www.martin-walton.me.uk/2013/02/get-host-of-webdriver-grid-node-in-ruby/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608363",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Adobe Flex 3: width and height specified in percentage not working for children of a viewstack I have a ViewStack which is dataProvider for a TabBar. There are two VBoxs as children for this ViewStack. It works fine with absolute values for width and height for these VBoxs, but when specified in percentages, the VBox uses all the available space (100%) for any percentage value. Please find the code and screen shots below.
Can someone please explain why it is getting rendered so? And also how can children of a ViewStack be aligned to center? There is no horizontalAlign property for ViewStack and it is not working with horizontalCenter= "0".
Code:
<mx:ViewStack id="viewStack" width="100%" height="100%" selectedIndex="0" horizontalCenter="0" textAlign="center">
<mx:VBox label="Tab 1" width="25%" height="10%" borderThickness="2" borderColor="red"
borderStyle="solid" horizontalAlign="left">
<mx:Text text="This is tab 1" />
</mx:VBox>
<mx:VBox label="Tab 2" width="30%" height="20%" borderThickness="2" borderColor="haloBlue"
borderStyle="solid">
<mx:Text text="This is tab 2" />
</mx:VBox>
</mx:ViewStack>
Image 1(with absolute values):
Image 2(with width="25%" and height="10%"):
Thanks,
Anji
A: Simply use an outer container that fills the space (which is what you want in a view stack) and put your content inside. That outer container can center your inner content. Like this:
<mx:Box label="Tab 1" width="100%" height="100%" horizontalAlign="center">
<mx:VBox width="25%" height="10%" borderThickness="2" borderColor="red"
borderStyle="solid" >
<mx:Text text="This is tab 1" />
</mx:VBox>
</mx:Box>
A: Please Refer the link
View Stack Container in that please read the
Sizing the children of a ViewStack container
by that U might get the clear Idea
If needed use another container inside the vbox
~~~ HappY Coding ~~~
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SSIS - what do I look for? "Invalid column type from bcp client for colid 1." I have an issue with a SSIS package which was working up till now but suddenly starts throwing up an error which I don't know were to place.
I'm uploading bulk records into a OLE DB Destination, inside a view, and I get this error:
An OLE DB error has occurred. Error code: 0x80004005. An OLE DB record is available. Source: "Microsoft SQL Native Client" Hresult: 0x80004005 Description: "Invalid column type from bcp client for colid 1.".
What does: Invalid column type from bcp client for colid 1. mean? I've searched high and low for this but still don't understand why it fails now (and it worked before).
I've checked the data that goes to the view and I see no differences in types or lengths.
What do I look for? Have you encountered this? what was the issue?
A: I'd be surprised if it had just stopped working and nothing is different.
In general terms, the error is saying that the data type of the data provided by SSIS (your 'BCP client') does not match that of column #1 in your destination.
In other words, I'd expect to find either the wrong type of data defined, or a string that exceeds the defined length, or a decimal where you should have an Int. Might take some searching, but the bad data's there somewhere!
A: I've managed to fix this by deleting and then recreating the view where I was inserting the data.
I'm posting this, maybe someone else could use it and not end up tearing their hairs out.
A: This happened to me. Here’s my understanding of what happened:
*
*I created a table that included column MY_COLUMN
VARCHAR(50)
*I created a view of this table for use in importing data via SSIS.
*I created an SSIS package to import data through this view.
*I tested the package and it worked fine.
Here’s where the problem started:
*
*Later, I realized that VARCHAR(50) wasn’t long enough for the data
that MY_COLUMN should hold, so I increased it to VARCHAR(100).
*I updated the SISS package to reflect the change.
*However, no one has told the view that the underlying schema has
changed. So it still thinks the length of MY_COLUMN is VARCHAR(50).
(Sorry to anthropomorphize here…)
*The next time I ran the SSIS package, it failed with the error
"Invalid column type from bcp client for colid xx."
Solution:
Tell the view about the schema change, i.e. recompile it. No need to drop it and recreate it. (Note, recompile simply means to run the script that modifies the view.) It’s simple fast and easy.
Unfortunately, this is a typical Microsoft error message: Completely accurate but utterly useless.
-Robbie
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608366",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How can I check a group of numbers are consecutive in T-SQL? If i was to have a table with an integer column containing n number of rows and wanted to check if they were consecutive, how could I do this?
DECLARE @Temp TABLE
(
IntegerValue INT,
Processed BIT
)
I have a solution that works for 3 rows but this is infelxable, if the requirements change then so would the query (ignoring the fact that my sum wouldnt work in this case).
@SumOfValues = (@FirstValue * @NumOfValues) + @NumOfValues
A: SELECT CASE
WHEN COUNT(DISTINCT IntegerValue) /*Or COUNT(*) dependant on how
duplicates should be treated */
= 1 + MAX(IntegerValue) - MIN(IntegerValue) THEN 'Y'
ELSE 'N'
END
FROM @Temp
If you want to know where the gaps are you can use
;WITH T AS
(
SELECT *,
DENSE_RANK() OVER (ORDER BY IntegerValue) - IntegerValue AS Grp
FROM @Temp
)
SELECT MIN(IntegerValue) AS RangeStart,
MAX(IntegerValue) AS RangeEnd
FROM T
GROUP BY Grp
ORDER BY MIN(IntegerValue)
A: CREATE TABLE #T(ID INT)
DECLARE @i INT
SET @I = 1
WHILE(@I <= LEN('12235588966'))
BEGIN
IF(SUBSTRING('12235588966',@i,1) = SUBSTRING('12235588966',@i-1,1))
BEGIN
INSERT INTO #T SELECT SUBSTRING('12235588966',@i,1)
END
SET @i = @I +1
END
SELECT * FROM #T
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: EntityFramework to Json workaround? ( A circular reference was detected while serializing an object of type...DynamicProxies) so heres the deal i have
Models
public class News
{
public News()
{
this.Created = DateTime.Now;
}
public int Id { get; set; }
public string Title { get; set; }
public string Preamble { get; set; }
public string Body { get; set; }
public DateTime Created { get; set; }
public int UserId { get; set; }
public virtual User User { get; set; }
public int CategoryId { get; set; }
public int ImageId { get; set; }
public virtual Image Image { get; set; }
public virtual Category Category { get; set; }
}
public class Image
{
public int Id { get; set; }
public string Name { get; set; }
public string ImageUrl { get; set; }
public Byte[] ImageData { get; set; }
public string ImageMimeType { get; set; }
}
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
}
....following models(these models are connected to the EfDbContext) connected to following repository...
Interface/Repository
public class NewsRepository : INewsRepository
{
EfDbContext context = new EfDbContext();
public IQueryable<News> All
{
get { return context.News; }
}
public IQueryable<News> AllIncluding(params Expression<Func<News, object>>[] includeProperties)
{
IQueryable<News> query = context.News;
foreach (var includeProperty in includeProperties) {
query = query.Include(includeProperty);
}
return query;
}
public News Find(int id)
{
return context.News.Find(id);
}
public void InsertOrUpdate(News news)
{
if (news.Id == default(int)) {
// New entity
context.News.Add(news);
} else {
// Existing entity
context.Entry(news).State = EntityState.Modified;
}
}
public void Delete(int id)
{
var news = context.News.Find(id);
context.News.Remove(news);
}
public void Save()
{
context.SaveChanges();
}
}
public interface INewsRepository
{
IQueryable<News> All { get; }
IQueryable<News> AllIncluding(params Expression<Func<News, object>>[] includeProperties);
News Find(int id);
void InsertOrUpdate(News news);
void Delete(int id);
void Save();
}
In my HomeController() i got a a JsonResult metod that i want to return the context.
Here is the Method
Json Request
[HttpGet]
public JsonResult GetNews()
{
var p = newsRepository.AllIncluding(news => news.Category, news => news.Image);
return Json(p, JsonRequestBehavior.AllowGet);
}
I get the following error:
A circular reference was detected while serializing an object of type 'System.Data.Entity.DynamicProxies.News_96C0B16EC4AC46070505EEC7537EF3C68EE6CE5FC3C7D8EBB793B2CF9BD391B3'.
I guessed that this has something to do with the lazyloading stuff(Iam currently learning about C#) i found this article about this...
http://hellowebapps.com/2010-09-26/producing-json-from-entity-framework-4-0-generated-classes/
but i didnt get it to work... what i could read about the code was that they were tryin to depth search trough the object... more than that i couldn't figure out.
my question is how to i can pass in lazyLoading objects? into json/serializer
or does it not exist, any thoughts of how i can proceed?
A: To add to Kamyar's answer...
The AllIncluding method is only available if you are using MVC scaffolding. see the following link for a listing of the method:
Mvc 3 Scaffolding: the Model passed to the View throws SQL errror
I tried using it, but still encountered the circular reference error, since the root objects were still being returned as proxies. So I customised the method to temporarily turn off the ProxyCreationEnabled flag on the EF context, and eagerly load the specified properties listed in the method's parameter. See the following link for further details:
Loading from database without proxy classes?
In order for this to work, the query had to be performed while the setting was still off, so I had to call the query's ToList() method to perform the query, and then returned the IEnumerable, rather than IQueryable. This did the job for me.
Here is the method I used ("_context" is the variable name for my EF context):
public IEnumerable<TEntity> ListIncluding<TEntity>(params Expression<Func<TEntity, object>>[] includeProperties)
where TEntity : class
{
bool cachedSetting = _context.Configuration.ProxyCreationEnabled;
_context.Configuration.ProxyCreationEnabled = false;
IQueryable<TEntity> query = _context.Set<TEntity>();
foreach (var includeProperty in includeProperties)
{
query = query.Include(includeProperty);
}
IEnumerable<TEntity> list = query.ToList();
_context.Configuration.ProxyCreationEnabled = cachedSetting;
return list;
}
This can then get called using the following syntax:
IEnumerable<News> newsItems = newsRepository.ListIncluding<News>(news => news.Category, news => news.Image);
A: Since Json is a tree-based serialization format, it has problems with references like A->B->A.
I've read somewhere that you can use ScriptIgnore attribute in your viewmodels to prevent this error. But have not tested it.
You can change your code to the following (use anonymous types) to retrieve the items successfully:
var p = newsRepository.AllIncluding(news => news.Category, news => news.Image)
.Select(n => new {id = n.Id, Body = n.Body});
Include any other property you wish to display in the last Select method. This makes your Json results more lightweight too.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608372",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: Connect Twisted IRCClient through a http proxy I am playing around with Twisted and while trying to rewrite an old java IRC bot in Python (2.7), I built upon the IrcLogBot example.
I need to connect to the IRC server through a (non auth) HTTP proxy - but there does not seem to be any support for this neither in the irc.IRCClient or in reactor.connectTCP. Am I looking in the wrong places? Can I wrap my connection in some kind of proxy tunneler?
Thanks in advance for any help!
A: If the HTTP proxy you are connecting to supports CONNECT requests, this is totally doable.
Here is an example that works for tunneling SSH connections over an HTTP proxy. It should work for IRC connections as well.
With the example code, you should be able to do something like:
proxy = HTTPProxyConnector('myhttpproxy.server', 8080)
proxy.connectTCP('myirc.server', 6667, MyTwistedIRCClientFactory())
There are still some issues to work out with handling server timeouts more gracefully / quickly, but if you include some kind of periodic application or underlying protocol-level ping, it should keep both servers from timing out your connection.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: roo gem in Ruby I am using 'roo' gem for reading and writing the excel sheets.
How can I get the last column of each row in excel sheet using 'roo' gem in Ruby
Please give me some suggestion on this...
A: http://roo.rubyforge.org/
You can use a for with the method last_column as stated on the link above.
A: You can do the following:
wb = Roo::Excelx.new 'somepath/somefile.xlsx'
1.upto(wb.last_row) do |row_index|
last_column = wb.cell(row_index, wb.last_column)
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608375",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unity run-time resolving? I have the following code in a console program.
interface I { ...; string X { get; }; string Y {get; }; string Z {get; } ...}
class A : I {...}
class B : I {...}
class C : I {...}
The program accept command line parameters like test.exe b -x 10 -z 20. And it will create an instant of B and set X to 10, Z to 20.
How to implement this using unity? This may be a newbie question.
A: You need to register named mapping against same interface and resolve using the name passed as argument.
var container = new UnityContainer();
container.RegisterType<I, A>("a");
container.RegisterType<I, B>("b");
container.RegisterType<I, C>("c");
I instance = container.Resolve<I>(args[0]);
Read Registering Type Mappings with the Container for explanation
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608376",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to escape? data that is being inserted into sqlite database. I'm making an apple app using phone gap (which uses sqlite database).
All my inserts work fine except for when I try to insert a weblink. This errors because there are " characters in the weblink.
Using the following:
var content = 'hello, this is my <a href="www.google.com">link</a>'
tx.executeSql('UPDATE PAGES SET content="'+content+'" WHERE id="1"');
Brings back the following error
error code 1
error: "near "http": syntax error"
If I remove the website address, I don't get an error. I have tried:
content = escape(content);
but that hasn't worked.
A: To escape quotes in SQLite you'll have to repeat the quotes.
So to insert a 7" screen you'll have to put a 7"" screen in the INSERT statement.
A: Use parameter binding. This is the right and the safest way to do what you're trying to do.
tx.executeSql('UPDATE PAGES SET content=? WHERE id=1', [content]);
A: The problem is the quote marks. They change the meaning of the SQL request and cause the error.
I can't find any information on escaping them properly. I read that you can put \ before them and then add ESCAPE ("\") to the SQL statement, but this doesn't seem to work with PhoneGap's implementation.
In the end, I did a simple replace, where single or double quote marks are replaced with ", like so:
var thisNotes = $('textarea#notes').val().replace(/(["'])/g,'"');
I just need to display quote marks in a text field however - I don't need them as part of a HTML link, so I'm not sure whether the link would still work. You may need to reverse the replace before displaying the link.
Hope this helps.
A: use javascript replace maybe create a function like so:
function CleanDbData( dirty ){
var clean = dirty.replace( "/"","''").replace("<script>","[script]");
return clean;
}
var mydata = CleanDbData( dirtydata );
this is not AS is, you will have to mess with regex etc but you get the idea [hopefully]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608378",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Image thumbnail from pdf not displaying in IE8 I have a very strange problem with an thumbnail image, which generates from an uploaded PDF via paperclip in a rails app. The uploaded files are stored on Amazon S3. Paperclip generates a thumbnail image of the first page of the uploaded pdf. This works fine and the thumb image can be viewed in all browsers, except IE8. Here you only see an X
Here is the url of one sample generated thumbnail (https://s3.amazonaws.com/production.harold-scholz.de/pictures/70/Sonderdruck BWI 11-04-original-thumb.jpg).
Does anyone have a clue?
A: Perhaps something to do with the spaces in the web address? Have you tried removing them and seeing if this resolves the issue?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: any example augmented reality in iphone any code best tutorial or code available for the augmented reality in iphone?
I am facing lots of problem with the capturing of image with attaching other image on that.
add any overlay or something.
any sample code is more then appreciated.
A: Please go through https://github.com/zac/iphonearkit.
It's the best objectiveC code available.
A: There's a step-by step tutorial from iOS environment setup to tracking and rendering 3D animations here: http://dev.metaio.com/sdk/tutorials/hello-world/
Also includes sample code and 3D assets to play around with.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608395",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Image uploading on android I am in a strange problem right now.
I've been trying to upload an image from my android app to the server, however it works fine when i am using wifi connection but when i am on GPRS the application just keeps on processing for an infinite amount of time. Below is the code:
try
{
Log.i(TAG,"publishFileToServer Called...");
FileInputStream fileInputStream = new FileInputStream(new File(filePath) );
URL url = new URL(urlServer);
System.setProperty("http.keepAlive", "false");
connection = (HttpURLConnection) url.openConnection();
Log.i(TAG,"publishFileToServer Called... 1");
// Allow Inputs & Outputs
connection.setDoInput(true);
connection.setDoOutput(true);
connection.setUseCaches(false);
Log.i(TAG,"publishFileToServer Called... 2");
// Enable POST method
connection.setRequestMethod("POST");
connection.setRequestProperty("Connection", "Keep-Alive");
connection.setRequestProperty("Content-Type", "multipart/form-data;boundary="+boundary);
Log.i(TAG,"publishFileToServer Called...3");
outputStream = new DataOutputStream( connection.getOutputStream() );
outputStream.writeBytes(twoHyphens + boundary + lineEnd);
outputStream.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + filePath +"\"" + lineEnd);
outputStream.writeBytes(lineEnd);
Log.i(TAG,"publishFileToServer Called...4");
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
buffer = new byte[bufferSize];
Log.i(TAG,"publishFileToServer Called...5");
// Read file
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
Log.i(TAG,"publishFileToServer Called...6");
while (bytesRead > 0)
{
outputStream.write(buffer, 0, bufferSize);
bytesAvailable = fileInputStream.available();
bufferSize = Math.min(bytesAvailable, maxBufferSize);
bytesRead = fileInputStream.read(buffer, 0, bufferSize);
}
Log.i(TAG,"publishFileToServer Called...7");
outputStream.writeBytes(lineEnd);
outputStream.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);
Log.i(TAG,"publishFileToServer Called...8");
// Responses from the server (code and message)
int serverResponseCode = connection.getResponseCode();
Log.i(TAG,"publishFileToServer: ServerResponseCode = "+serverResponseCode);
String serverResponseMessage = connection.getResponseMessage();
Log.i(TAG,"publishFileToServer: ServerResponseMessage = "+serverResponseMessage);
Log.i(TAG,"publishFileToServer Called...9");
fileInputStream.close();
outputStream.flush();
outputStream.close();
Log.i(TAG,"publishFileToServer Called...10");
}
catch (Exception ex)
{
Log.e(TAG,"publishFileToServer: "+ex.getMessage());
}
It's noticeable that i use this same code to upload a text file an it works fine even on GPRS, i've tried to narrow it down and my application goes into the problem right before the getResponse() method when I am uploading an image.
A: Are you doing this from inside an activity?
Use a service and put it in an AsyncTask
With wifi, there is little to no latency. With the cell network, there is plenty of latency, so your request is most likely blocking the ui thread.
A: Apparently the problem went away after a re-install of the sdk.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608400",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to truncate table in sqlite in android I am new in android. Can anyone help me to hows truncate table in sqlite in android..
Can anyone give me example of that delete table?
Please help me.
A: What do you want to do? If you want to truncate the table (delete all data) you can use the DELETE query without a where condition. If you want to delete the entire table you can use a DROP TABLE query
A: It is the two step process:
*
*First delete all data from that table using this:
Delete from TableName
*Second step:
DELETE FROM SQLITE_SEQUENCE WHERE name='TableName';
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Drag n Drop sections on the BBC website, how is it done? I have a new project to plan and the client likes the BBC's drag / drop sections on the home page. How is that done ? Is it with a framework like Sencha or jQuery ?
Thanks
Rich :)
A: The BBC uses its own JavaScript framework called Glow. What you're looking at is probably the sortable widget.
The "Customisable Homepage Demo" at the bottom of the sortable widget documentation looks like a barebones version of the BBC homepage.
A: $(function(){
$('.bucket').sortable({
connectWith: '.bucket'
});
$('.element').draggable({
connectToSortable: '.bucket'
});
$('ul', 'li').disableSelection();
})
This allows you to have many containers, and you can drag elements between containers.
Press the '+' element to create a 'task'. Then try and drag it.
An example: http://jsfiddle.net/RD5M6/3/
For further reading: http://jqueryui.com/demos/sortable/
A: most likely a custom version of http://jqueryui.com/demos/sortable/#display-grid
A: The BBC are most likely using their own Javascript library. Glow, as mentioned already.
But this type of interface can also be achieved with jQueryUI or Scriptaculous:
http://jqueryui.com/demos/draggable/
http://madrobby.github.com/scriptaculous/draggable/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608408",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Chosing language in application - objective-c
Possible Duplicate:
How to force NSLocalizedString to use a specific language
How to change language in my application? I have 2 localizations: english and russian. Language changes when i change my system language in iPhone. But i want to change language in my own application by user. How to do this?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608409",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to see exactly what happend in git merge I'm in
branch_X
I do
git log -p lib/foo
to see differences in the file foo, but the interesting thing I want to see is just written as:
commit aaaaaaaaaaaaaaaaaaaa
Merge: bbbbbbbb cccccc
Merge branch 'branch_X' into branch_Y
Conflicts:
lib/foo
How can I see exactly what happend in this merge?
Something bad seems to have gotten inserted into branch_X during this merge.
A: It sounds like you want to view the differences that were merged in which you can do with:
git diff aaaaaaaaaaaaaaaaaaaa^ aaaaaaaaaaaaaaaaaaaa
Although looking at the message: "Merge branch 'branch_X' into branch_Y", it sounds like the merge was done the other way around. Either way you might want to look at the merge the other way around and see what the differences to the second parent were:
git diff aaaaaaaaaaaaaaaaaaaa^2 aaaaaaaaaaaaaaaaaaaa
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608411",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Class with builtin marshalling. Why are the field converters not working? I have the following questions:
*
*Should the marshalling be placed in a class helper instead? Or is it quite OK to place it "inside" the class?
*Why are the field converters not working?
Using Delphi XE - consider this:
type
TMyClass = Class
public
FaString : String;
FaStringList : TStringList;
FMar : TJsonMarshal;
procedure RegisterConverters;
function Marshal : TJsonObject; // should handle marshalling
end;
RegisterConverters would look something like this.
procedure TMyClass.RegisterConverters;
begin
// try and catch the marshaller itself.
FMar.RegisterConverter(TJsonMarshal, 'FMar',
function(Data : TObject; Field:String): TObject
begin
Exit(nil); // Since we cannot marshal it - and we dont need it anyways.
end);
// catch TStringList
FMar.RegisterConverter(TStringList, 'FaStringList',
function(Data: TObject; Field:String): TListOfStrings
var
i, count: integer;
begin
count := TStringList(Data).count;
SetLength(Result, count);
for i := 0 to count - 1 do
Result[i] := TStringList(Data)[i];
end);
end;
And the Marshal method :
function TMyClass.Marshal: TJSONObject;
begin
if FMar = nil then
FMar := TJSONMarshal.Create(TJSONConverter.Create);
try
RegisterConverters;
try
Result := FMar.Marshal(Self) as TJSONObject;
except
Result := nil;
end;
finally
FMar.Free;
end;
end;
Then we can do this:
var
aObj : TMyClass;
ResultString : String;
begin
aObj := TMyClass.Create;
aObj.FaString := 'Test string';
aObj.FaStringList := TStringList.Create;
aObj.FaStringList.Add('stringliststring #1');
aObj.FaStringList.Add('stringliststring #2');
aObj.FaStringList.Add('stringliststring #3');
aObj.FaStringList.Add('stringliststring #4');
// StringList and JsonMarshal should be handled by converter
ResultString := (aObj.Marshal).ToString;
end;
But I simply cannot get it working. Field Converters do not get triggered?
Am I doing something wrong here? Or should I look at my Delphi XE installation (perhaps it is pooched)?
A: When doing the marshal from "within" you have to set it up correctly :-)
procedure TMyClass.RegisterConverters;
begin
// try and catch the marshaller itself.
FMar.RegisterConverter(ClassType, 'FMar',
function(Data : TObject; Field:String): TObject
begin
Exit(nil); // Since we cannot marshal it - and we dont need it anyways.
end);
// catch TStringList
FMar.RegisterConverter(ClassType, 'FaStringList',
function(Data: TObject; Field:String): TListOfStrings
var
i, count: integer;
begin
count := TStringList(Data).count;
SetLength(Result, count);
for i := 0 to count - 1 do
Result[i] := TStringList(Data)[i];
end);
end;
The difference is using ClassType as the type in the call to RegisterConverter.
Otherwise one cannot get to the specified field - I should have seen that !
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608415",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Update listview's viewitems without notifyDataSetChanged I have an android application with a listview which .. blablabla .. presents a title and adress of a location. Furthermore it displays a distance in meters and a compas.
http://i.stack.imgur.com/k5XHF.jpg (Sorry cant post screenshots yet :)
Whenever i get new compas data from my SensorManagers listener, i do notifyDataSetChanged the list is updated with the new bearing and everythings fine, however it seems to freeze the application for a few ms, nothing serious but the user can sure feel this laggy effect.
And now to my real question:
Is it possible to update only the "compasviews" without doing notifyDataSetChanged?
I thought the best way to go about this would be some "findviewsbyid"function, save the destination in the compasview it self and only update the compasview, but i can only find the findViewById method.
A: Are you doing extensive calculations on the UI-thread? If so, consider implementing an AsyncTask for calculating the new values and then call notifyDataSetChanged() in onPostExecute()-method of your AsyncTask.
private class MyAsyncTask extends AsyncTask<Params, Progress, Result> {
@Override
protected Result doInBackground(Params... params) {
//Do calculations here
return null;
}
protected void onPostExecute(Result result) {
//Submit new data to the listadapter
adapater.notifyDataSetChanged();
};
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608421",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to use Spring SimpleThreadScope? Spring 3.0 defines a SimpleThreadScope. Looking at all known implementing classes of the Scope interface, I see: AbstractRequestAttributesScope, PortletContextScope, RequestScope, ServletContextScope, SessionScope, SimpleThreadScope.
The first observation is that I don't see a PrototypeScope, and don't understand why.
My question, though, is how to use SimpleThreadScope, since RequestScope becomes "request" in XML or annotation, so I tried to use "simplethread" and "simpleThread", but they don't work.
I get the following message:
Caused by: java.lang.IllegalStateException: No Scope registered for scope 'simpleThread'
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:192)
Does it mean that SimpleThreadScope should be used only programmatically, not through XML or annotations? And how to use it?
A: SimpleThreadScope is not registered by default, so that you need to register it manually in order to use it, see 3.5.5.2 Using a custom scope.
singleton and prototype scopes don't have their Scope classes since they are hardcoded into bean factory.
A: Here is one way to use SimpleThreadScope in Spring Boot.
Go to the Application class where your project starts when executed.
Then will need to import the following:
import org.springframework.context.annotation.Bean;
import org.springframework.beans.factory.config.CustomScopeConfigurer;
import org.springframework.context.support.SimpleThreadScope;
Create a static method that returns an object of type CustomScopeConfigurer and apply the @Bean annotation to it:
@Bean
public static CustomScopeConfigurer yourCustomScopeConfigurer() {}
This will indicate that this method will produce a bean to be managed by the Spring container.
Then, create a new CustomScopeConfigurer which you will setup later.
@Bean
public static CustomScopeConfigurer yourCustomScopeConfigurer() {
final CustomScopeConfigurer newConfigurer = new CustomScopeConfigurer();
return newConfigurer;
}
We use the keyword final here to create a constant object which you can setup but you can't modify. In other words, the reference variable cannot be re-bound to another object. The internal state of the object pointed by this reference variable can be changed.
Next, we need to register all of the supplied scopes, here is where we use the SimpleThreadScope via a HashMap:
@Bean
public static CustomScopeConfigurer yourCustomScopeConfigurer() {
final CustomScopeConfigurer newConfigurer = new CustomScopeConfigurer();
Map<String, Object> newScopes = new HashMap<String, Object>();
newScopes.put("thread", new SimpleThreadScope());
newConfigurer.setScopes(newScopes);
return newConfigurer;
}
Optional
You might want to use the @EnableAsync annotation which enables Spring's asynchronous method execution capability:
import org.springframework.scheduling.annotation.EnableAsync;
...
@EnableAsync
public class YourProjectApplication{
...
}
Note: the three dots means code between those lines.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to convert the WordOpenXML property into a System.IO.Packaging.Package? I've been experimenting with building an Outlook 2010 addin in C#, using Visual Studio 2008. I am able to obtain a Microsoft.Office.Interop.Word.DocumentClass object from a Microsoft.Office.Interop.Outlook.Inspector object, which represents the e-mail being currently edited. I understand that this DocumentClass is used in various other contexts too (usually for Microsoft Word extensions, unsurprisingly).
That class helpfully has a property called WordOpenXML, which seems to be an XML representation of all the files constituting the the .docx package which would be saved to disk when saving this Word document as a .docx.
One way this property would be very useful is if it could be converted into a System.IO.Packaging.Package object in memory; ie. deserialize it. Does anyone know whether there is an easy way to do this, or do I need to write some XML parsing code to do it manually?
A: I ended up modifying some code I found online to create a method which converts WordOpenXML to a Package, which is saved to disk:
using System;
using System.Xml;
using System.Xml.XPath;
using System.Text;
using System.IO;
using System.IO.Packaging;
// [...]
// Call like this: createPackageFromWordOpenXML(wordEditor.WordOpenXML, @"C:\outputFiles\testOut.docx");
/// <summary>
/// Creates a ZIP package (ie. Word's .docx format) from a WordOpenXML string, which is saved to the file at the path specified.
/// </summary>
/// <param name="wordOpenXML">The WordOpenXML string to get the ZIP package data from.</param>
/// <param name="filePath">The path of the file to save the ZIP package to.</param>
private void createPackageFromWordOpenXML(string wordOpenXML, string filePath)
{
string packageXmlns = "http://schemas.microsoft.com/office/2006/xmlPackage";
Package newPkg = System.IO.Packaging.ZipPackage.Open(filePath, FileMode.Create);
try
{
XPathDocument xpDocument = new XPathDocument(new StringReader(wordOpenXML));
XPathNavigator xpNavigator = xpDocument.CreateNavigator();
XmlNamespaceManager nsManager = new XmlNamespaceManager(xpNavigator.NameTable);
nsManager.AddNamespace("pkg", packageXmlns);
XPathNodeIterator xpIterator = xpNavigator.Select("//pkg:part", nsManager);
while (xpIterator.MoveNext())
{
Uri partUri = new Uri(xpIterator.Current.GetAttribute("name", packageXmlns), UriKind.Relative);
PackagePart pkgPart = newPkg.CreatePart(partUri, xpIterator.Current.GetAttribute("contentType", packageXmlns));
// Set this package part's contents to this XML node's inner XML, sans its surrounding xmlData element.
string strInnerXml = xpIterator.Current.InnerXml
.Replace("<pkg:xmlData xmlns:pkg=\"" + packageXmlns + "\">", "")
.Replace("</pkg:xmlData>", "");
byte[] buffer = Encoding.UTF8.GetBytes(strInnerXml);
pkgPart.GetStream().Write(buffer, 0, buffer.Length);
}
newPkg.Flush();
}
finally
{
newPkg.Close();
}
}
A: I converted this to VB.NET and added a piece to deal with binary attachments. Thanks for the excellent work!
Public Sub createDocXFromWordOpenXML(ByRef sWordOpenXML As String, ByVal sfilePath As String)
Dim sPackageXMLNS As String = "http://schemas.microsoft.com/office/2006/xmlPackage"
Dim docxPkg As Package
Dim xPathDoc As XPathDocument
Dim xpNav As XPathNavigator
Dim xNSMgnr As XmlNamespaceManager
Dim xpPntr As XPathNodeIterator
Dim partURI As Uri
Dim pkgPart As PackagePart
Dim sInnerXML As String
Dim bytBuffer As Byte()
docxPkg = System.IO.Packaging.ZipPackage.Open(sfilePath, FileMode.Create)
Try
xPathDoc = New XPathDocument(New StringReader(sWordOpenXML))
xpNav = xPathDoc.CreateNavigator()
xNSMgnr = New XmlNamespaceManager(xpNav.NameTable)
xNSMgnr.AddNamespace("pkg", sPackageXMLNS)
xpPntr = xpNav.Select("//pkg:part", xNSMgnr)
While xpPntr.MoveNext()
partURI = New Uri(xpPntr.Current.GetAttribute("name", sPackageXMLNS), UriKind.Relative)
pkgPart = docxPkg.CreatePart(partURI, xpPntr.Current.GetAttribute("contentType", sPackageXMLNS))
sInnerXML = xpPntr.Current.InnerXml
Select Case True
Case sInnerXML.Contains("xmlData")
sInnerXML = sInnerXML.Replace("<pkg:xmlData xmlns:pkg=""" & sPackageXMLNS & """>", String.Empty)
sInnerXML = sInnerXML.Replace("</pkg:xmlData>", String.Empty)
bytBuffer = Encoding.UTF8.GetBytes(sInnerXML)
pkgPart.GetStream().Write(bytBuffer, 0, bytBuffer.Length)
Case sInnerXML.Contains("binaryData")
sInnerXML = sInnerXML.Replace("<pkg:binaryData xmlns:pkg=""" & sPackageXMLNS & """>", String.Empty)
sInnerXML = sInnerXML.Replace("</pkg:binaryData>", String.Empty)
bytBuffer = Convert.FromBase64String(sInnerXML)
pkgPart.GetStream().Write(bytBuffer, 0, bytBuffer.Length)
End Select
End While
docxPkg.Flush()
Catch ex As Exception
Throw
Finally
docxPkg.Close()
End Try
End Sub
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: how to upload, download file from tomcat server with username,password in swing I want to make a program in swing which connect to tomcat server running locally. with username,password authentication, then user able to upload file in server directory. ie.http://localhost:8080/uploadfiles. from user defined file path , and same as download to the local directory.
A: Here is one possibility:
Download:
URL url = new URL("http://localhost:8080/uploadfiles");
HttpURLConnection con = (HttpURLConnection)url.openConnection();
try {
con.addRequestProperty("Authorization",
"Basic " + encode64(username + ":" + password));
InputStream in = con.getInputStream();
try {
OutputStream out = new FileOutputStream(outFile);
try {
byte buf[] = new byte[4096];
for (int n = in.read(buf); n > 0; n = in.read(buf)) {
out.write(buf, 0, n);
}
} finally {
out.close();
}
} finally {
in.close();
}
} finally {
con.disconnect();
}
Upload:
URL url = new URL("http://localhost:8080/uploadfiles");
HttpURLConnection con = (HttpURLConnection)uploadUrl.openConnection();
try {
con.setDoOutput(true);
con.setRequestMethod("POST");
con.addRequestProperty("Authorization",
"Basic " + encode64(username + ":" + password));
OutputStream out = con.getOutputStream();
try {
InputStream in = new FileInputStream(inFile);
try {
byte buffer[] = new byte[4096];
for (int n = in.read(buffer); n > 0; n = in.read(buffer)) {
out.write(buffer, 0, n);
}
} finally {
in.close();
}
} finally {
out.close();
}
int code = con.getResponseCode();
if (code != HttpURLConnection.HTTP_OK) {
String msg = con.getResponseMessage();
throw new IOException("HTTP Error " + code + ": " + msg);
}
} finally {
con.disconnect();
}
Now, on the server side, you will need to distinguish between GET and POST requests and handle them accordingly. You will need a library to handle uploads, such as apache FileUpload
Oh, and on the client side, you will need a library that does Base64 encoding such as apache commons codec
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608428",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to implement search Token (like in mac Lion )in Java? I am thinking to implement search token (see below) in java. I have my different fields to search from and text to search. I am a little confused on how to make the UI like the rectangular ellipse and text in it and a cross button on it. How do we make that in JTextArea. Ideas are welcome.
Example of a search token:
A: If this question is purely about the UI, then you need to change the LookAndFeel to something that matches Mac OS.
I don't think there is a Mac like LAF out of the box, but a quick Google search shows some promising results.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608433",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: IBM MQ vs JMS - Spring Implementation I am working on a Spring application where we have implemented code to send messages through IBM MQ.
Now we have been advised not to directly use MQ APIs directly and instead use JMS.
The steps I followed :
*
*created a JNDI name to connect to the Message queue configured as:
<bean id="emailQueueDestination" class="org.springframework.jndi.JndiObjectFactoryBean" lazy-init="true">
<property name="jndiName" value="<<JNDI name of Queue" >>/>
</bean>
*I need a connecton factory object to connect to the JMS Provider and I have configured it as:
<bean id="emailQueueConnectionFactory" class="com.ibm.mq.jms.MQQueueConnectionFactory">
<property name="queueManager" value="" />
<property name="hostName" value="" />
<property name="channel" value="" />
<property name="port" value="1414" />
</bean>
Further I have injected the above 2 beans in JMSTemplate class:
<bean id="emailQueueTemplate" class="org.springframework.jms.core.JmsTemplate" lazy-init="true">
<property name="connectionFactory" ref="emailQueueConnectionFactory" />
<property name="defaultDestination" ref="emailQueueDestination" />
</bean>
Now since my purpose is to remove dependency on MQ APIs, do you think the configuration above (especially for connection factory) looks good?
A: If your code doesn't refer to any of the MQ classes (i.e. it references that bean only as a JMS ConnectionFactory and you don't rely on any other non-standard features of MQ, then this should make your code reasonably easy to port.
I wouldn't bet that switching to another product would require zero code changes (many JMS implementations seem to have some interesting peculiarities), but you're definitely on the right way.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608434",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Implement facebook authentication How many methods to implement facebook authentication on my website? My approach are:
*
*Display a facebook login button on my website
*When user click on it, they will be asked for username password or grant some permissions etc...
*After they logged, display their face and name on my website at position of login button.
Now, I can do 1, 2 with this code below
<div id="fb-root"></div>
<script src="http://connect.facebook.net/en_US/all.js"></script>
<script>
FB.init({
appId:'22***00**58****',
cookie:true,
status:true,
xfbml:true,
oauth:true
});
</script>
<fb:login-button></fb:login-button>
I'm still stuck with 3.
A: check out the guide at http://fbdevhub.com/wiki/index.php?title=Canvas_App_Tutorial for a quickstart example
A: Here is the JS SDK method you'll need to use.
FB.login(function(responseLogin) {
if (responseLogin.session) {
// user is logged in
// uid is in responseLogin.session.uid
// just explore the whole object with console.log(responseLogin);
} else {
// refused to grant the permissions
}
}, { perms:'offline_access,email' }); // example of perms
Remove the <fb:login> button, replace by a real button, and when the user clicks on this button, call this method.
It's not the only way, but it's a simple one.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Additive Skeleton Animation Im having a hard time to code additive skeletal animation.
Everything work fine if I playback each animation separately so I know that the pose of each animation is correct... What I can't figure out is how to additively blend them.
I got the following:
void MD5ANIM_additive_blending( MD5MD5ANIM *md5, MD5MD5ANIMJOINT *dst, MD5MD5ANIMJOINT *pose0, MD5MD5ANIMJOINT *pose1 )
{
unsigned int i = 0;
while( i != md5->n_joint )
{
vec3 location;
quat4 quaternion;
// The joints location difference
vec3_subtract( &location, &pose1[ i ].location, &pose0[ i ].location );
// Add the joint location difference to the first pose to create additive new pose.
vec3_add( &dst[ i ].location, &pose0[ i ].location, &location );
// The quaternion difference
quat4_subtract( &quaternion, &pose0[ i ].quaternion, &pose1[ i ].quaternion );
// Add the joint quaternion difference to the first pose to create additive new pose.
quat4_add( &dst[ i ].quaternion, &pose0[ i ].quaternion, &quaternion );
quat4_normalize( &dst[ i ].quaternion,
&dst[ i ].quaternion );
++i;
}
}
Anybody can point me out where I get it wrong. From what I understand additively blending to skeleton pose is as simple as:
additive_pose = pose0 + ( pose0 - pose1 )
What I am doing wrong?
A:
Lets say you have a walk animation, and another one with a hand in the air. So basically walk + hand = walk with hand in the air
There are two possibilities:
*
*Your walk animation does not affect the same bones that your hand animation does.
*Your walk animation does affect the same bones that your hand animation does.
Case 1
In this case, you have two options. Your pose structure can have a bitfield telling whether a particular bone is in it. Thus you can compose two poses by seeing which pose has bones that the other one doesn't provide.
If there is no bitfield or other information saying whether a pose actually contains bone data, then you can do this. Any bone for a pose that was not in the animation should be identity. Therefore, you can multiply the bones of the two poses together via quaternion multiplication.
Case 2
Since there is overlap between the two animations, someone has to win. Basically, you have to know what bones the layered animation has and replace the data from the lower pose with ones from the higher pose.
The code you posted is gibberish. In general, if you have two orientation quaternions and think that adding/subtracting them is a good idea, then you're either doing some complex optimizations (in which case you know what you're doing), or you're doing something very wrong.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608444",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Tomahawk + seam does not work So I have a Seam Project and I'm trying to integrate Tomahawk 1.2. I've copied the tomahawk12.jar in WebInf/lib and I have the following configuration in web.xml:
<filter>
<filter-name>MyFacesExtensionsFilter</filter-name>
<filter-class>org.apache.myfaces.webapp.filter.ExtensionsFilter</filter-class>
<init-param>
<param-name>maxFileSize</param-name>
<param-value>20m</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>MyFacesExtensionsFilter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
<filter-mapping>
<filter-name>MyFacesExtensionsFilter</filter-name>
<url-pattern>/faces/myFacesExtensionResource/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>MyFacesExtensionsFilter</filter-name>
<url-pattern>*.seam</url-pattern>
</filter-mapping>
I want to use the Scheduler but I get the following Exception:
"Caused by: javax.el.ELException: /pages/Interpreter/interpreterCalendar.xhtml @28,67 value="#{schedule.model}": Error reading 'model' on type org.javassist.tmp.java.lang.Object_$$_javassist_seam_2
at com.sun.facelets.el.TagValueExpression.getValue(TagValueExpression.java:76)
at javax.faces.component.ValueBindingValueExpressionAdapter.getValue(ValueBindingValueExpressionAdapter.java:113)
... 66 more
Caused by: java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.jboss.seam.util.Reflections.invoke(Reflections.java:22)
at org.jboss.seam.intercept.RootInvocationContext.proceed(RootInvocationContext.java:32)
at org.jboss.seam.intercept.ClientSideInterceptor$1.proceed(ClientSideInterceptor.java:76)
at org.jboss.seam.intercept.SeamInvocationContext.proceed(SeamInvocationContext.java:56)
at org.jboss.seam.intercept.RootInterceptor.invoke(RootInterceptor.java:107)
at org.jboss.seam.intercept.ClientSideInterceptor.invoke(ClientSideInterceptor.java:54)
at org.javassist.tmp.java.lang.Object_$$_javassist_seam_2.getModel(Object_$$_javassist_seam_2.java)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at javax.el.BeanELResolver.getValue(BeanELResolver.java:62)
at javax.el.CompositeELResolver.getValue(CompositeELResolver.java:53)
at com.sun.faces.el.FacesCompositeELResolver.getValue(FacesCompositeELResolver.java:72)
at org.jboss.el.parser.AstPropertySuffix.getValue(AstPropertySuffix.java:53)
at org.jboss.el.parser.AstValue.getValue(AstValue.java:67)
at org.jboss.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:186)
at com.sun.facelets.el.TagValueExpression.getValue(TagValueExpression.java:71)
... 67 more
Caused by: java.lang.LinkageError: loader constraint violation: loader (instance of org/jboss/web/tomcat/service/WebCtxLoader$ENCLoader) previously initiated loading for a different type with name "org/apache/myfaces/custom/schedule/model/SimpleScheduleModel"
at $Proxy234.getModel(Unknown Source)
... 89 more"
any ideas?
A: "java.lang.LinkageError: loader constraint violation" usually means there is something wrong in your classpath. Check in your classpath for duplicate jars (in this case tomahawk jars).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608446",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Making network-intensive code more robust I have code which interacts with amazon S3 and the files transferred are usually big - couple of gigs so what suggestions can you make to make them more robust in case of failure. Also what is the (if any) general strategy for implementing robustness in network code. Is something like that acceptable in order to try an operation 3 times? Any tips are appreciated
public void downloadFile(String path, int retries) {
(if retries == 3) return;
Connection con = new ConnectToAmazon();
try {
con.saveFileToDisk(path, LocalDiskPath);
} catch ( Exception) {
downloadFile(path, retries++);
}
A: Make sure that you upload using the multipart upload API more info is in the documentation
http://docs.amazonwebservices.com/AmazonS3/latest/dev/index.html?uploadobjusingmpu.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608448",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Database index error when importing contact entity in crm 2011 organisation Our company has a crm 2011 dev environment and some customers. I recently exported a solution which contained the contact entity from dev and tried to import it in an other organisation (one of our customers). At approx 30% import i get the following error;
"One of the fields of the selected entity is a part of database index and so it cannot be greater than 900 bytes."
..on the contact entity.
Log file:
1.0
Unmanaged
DefaultPublisherhc
Default Publisher for hc
Default publisher for this organization
Failure
One of the fields of the selected entity is a part of database index and so it cannot be greater than 900 bytes.
34.62
42.2
This organisation runs on a partner hosted server.
Anyone a clue what the problem (and solution) could be?
Thanks in advance,
Kind regards
Angelo
A: Is this a fresh new organization, or have there already been some customizations to it? If you have access to the SQL box, I'd check for any indexes on the ContactBase or ContactExtensionBase tables and remove them.
I'd also check your customizations... did you increase the maximum length of any native text attributes above 900 characters? Try dialing those back if you can and reimport.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608451",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android - custom UI with custom attributes I know it is possible to create custom UI element (by way of View or specific UI element extension). But is it possible to define new properties or attributes to newly created UI elements (I mean not inherited, but brand new to define some specific behavior I am not able to handle with default propertis or attributes)
e.g. element my custom element:
<com.tryout.myCustomElement
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Element..."
android:myCustomValue=<someValue>
/>
So is it possible to define MyCustomValue?
Thx
A: Yes. Short guide:
*
*Create an attribute XML
Create a new XML file inside /res/values/attrs.xml, with the attribute and its type
<?xml version="1.0" encoding="UTF-8"?>
<resources>
<declare-styleable name="MyCustomElement">
<attr name="distanceExample" format="dimension"/>
</declare-styleable>
</resources>
Basically you have to set up one <declare-styleable /> for your view that contains all your custom attributes (here just one). I never found a full list of possible types, so you need to look at the source for one I guess. Types that I know are reference (to another resource), color, boolean, dimension, float, integer and string. They are pretty self-explanatory
*Use the attributes in your layout
That works the same way you did above, with one exception. Your custom attribute needs its own XML namespace.
<com.example.yourpackage.MyCustomElement
xmlns:customNS="http://schemas.android.com/apk/res/com.example.yourpackage"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Element..."
customNS:distanceExample="12dp"
/>
Pretty straight forward.
*Make use of the values you get passed
Modify the constructor of your custom view to parse the values.
public MyCustomElement(Context context, AttributeSet attrs) {
super(context, attrs);
TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.MyCustomElement, 0, 0);
try {
distanceExample = ta.getDimension(R.styleable.MyCustomElement_distanceExample, 100.0f);
} finally {
ta.recycle();
}
// ...
}
distanceExample is a private member variable in this example. TypedArray has lots of other things to parse other types of values.
And that's it. Use the parsed value in your View to modify it, e.g. use it in onDraw() to change the look accordingly.
A: In your res/values folder create attr.xml. There you can define your attribues:
<declare-styleable name="">
<attr name="myCustomValue" format="integer/boolean/whatever" />
</declare-styleable>
When you then want to use it in your layout file you have to add
xmlns:customname="http://schemas.android.com/apk/res/your.package.name"
and then you can use the value with customname:myCustomValue=""
A: Yes , you can.Just use <resource> tag.
like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="CodeFont" parent="@android:style/TextAppearance.Medium">
<item name="android:layout_width">fill_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:textColor">#00FF00</item>
<item name="android:typeface">monospace</item>
</style>
</resources>
link from official website
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608464",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "115"
}
|
Q: BDD Style UI testing for Compact.Net Forms I am used to using Cucumber or StoryQ with Selenium/Webdriver (based upon my platform) for automated UI testing in a continous integration environment, I have looked at White for winforms testing before now however the problem I am facing is that my next project is targetting Compact.Net and I would like to continue testing in this manner.
So could anyone recommend any tool which would be akin to Selenium or White, but support Compact.Net UIs. Ideally I would like to use StoryQ and write the tests in C# for this one as there will be more developers than testers.
One thing that I cannot get my head around 100% is that the forms are hosted on the device/emulator, so I am assuming if anything can do what im asking it would require the build server to have an emulator running on it to carry out these tests.
A: There was some discussion of this in Automated GUI Testing .NET CF (Windows Mobile 5). Whatever tool you use will have to run inside the emulator as well.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Ctrl-space function on roo shell unable to work on mac osx despite changing shortcut keys I'm on mac osx snow leopard running eclipse 3.7 with sts 2.7.2 roo 1.1.5 plugin. Under roo shell, pressing cmd+Space will trigger spotlight so I disabled spotlight shortcut, but still roo content assist doesn't show up. Then I changed content assist shortcut for eclipse to Shift+Space, still doesn't work.
A: If the problem continues, please file a bug in the STS Issue Tracker.
However, you can still use the Roo console from the operating system shell. In there, by default, the content assist for Roo shell works with the Tab key.
A: I have stock sts 2.7.1 running on OSX 10.6, and default shortcut for assist is CTRL+Space (not CMD+Space)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Rails migration: update_all with dynamic code is possible? I'd like to add a new field in a table.
My new "secret_code" field in my User model should be equal to Digest::SHA1.hexdigest([Time.now, rand].join)[1..12].
What I'm trying to do is generate a migration that would add the field to the table and also populate my existing users with a (sort of) unique "secret_code".
class AddSecretCodeToUsers < ActiveRecord::Migration
def self.up
add_column :users, :secret_code, :string
User.update_all ["secret_code =?", Digest::SHA1.hexdigest([Time.now, rand].join)[1..12]]
end
def self.down
remove_column :users, :secret_code
end
end
The problem is that this migration populate all the existing users with the same secret code!
One solution would be NOT to use update_all and run a loop to fetch every user and send an update to each one, but in this case my migration would be extremely slow.
Is there a way to send a "unique" random value to an update_all method?
Thanks,
Augusto
A: Try changing it to Digest::SHA1.hexdigest([Time.now, rand].to_s) but personally I'd create a rake task to the above as it's not really a migration.
Your rake task would do
User.all.each do |u|
u.update_attribute(:secret_code, Digest::SHA1.hexdigest([Time.now, rand].to_s))
end
However, for your migration I'd also add t.string :secret_code, :default => Digest::SHA1.hexdigest([Time.now, rand].to_s)
to the attribute so that it is added on newly created records.
A: For MySQL, you could throw this right in your self.up:
connection.execute(%Q{
update users
set secret_code = substring(sha1(rand()) from 1 for 12)
})
PostgreSQL doesn't have SHA1 support by default but it does have MD5 and that's probably good enough for this:
connection.execute(%Q{
update users
set secret_code = substring(md5(random()::varchar) from 1 for 12)
})
If you have the pgcrypto package installed then you could use SHA1 for both.
Both of those will let the database do all the work and avoid all the overhead of round-tripping your whole table. You can play around with what you hash a bit as well, if you wanted to mix the time in:
md5(random()::varchar || now()::varchar) -- PostgreSQL
sha(rand() || now() ) -- MySQL
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608481",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to create memory DC with 24 bits per pixel? I need it to work with RGB24 data using GDI functions (specifically StretchBlt() which is pretty fast) and I can't use CreateCompatibleDC() since it can create memory DC only with color depth of other DC. Usually it's used with screen DC (by transmitting NULL pointer to function) and usually screen has color depth of value 32. In addition I can't rely on it, 'coz if screen settings are changed my application probably won't work.
So I need some way to create memory DC with specific certain color depth. So far I've found only one way with using CreateDC() function but it requires many device specific parameters and seems somewhat unreliable for me. Moreover there are too many fields to be filled with appropriate values to call CreateDC().
Is there some easier way to create specific memory DC and not rely on some devices? Or even if to create memory DC with 24 bpp?
P.S. I need it for some fast graphics. I've tried manual adding alpha channel to bitmap for using it with compatible to screen 32bpp memory DC and it worked out, but was too slow. And as I said above, I can't rely on screen settings which can be changed.
A: Bits-per-pixel does not really depend on a DC, but on the bitmap selected into it. Create a 24bpp bitmap with CreateDIBSection then select it into a memory DC.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608490",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: What is a container app in iPhone? Our client wants us to make a container app, but I am not exactly sure what he means by this. I have to extend the functionality of his existing app but he does not wish to share his code with me.. so he says I should make a container app... I know it something similar to making in app purchases but can any one elaborate ?
A: Note: you should definitely clarify this with your client instead of this community.
I guess your client wants to have an App-in-App structure that you find in various iOS applications in the AppStore. E.g. the three20 framework offers a launcher that is similar to the Springboard of the iPhone/iPad/iPod where you can put multiple apps (which aren't necessarily independent apps).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608491",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: MySQL foreign keys with non-identifying relationships All I need is to create 2 tabeles with next structure:
The SQL:
CREATE TABLE IF NOT EXISTS `ds_cats` (
`id` int(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `module_news_cats` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parent` int(11) NOT NULL,
`cat_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_module_news_cats_module_news_cats` (`parent`),
KEY `fk_module_news_cats_ds_cats1` (`cat_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
ALTER TABLE `module_news_cats`
ADD CONSTRAINT `fk_module_news_cats_ds_cats1` FOREIGN KEY (`cat_id`) REFERENCES `ds_cats` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `fk_module_news_cats_module_news_cats` FOREIGN KEY (`parent`) REFERENCES `module_news_cats` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
But when I try to insert first row to my table "module_news_cats", I recive next error:
#1452 - Cannot add or update a child row: a foreign key constraint fails (`empty`.`module_news_cats`, CONSTRAINT `fk_module_news_cats_module_news_cats` FOREIGN KEY (`parent`) REFERENCES `module_news_cats` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION)
Question:
How I can create table which will have an index with non-identifying relationship to the anther index in the same table? Some rows will have parents, and some not.
A: I think you just need to allow NULLs in module_news_cats.parent:
CREATE TABLE IF NOT EXISTS `module_news_cats` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parent` int(11) NULL, -- Change this
`cat_id` int(11) NOT NULL,
PRIMARY KEY (`id`),
KEY `fk_module_news_cats_module_news_cats` (`parent`),
KEY `fk_module_news_cats_ds_cats1` (`cat_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
and then if there isn't a parent, create the row with a NULL in parent.
A: Your 'parent' field cannot be empty (NULL) if you insert a record, which means that every record you insert should refer to a parent ID (which is impossible if there are no entries in your table yet).
If you make the 'parent' field in the module_news_cats table nullable:
ALTER TABLE `module_news_cats` CHANGE `parent` `parent` INT( 11 ) NULL DEFAULT NULL
you should be able to insert records that have no parent ID associated (just supply NULL instead of a value).
A: You could make the parent column in the module_news_cats table nullable.
Then for rows that have no parents populate the parent column with null.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608493",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Visual studio setting or extension to highlight edited lines? I want to be able to see background highlighting on lines I have edited in Visual Studio 2010.
I know the thin strip next to the line numbers column shows edits in Green, but this isn't large enough/obvious enough.
Is there any setting or extension to help me out?
I want something like VS10x Method Block Highlighter that comes with the VS10x Code Map extension, but I was wondering if there were any options that are free or automatically highlight edited lines.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608495",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Crystal Reports export to HTML I use CrystalReports 13 (13.0.2000.0) in an ASP.NET 4.0 application.
I need to export report in HTML because i want a static report page, without reporviewer that allows user interaction.
If i try the following code:
Source1.ReportDocument.ExportToHttpResponse(
CrystalDecisions.Shared.ExportFormatType.HTML32 /*or HTML40*/
, this.Response , false, "report");
Application generates an error (Detail: Export in HTTP response in HTML format is not supported.)
If i try ReportExporter, HTML32 and HTML40 are not available ase ExportFormat.
Can someone help?
A: Report can be viewed in HTML as
MemoryStream oStream; // using System.IO
oStream = (MemoryStream)
rd.ExportToStream(
CrystalDecisions.Shared.ExportFormatType.HTML40);
Response.Clear();
Response.Buffer = true;
Response.ContentType = "text/html";
Response.BinaryWrite(oStream.ToArray());
Response.End();
But the format may suffer.
Reference: How to Export Crystal Report in ASP.NET
A: Because you marked it up I thought I'd upgrade it to an answer for closure and the rep:
you could save the html document to disk and then use a redirect to that as a workaround but I can't find any other way of doing it. if you are going to do it that way make sure you add uniqueness to the fime name (I find datetime is a useful string) to support concurrency,
MD
A: Would pdf help (the examples that I have seen use pdf export)? if so that is easy to do but does require that your users have acrobat reader installed. From the error it seems that exporting to an http response in html format was not implemented at release but there may be a patch to fix it so try patching to latest version,
MD
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608498",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Rails by Example (by Michael Hartl), Lesson 9, Sign In tests won't pass I am following Lesson 9 for sign-in, yet the signin test just won't pass! I followed the code to the letter and it still wont pass.
when testing with the browser - the sign in works with no errors..
Failures:
1) SessionsController POST 'create' with valid email and password should sign the user in
Failure/Error: controller.current_user.should == @user
expected: #
got: nil (using ==)
# ./spec/controllers/sessions_controller_spec.rb:55:in `block (4 levels) in '
2) SessionsController POST 'create' with valid email and password should redirect to the user show page
Failure/Error: response.should redirect_to(user_path(@user))
Expected block to return true value.
# ./spec/controllers/sessions_controller_spec.rb:61:in `block (4 levels) in '
Finished in 5.12 seconds
7 examples, 2 failures
Failed examples:
rspec ./spec/controllers/sessions_controller_spec.rb:53 # SessionsController POST 'create' with valid email and password should sign the user in
rspec ./spec/controllers/sessions_controller_spec.rb:59 # SessionsController POST 'create' with valid email and password should redirect to the user show page
As you can see, the test controller.current_user.should == @user returns nil for some reason.
Please help me understand this..
Thank you
SessionHelper
module SessionsHelper
def sign_in(user)
cookies.permanent.signed[:remember_token] = [user.id, user.salt]
self.current_user= user
end
def signed_in?
!self.current_user.nil?
end
def current_user=(user)
@current_user = user
end
def current_user
@current_user ||= user_from_remember_token
end
private
def user_from_remember_token
User.authenticate_with_salt(*remember_token)
end
def remember_token
cookies.signed[:remember_token] || [nil, nil]
end
end
Session controller
class SessionsController < ApplicationController
def new
@title = "Sign In"
end
def create
user = User.authenticate(params[:session][:email], params[:session][:password])
if user.nil?
flash.now[:error] = "Invalid email/password"
@title = "Sign In (right this time)"
render 'new'
else
#sign in the user
sign_in @user
redirect_to user
end
end
def destroy
end
end
User Model
require 'digest'
class User < ActiveRecord::Base
attr_accessor :password
attr_accessible :name, :email, :password, :password_confirmation
email_regex = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :name, :presence => true,
:length => {:minimum => 2, :maximum => 50}
validates :email, :presence => true, :format => {:with => email_regex}, :uniqueness => {:case_sensitive => false }
#Automatically creates the virtual password confimration attribute
validates :password, :presence => true,
:confirmation => true,
:length => {:within => 6..40}
before_save :encrypt_password
def has_password?(submitted_password)
self.salt = make_salt if new_record?
encrypted_password == encrypt(submitted_password)
end
def self.authenticate(email, submitted_password)
user = find_by_email(email)
return nil if user.nil?
return nil if user.has_password?(submitted_password)
end
def self.authenticate_with_salt(id, cookie_salt)
user = find_by_id(id)
(user && user.salt == cookie_salt) ? user : nil
end
private
def encrypt_password
self.salt = make_salt unless has_password?(password)
self.encrypted_password = encrypt(password)
end
def encrypt(string)
secure_hash("#{salt}--#{string}")
end
def make_salt
secure_hash("#{Time.now.utc}--#{password}")
end
def secure_hash(string)
Digest::SHA2.hexdigest(string)
end
end
session controller spec
require 'spec_helper'
describe SessionsController do
render_views
describe "GET 'new'" do
it "should be successful" do
get 'new'
response.should be_success
end
it "should have the right title" do
get :new
response.should have_selector("title", :content => "Sign In")
end
end
describe "POST 'create'" do
describe "invalid login" do
before(:each) do
@attr = {:email => "email@example.com", :password => "invalid"}
end
it "should re-render the new page" do
post :create, :session => @attr
response.should render_template('new')
end
it "should have the right title" do
post :create, :session => @attr
response.should have_selector("title", :content => "Sign In (right this time)")
end
it "should have flash.now message" do
post :create, :session => @attr
flash.now[:error].should =~ /invalid/i
end
end
describe "success" do
before(:each) do
@user = Factory(:user)
@attr = { :email => @user.email, :password => @user.password }
end
it "should sign the user in" do
post :create, :session => @attr
controller.current_user.should == @user
controller.should be_signed_in
end
it "should redirect to the user show page" do
post :create, :session => @attr
response.should redirect_to(user_path(@user))
end
end
end
end
A: I'm assuming you've completed past Section 9.3.3 and added the authenticate class method to your user model.
If you check your authenticate (9.17) class method it has user = find_by_email(email). You should check that your factory is in fact creating a user in your test database first.
Update
Do you have this in SessionsHelper
def signed_in?
!current_user.nil?
end
Update 2
Remove the following in your SessionsHelper!!
def current_user=(user)
@current_user = user
end
Hartl is quite specific as to why this writer is removed
If we did this, we would effectively replicate the functionality of
attr_accessor, first seen in Section 4.4.5 and used to make the
virtual password attribute in Section 7.1.1.7 The problem is that it
utterly fails to solve our problem: with the code in Listing 9.15, the
user’s signin status would be forgotten: as soon as the user went to
another page—poof!—the session would end and the user would be
automatically signed out.
To avoid this problem, we can find the session user corresponding to
the cookie created by the code in Listing 9.12, as shown in Listing
9.16.
It is instead replaced by
def current_user
@current_user ||= user_from_remember_token
end
First, Listing 9.16 uses the common but initially obscure ||= (“or
equals”) assignment operator (Box 9.4). Its effect is to set the
@current_user instance variable to the user corresponding to the
remember token, but only if @current_user is undefined.8 In other
words, the construction calls the user_from_remember_token method the
first time current_user is called, but on subsequent invocations
returns @current_user without calling user_from_remember_token.
A: I had the same issue. I understood also that it should be replaced. But it should not both methods are needed.
def current_user=(user)
@current_user = user
end
def current_user
@current_user ||= user_from_remember_token
end
A: Took me forever to track this one down...
The rspec error message:
1) SessionsController POST 'create' with valid email and password should sign the user in
Failure/Error: controller.current_user.should == @user
NoMethodError:
undefined method `current_user' for #<SessionsController:0x00000005426eb8>
# ./spec/controllers/sessions_controller_spec.rb:51:in `block (4 levels) in <top (required)>'
You want to edit app/helpers/sessions_helper.rb :
WRONG:
def current_user=(user)
@current_user = user ||= user_from_remember_token
end
RIGHT:
def current_user
@current_user ||= user_from_remember_token
end
I clearly wasn't paying close enough attention when I was following along and unfortunately the error message from rspec wasn't as helpful as it normally is. Hope this helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Delphi Word automation - print merged document My D5 application can currently mail merge multiple members data to a Word document using:
wrdapp := CreateOleObjct(word.application);
wrdDoc := wrdApp.Document.Open(TemplateLocation);
wrdMailMerge := wrdDoc.MailMerge;
populateMailMergeDateFile;
wrdMailMerge.execute;
and then
wrdDoc.Saved := False;
wrdDoc.Close(False);
wrdApp.Visible := True;
I would like to offer the option of passing the merged document straight to the printer. However I cannot find the code which allows this to happen
wrdDoc.PrintOut;
wrdDoc.Saved := False;
wrdDoc.Close(False);
Prints out the template document with no merged data.
wrdDoc.Saved := False;
wrdDoc.Close(False);
wrdDoc.PrintOut;
Displays a variant object error.
wrdMailMerge.PrintOut;
Displays an automation errors.
I've tried using True instead of False as well. Can anybody advise me as to how to print the merged document correctly?
many thanks
A: In my mailmerge code, I set MailMerge.Destination to wdSendToNewDocument before executing the merge, then afterwards I call WordApplication.ActiveDocument.Printout.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608500",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Data in ListActivity not cached when going back to it I've got a ListActivity filled by an adapter extending SimpleCursorAdapter. Some category buttons can be clicked, which fills the listview with a list of articles in the corresponding category. When clicking on an item in the list a new activity is launched which shows the detail of the article.
Now, when pressing the back button in that article detail page, no data is shown. Does it have to reload the data from the DB? Isn't the data supposed to be cached?
Moreover, when going back to the myListActivity, onCreate is not called. Only onResume is called. Shall I do everything in onResume? In that case what's the best way to keep the value of the current category and retrieve it when going back to the ListActivity from the article detail?
Thanks
public class Home extends ListActivity implements OnItemClickListener{
private DBAdapter dbAdapter;
private HomeListAdapter adapter; //extends SimpleCursorAdapter
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home);
// open database
dbAdapter = new DBAdapter(this);
dbAdapter.open();
/* more stuff */
getArticlesbyCat(category);
/* more stuff */
}
private void getArticles(int category){
Cursor c = dbAdapter.fetchArtByCat(category);
c.moveToFirst();
startManagingCursor(c);
String[] from = new String[] {};
int[] to = new int[] {};
setListAdapter(new HomeListAdapter(this, R.layout.article_row, c, from, to));
adapter.notifyDataSetChanged();
c.close();
}
@Override
public void onItemClick(AdapterView arg0, View v, int position, long arg3) {
/* Go to article page */
}
@Override
protected void onPause() {
super.onPause();
// close database
dbAdapter.close();
}
}
EDIT
public class HomeListAdapter extends SimpleCursorAdapter {
private int mLayout;
private Cursor mCursor;
private Resources mResources;
// Column index
private int mCatInd;
private int mURLPicInd;
private int mIntroInd;
private int mTitleInd;
private LayoutInflater mLayoutInflater;
private final ImageDownloader mImageLoader;
private final class ViewHolder {
public TextView category;
public ImageView image;
public TextView intro;
public TextView title;
}
public HomeListAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
super(context, layout, c, from, to);
this.mLayout = layout;
this.mCursor = c;
this.mCatInd = mCursor.getColumnIndex(DBAdapter.KEY_CATEGORY_NAME);
this.mURLPicInd = mCursor.getColumnIndex(DBAdapter.KEY_URL_PIC);
this.mIntroInd = mCursor.getColumnIndex(DBAdapter.KEY_INTRO);
this.mTitleInd = mCursor.getColumnIndex(DBAdapter.KEY_TITLE);
this.mLayoutInflater = LayoutInflater.from(context);
mResources = context.getResources();
mImageLoader = new ImageDownloader(mResources,
((BitmapDrawable)mResources.getDrawable(R.drawable.default_row_pic)).getBitmap(), 1);
}
public View getView(int position, View convertView, ViewGroup parent) {
if (mCursor.moveToPosition(position)) {
ViewHolder viewHolder;
if (convertView == null) {
convertView = mLayoutInflater.inflate(mLayout, null);
viewHolder = new ViewHolder();
viewHolder.category = (TextView) convertView.findViewById(R.id.cat);
viewHolder.image = (ImageView) convertView.findViewById(R.id.picture);
viewHolder.title = (TextView) convertView.findViewById(R.id.title);
viewHolder.intro = (TextView) convertView.findViewById(R.id.intro);
viewHolder.intro.setMaxLines(3);
convertView.setTag(viewHolder);
}
else {
viewHolder = (ViewHolder) convertView.getTag();
}
String category = mCursor.getString(mCatInd);
String title = mCursor.getString(mTitleInd);
String intro = mCursor.getString(mIntroInd);
String url_pic = mCursor.getString(mURLPicInd);
viewHolder.category.setText(category);
viewHolder.title.setText(title);
viewHolder.intro.setText(intro);
if(!url_pic.equals("")){
mImageLoader.download(url_pic, (ImageView) viewHolder.image);
}
else {
viewHolder.image.setImageResource(R.drawable.default_row_pic);
}
}
return convertView;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: XCode 4. Keyboard doesn't hide on iPad I have a problem with my iPad app.
I perform authorization in social networks (facebook, twitter etc.) to post information from app. Several webviews change each other (login, content of post, captcha). They have text fields and I have to show keyboard. After posting I return to some start view with posted information.
It works good, but after posting first news something goes wrong. When I post news one more time, after return keyboard is still on the screen.
I saw here some questions familiar to this, but they wasn't useful.
I tried to make resignFirstRersponder to all webViews, textFields and textViews. Also i\I tried to implement method disablesAutomaticKeyboardDismissal but it doesn't help me.
I don't know where search for problem...
So questions are: why could this happened? How can I solve this? fnd How can I get some information about keyboard? (is it visible, what object has focus etc., anything that could be useful to solve problem)
And one more thing. I have similar app for iPhone and it seems to work correct.
A: Try this:
[searchBar performSelector:@selector(resignFirstResponder) withObject:nil afterDelay:0.1];
Make sure to replace searchBar with the object that is the actual First responder in your case
A: Problem is fixed, finally. The reason was the way I had changed visible view. I set a new value to view property of ViewController. And as previous view contains text field with focus on it, focus wasn't lost before changing view (and keyboard was still on the screen), but I had lost handler to previous view.
Solution is: resignFirstResponder to all (or current) inputs BEFORE changing view.
Hope, it's clear. Thanks for your help!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608502",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PyPy on Windows 7 x64? I am trying to use PyPy on a Windows 7 x64 machine but do not find any way to do it.
Apparently there is a win32 binary, but no x64 binary or installation guide.
I am currently using Python 2.7.2 win64 (Python 2.7.2 (default, Jun 12 2011, 14:24:46) [MSC v.1500 64 bit (AMD64)] on win32).
Installation from sources raised the following error:
[translation:ERROR] WindowsError: [Error 193] %1 is not a valid Win32 application
Does anyone have a guide/hint to use PyPy on a win64?
Or is it just not possible?
A: There's no version available for 64 bit Python on Windows. You appear to have the following options:
*
*Download the source to PyPy and port it to 64 bit.
*Switch to 32 bit Python.
Option 2 looks more tractable.
A: Just an update on this issue if anyone read it nowadays: PyPy seems to have solved their issues with Windows x64, you can download the 32-bit version of PyPy and it will work flawlessly under Windows 7 x64 (I even have a 64-bit python install beside, and pypy is working nicely along, I just have to specify the full path to pypy to use it for the scripts I need).
A: PyPy is not compatible with 64bit windows. Primary reason is that sizeof(void*) != sizeof(long) which is a bit annoying. Contributions are more than welcome :)
A: 64-bit PyPy now supports Windows. They wrote a post about how they were finally able to add support (https://doc.pypy.org/en/latest/windows64.html). If you go to their downloads page, they have 64-bit Windows downloads available (https://www.pypy.org/download.html).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: using precompiled header from different project I have two projects in Visual Studio 2010 that I want to share the precompiled header outputs .pch(i) file: one builds it and the other should only use it.
After Clean, and Rebuild Project1, the .pchi file is created.
Rebuild Project2 does a strange thing, it Deletes the .pchi file and then complains that can't find it for compilation.
What should I change to stop this behaviour (possibly in the file "Microsoft.Cpp.x64.Intel C++ Compiler XE 12.0.targets"?) ?
I've set the file to read-only, then of course Project2 Build complains:
C:\Program Files
(x86)\MSBuild\Microsoft.Cpp\v4.0\Platforms\x64\PlatformToolsets\Intel
C++ Compiler XE 12.1\Microsoft.Cpp.x64.Intel C++ Compiler XE
12.1.targets(84,5): error MSB3061: Unable to delete file ".pchi".
Access to the path '.pchi' is denied.
at the line#84 the .targets file has
< Delete Condition="'%(ClCompile.DebugInformationFormat)' != '' and
'%(ClCompile.DebugInformationFormat)' != 'OldStyle' and
'%(ClCompile.ProgramDataBaseFileName)' != '' and
!Exists(%(ClCompile.ProgramDataBaseFileName))
and '%(ClCompile.UseMSVC)'!='true' and
'%(ClCompile.InterproceduralOptimization)'!='MultiFile' and
'%(ClCompile.LevelOfStaticAnalysis)'!='Brief' and
'%(ClCompile.LevelOfStaticAnalysis)'!='Medium' and
'%(ClCompile.LevelOfStaticAnalysis)'!='Verbose'"
Files="%(ClCompile.PrecompiledHeaderOutputFile)i" />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to get CPU Usage of a Silverlight application from code? I need to build a widget which would show (and monitor) CPU usage by a Silverlight instance (the control will be part of the silverlight application and would track the running instance). I could not find Process/PerformanceMonitor class in Silverlight.
Is there any existing API or some way to do this?
Edit 1) Same question being answered for non-Silverlight: How to get the CPU Usage in C#?
Thanks for your interest.
A: You should be about to use System.Windows.Analytics.AverageProcessorLoad to get the CPU load.
http://msdn.microsoft.com/en-us/library/system.windows.analytics.averageprocessorload%28VS.95%29.aspx
Not sure if OOB or Elevated Trust is required for this to work.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: In Android how to decode a jpeg in cmyk color format? I'm trying to decode a jpeg that is in CMYK color format. BitmapFactory returns null. I googled around but with no luck. Is it possibile Android team did not the right job supporting all kind of color format?
I'm using Android 2.2.
Thank you so much.
A: Found the solution: loading the JPEG using the external library libjpeg compiled with NDK. It has been a hard work, but I did it!
A: It's very possible I'd say:
http://code.google.com/p/skia/issues/detail?id=69
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608507",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Combine two maven based projects on two frameworks I have two maven projects say MvnSpring and MvnGuice.MvnSpring is working on spring and hibernate frame works.
And MvnGuice is working on google guice and mybatis. I need to combine both the features together.
Both are following singleton pattern. I need to get some class of MvnSpring in MvnGuice while coding. So that I created a jar of MvnSpring and put it in .m2 repository and give the dependacy details in MvnGuice. Now I can import classes of MvnSpring in MvnGuice classes.MvnSpring uses spring dependency injection and MvnGuice uses guice dependency injection for object creation. Now in MvnSpring flow is MSserviceImpl(implements MSservice) > MSdaoImpl(implements MSdao). Now I need to call MSService class from MvnGuice. Then at run time it shows error like MSService class is null. Then I made a guice dependency injection for MSService class in MvnGuice. Now the control reaches MSserviceImpl but now MSdao is null at here. Is it possible to start MvnSpring along with MvnGuice. I hope then I can solve the issue.
A: While Spring and Guice are targeted at the same problem, IoC, they take very different approaches to solve it. They differ both in functionality and in how they are configured, where Spring has bean definitions and Guice uses bindings.
Fortunately they do have common grounds in that they both support JSR-330, a standards specification that defines a set of annotations. This enables you to write your singletons and describe the injections that they need without depending on either Spring or Guice.
This way you can share your singletons between projects irregardless of the framework you use in a particular project. I would not recommend using both Guice and Spring in the same project, except if there's a clearly defined separation between them. For instance you might use Guice for a module that is used by Spring code via a defined API that hides the fact that it internally is based on Guice.
A: There was already mentioned JSR-330.
For some cases it can be not enough, e.g., you have code:
final String className = config.getProperty(«serviceImpl»);
// Class.forName(name) and check required interface for type safety
final Class<? extends Service> serviceClass = Reflection.classForName(className, Service.class);
final Service service = injector.getInstance(serviceClass);
In different DI environments you are supposed to support both com.guice.inject.Injector.getInstance() and org.springframework.context.ApplicationContext.getBean() implementations.
There is the draft solution sdif4j Simple Dependency Injection Facade.
The idea of this project is to encapsulate different DI frameworks logic with own abstraction to extend default JSR-330 possibilities. Note, there is no public releases yet, but you can find ideas how to solve your problem or make an internal release in a fork.
The general issue, is that your both MvnSpring and MvnGuice projects are supposed to be based on JSR-330 (instead of guice/spring annotations) and org.sdif4j:sdif4j-api (or your own abstraction; only if Injector functionality is required). It is recommended to make guice and spring dependencies optional (to compile but not export) to allow the library clients to choose the DI themselves.
In your MvnCompineGuiceAndSpring you just declare sdif4j-guice or sdif4j-spring dependency (it is similar to slf4j usage) and configure your DI environment. You can find different examples in testing subproject.
Some more notes:
Spring default scope is singleton, Guice - prototype (Spring terminology). So, if you want a prototype bean, you can use:
@org.springframework.context.annotation.Scope("prototype")
@javax.inject.Named
public class TestPrototype {
}
The Spring @Scope annotation should be ignored by guice even if spring does not present in your classpath.
Also you have to declare all your Singleton beans with @javax.inject.Named and @javax.inject.Singleton annotation to support both Spring and Guice, like this:
@javax.inject.Named
@javax.inject.Singleton
public class TestSingleton implements ITestSingleton {
public TestSingleton() {
}
}
As with @Scope annotation, you can use @ImplementedBy(@ProvidedBy) guice annotations on your code (when feasible; be careful with it, in general it is not a good practice), that should be also ignored in Spring DI (in both cases if Spring exists in classpath or not).
Hope, that's clear.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Java POI : How to read Excel cell value and not the formula computing it? I am using Apache POI API to getting values from an Excel file.
Everything is working great except with cells containing formulas. In fact, the cell.getStringCellValue() is returning the formula used in the cell and not the value of the cell.
I tried to use evaluateFormulaCell() method but it's not working because I am using GETPIVOTDATA Excel formula and this formula is not implemented in the API:
Exception in thread "main" org.apache.poi.ss.formula.eval.NotImplementedException: Error evaluating cell Landscape!K11
at org.apache.poi.ss.formula.WorkbookEvaluator.addExceptionInfo(WorkbookEvaluator.java:321)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluateAny(WorkbookEvaluator.java:288)
at org.apache.poi.ss.formula.WorkbookEvaluator.evaluate(WorkbookEvaluator.java:221)
at org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.evaluateFormulaCellValue(HSSFFormulaEvaluator.java:320)
at org.apache.poi.hssf.usermodel.HSSFFormulaEvaluator.evaluateFormulaCell(HSSFFormulaEvaluator.java:213)
at fromExcelToJava.ExcelSheetReader.unAutreTest(ExcelSheetReader.java:193)
at fromExcelToJava.ExcelSheetReader.main(ExcelSheetReader.java:224)
Caused by: org.apache.poi.ss.formula.eval.NotImplementedException: GETPIVOTDATA
at org.apache.poi.hssf.record.formula.functions.NotImplementedFunction.evaluate(NotImplementedFunction.java:42)
A: There is an alternative command where you can get the raw value of a cell where formula is put on. It's returns type is String. Use:
cell.getRawValue();
A: If the need is to read values from Excel sheets and having them as strings then, for example to present them somewhere or to use them in text file formats, then using DataFormatter will be the best.
DataFormatter is able to get a string from each cell value, whether the cell value itself is string, boolean, number, error or date. This string then looks the same as Excel will show it in the cells in it's GUI.
Only problem are formula cells. Up to apache poi 5.1.0 a FormulaEvaluator is needed to evaluate the formulas while using DataFormatter. This fails when apache poi is not able evaluating the formula. From 5.2.0 on the DataFormatter can be set to use cached values for formula cells. Then no formula evaluation is needed if Excel had evaluated the formulas before.
Complete example:
import org.apache.poi.ss.usermodel.*;
import java.io.FileInputStream;
class ReadExcel {
public static void main(String[] args) throws Exception {
Workbook workbook = WorkbookFactory.create(new FileInputStream("./ExcelExample.xlsx"));
// up to apache poi 5.1.0 a FormulaEvaluator is needed to evaluate the formulas while using DataFormatter
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
DataFormatter dataFormatter = new DataFormatter(new java.util.Locale("en", "US"));
// from 5.2.0 on the DataFormatter can set to use cached values for formula cells
dataFormatter.setUseCachedValuesForFormulaCells(true);
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
for (Cell cell : row) {
//String value = dataFormatter.formatCellValue(cell, evaluator); // up to apache poi 5.1.0
String value = dataFormatter.formatCellValue(cell); // from apache poi 5.2.0 on
System.out.println(value);
}
}
workbook.close();
}
}
A: For formula cells, excel stores two things. One is the Formula itself, the other is the "cached" value (the last value that the forumla was evaluated as)
If you want to get the last cached value (which may no longer be correct, but as long as Excel saved the file and you haven't changed it it should be), you'll want something like:
for(Cell cell : row) {
if(cell.getCellType() == Cell.CELL_TYPE_FORMULA) {
System.out.println("Formula is " + cell.getCellFormula());
switch(cell.getCachedFormulaResultType()) {
case Cell.CELL_TYPE_NUMERIC:
System.out.println("Last evaluated as: " + cell.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println("Last evaluated as \"" + cell.getRichStringCellValue() + "\"");
break;
}
}
}
A: Previously posted solutions did not work for me. cell.getRawValue() returned the same formula as stated in the cell. The following function worked for me:
public void readFormula() throws IOException {
FileInputStream fis = new FileInputStream("Path of your file");
Workbook wb = new XSSFWorkbook(fis);
Sheet sheet = wb.getSheetAt(0);
FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();
CellReference cellReference = new CellReference("C2"); // pass the cell which contains the formula
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol());
CellValue cellValue = evaluator.evaluate(cell);
switch (cellValue.getCellType()) {
case Cell.CELL_TYPE_BOOLEAN:
System.out.println(cellValue.getBooleanValue());
break;
case Cell.CELL_TYPE_NUMERIC:
System.out.println(cellValue.getNumberValue());
break;
case Cell.CELL_TYPE_STRING:
System.out.println(cellValue.getStringValue());
break;
case Cell.CELL_TYPE_BLANK:
break;
case Cell.CELL_TYPE_ERROR:
break;
// CELL_TYPE_FORMULA will never happen
case Cell.CELL_TYPE_FORMULA:
break;
}
}
A: If you want to extract a raw-ish value from a HSSF cell, you can use something like this code fragment:
CellBase base = (CellBase) cell;
CellType cellType = cell.getCellType();
base.setCellType(CellType.STRING);
String result = cell.getStringCellValue();
base.setCellType(cellType);
At least for strings that are completely composed of digits (and automatically converted to numbers by Excel), this returns the original string (e.g. "12345") instead of a fractional value (e.g. "12345.0"). Note that setCellType is available in interface Cell(as of v. 4.1) but deprecated and announced to be eliminated in v 5.x, whereas this method is still available in class CellBase. Obviously, it would be nicer either to have getRawValue in the Cell interface or at least to be able use getStringCellValue on non STRING cell types. Unfortunately, all replacements of setCellType mentioned in the description won't cover this use case (maybe a member of the POI dev team reads this answer).
A: SelThroughJava's answer was very helpful I had to modify a bit to my code to be worked .
I used https://mvnrepository.com/artifact/org.apache.poi/poi and https://mvnrepository.com/artifact/org.testng/testng as dependencies .
Full code is given below with exact imports.
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.util.CellReference;
import org.apache.poi.sl.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellType;
import org.apache.poi.ss.usermodel.CellValue;
import org.apache.poi.ss.usermodel.FormulaEvaluator;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ReadExcelFormulaValue {
private static final CellType NUMERIC = null;
public static void main(String[] args) {
try {
readFormula();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void readFormula() throws IOException {
FileInputStream fis = new FileInputStream("C:eclipse-workspace\\sam-webdbriver-diaries\\resources\\tUser_WS.xls");
org.apache.poi.ss.usermodel.Workbook workbook = WorkbookFactory.create(fis);
org.apache.poi.ss.usermodel.Sheet sheet = workbook.getSheetAt(0);
FormulaEvaluator evaluator = workbook.getCreationHelper().createFormulaEvaluator();
CellReference cellReference = new CellReference("G2"); // pass the cell which contains the formula
Row row = sheet.getRow(cellReference.getRow());
Cell cell = row.getCell(cellReference.getCol());
CellValue cellValue = evaluator.evaluate(cell);
System.out.println("Cell type month is "+cellValue.getCellTypeEnum());
System.out.println("getNumberValue month is "+cellValue.getNumberValue());
// System.out.println("getStringValue "+cellValue.getStringValue());
cellReference = new CellReference("H2"); // pass the cell which contains the formula
row = sheet.getRow(cellReference.getRow());
cell = row.getCell(cellReference.getCol());
cellValue = evaluator.evaluate(cell);
System.out.println("getNumberValue DAY is "+cellValue.getNumberValue());
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608511",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "71"
}
|
Q: Is there any even function that occurs in the case of deleting the app? The iPhone app i developed save user data (id, pw) to keychain of iOS by using open source SFHFKeychainUtils
Problem is that the id,pw data still remains intact upon deleting the app,
which cause trouble when reinstalling the app.
Would it be possible to delete the id, pw in the keychaing along with the app?
Is there any even function that occurs in the case of deleting the app?
A: No, your app does not get notified of its deletion. AFAIK, the OS keeps the keychain data for some time (a few days or so) and then deletes it automatically.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: .htaccess to redirect to sub folder without causing errors on ajax JS calls to BE dir I need help with setting up 100% working .htaccess , I Googled a lot, came to several suggestions, part-working ones but still not 100%. The "problem" is quite simple: the site is hosted at: public_html/ dir, but my site is in /public_html/a/b/FE/ and the back-end at: public_html/a/b/BE/ (its PHP), inside i use relative path (require ('../BE/something.php')). So i want a fully working path redirect from public_html/ to public_html/a/b/FE/.
The .htaccess that "worked" the most is:
RewriteEngine On
Options +FollowSymlinks
RewriteBase /
# handle domain root and skip subfolders
RewriteCond %{HTTP_HOST} www.site.com
RewriteCond %{REQUEST_URI} !^/a/b/FE
RewriteCond %{REQUEST_URI} \..+$
RewriteRule ^(.*)$ a/b/FE/$1 [L]
# add trailing slash to subfolders (eg abc to: abc/)
RewriteCond %{HTTP_HOST} www.site.com
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} [^/]$
RewriteRule ^(.*)$ $1/ [L,R=301]
# handle files in subfolders
RewriteCond %{HTTP_HOST} www.site.com
RewriteCond %{REQUEST_URI} !^/a/b/FE
RewriteRule ^(.*)$ a/b/FE/$1/ [L]
It loads the site, but for example i have a captcha.php at /public_html/a/b/BE/captcha.php which generates an image and it cant find the file. I use it as:
<img src="../BE/captcha.php" />
also, in the JS that sits in the FE dir, i call AJAX calls to some back end modules, with their relative location: '../BE/some_module.php' . This causes error as well
thanks!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7608525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.