text stringlengths 8 267k | meta dict |
|---|---|
Q: How to select the default selection on the item in my list box using jquery Using this code I am inserting the code into listbox.
<select id="lstCodelist" size="17" name="lstCodelist" style="width:100%;height:280px;background-color:#EFEFFB;"></select>
Using this code I am displaying data in to lstCodelist box.
$.fn.fillSelectDD = function (data) {
return this.clearSelectDD().each(function () {
if (this.tagName == 'SELECT') {
var dropdownList = this;
$.each(data, function (index, optionData) {
var option = new Option(optionData.Text, optionData.Value);
if ($.browser.msie) {
dropdownList.add(option);
}
else {
dropdownList.add(option, null);
}
});
}
});
}
This is the function I am calling to insert into one list box to other list.
function DoInsert(ind) {
var sourceIndex = $("#lstAvailableCode").val();
var targetIndex = $("#lstCodelist").val();
var success = 0;
var rightSelectedIndex = $("#lstCodelist").get(0).selectedIndex;
var functionName = "/Ajax/SaveCodeforInsert";
if (ind == "plan") {
functionName = "/Ajax/SaveCodeforInsertForPlan";
}
$.ajax({
type: "POST",
traditional: true,
url: functionName,
async: false,
data: "ControlPlanNum=" + $("#ddControlPlan").val() + "&LevelNum=" + $("#ddlLevel").val() + "&ColumnNum=" + $("#ddlColumn").val() + "&SourcbaObjectID=" + sourceIndex + "&TargetbaObjectID=" + targetIndex + "&userID=<%=Model.userID%>",
dataType: "json",
error: function (data) {
alert("Error Adding Code");
FinishAjaxLoading();
},
success: function (data) {
if (data == 0) { success = 1; } else { success = data; }
// $("#lstCodelist option").eq(1).attr('selected', 'selected')
$("#lstCodelist option:first-child").attr("selected", "selected");
FinishAjaxLoading();
}
});
but using this code in my success function I am not able to select assign or hightlight or select to this lstCodelist box.
// $("#lstCodelist option").eq(1).attr('selected', 'selected')
$("#lstCodelist option:first-child").attr("selected", "selected");
but its not working in my code right now is that I am doing something wrong here?
Thanks
A: I think in selects, just use $("#select_id").val(default_val); to select the value you need.
http://api.jquery.com/val/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: error importing gdata.photos.service in gae servers I'm using python + django in gae python proyect.
I'm working with picasa python api, but in my computer i haven't problems with gdata.photos.service, but when i push project in GAE servers i have this error:
ViewDoesNotExist at /
Tried main in module trazovillena.main.views. Error was: 'module' object has no attribute 'v1_deprecated'
If i comment this line:
import gdata.photos.service
All work fine, buy i can't use google picasa api. I search problem in internet and people say something about init.py but i have all fine in project/gdata/photos and it works in anothers machines, but not in app engine.
You can see Traceback in : http://trazovillena.appspot.com/
Traceback (innermost last)
Switch to copy-and-paste view
/base/python_runtime/python_lib/versions/third_party/django-0.96/django/core/handlers/base.py in get_response
callback, callback_args, callback_kwargs =
resolver.resolve(request.path) ...
▶ Local vars
/base/python_runtime/python_lib/versions/third_party/django-0.96/django/core/urlresolvers.py
in resolve
sub_match = pattern.resolve(new_path) ...
▶ Local
vars
/base/python_runtime/python_lib/versions/third_party/django-0.96/django/core/urlresolvers.py
in resolve
return self.callback, args, kwargs ...
▶ Local vars
/base/python_runtime/python_lib/versions/third_party/django-0.96/django/core/urlresolvers.py
in _get_callback
raise ViewDoesNotExist, "Tried %s in module %s. Error was:
%s" % (func_name, mod_name, str(e)) ...
▶ Local vars
Only difference between error or not error is include gdata-python-cliente api of google http://code.google.com/p/gdata-python-client/ :
import gdata.photos.service
Some idea ?
A lot of thx. Sorry for my poor english.
A: ehm, your site is online, i presume that u are using now Django 1.x instead of the old 0.96 Django provided by appengine ?
A: put gdata/src to your app root folder
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547449",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why does MSDN recommend including object sender in delegate declarations? I was reading this page and I noticed how it said this is standard guidelines:
The .NET Framework guidelines indicate that the delegate type used for an event should take two parameters, an "object source" parameter indicating the source of the event, and an "e" parameter that encapsulates any additional information about the event.
I can understand how having an object sender could be useful in some circumstances, but I could see the exact opposite in others. For example,
*
*What if a class handling the event should not have any knowledge about who fired it? Coupling, cohesion, and all of that.
*In my case, I already have a reference to the object as a member variable. That is how I subscribe to the event. There will only ever be one instance of it so there's no reason to cast the sender object rather than just using the member variable.
*In my program the sender object should not be known at all to the clients. It's hard to explain what I am doing but basically I have a class with an internal constructor within a library that is used by two other classes also within that library. My client classes are subscribing to events from those two classes but the events are originally invoked from this internal class that clients should not have any knowledge of.
*It is confusing to clients of the event handler. Libraries should be simple to understand and in my case, there is no reason to ever use the sender variable. None. Then why include it?
That being said, why does Microsoft indicate that event handlers should follow these guidelines? Isn't it not always the best choice?
EDIT: Thanks for the replies everyone. I've decided to go with the majority and use EventHandler<T> for all my events in this library.
A: You are fighting against the wind, the .NET framework has certain design, rules and guidelines and when using it, if you want to use it correctly, you are supposed to follow those directions.
if you use raw delegates you have all the freedom you want but as stated above if you are declaring a delegate type for an event you should include sender object and EventArgs object as well (base or derived class).
if you break those rules, as I said a moment ago in my answer to your other question: Should I use EventArgs or a simple data type?, you could potentially end up in a situation where your code breaks.
Simplyfying at the maximum, when the framework invokes an OnClick event on a control, the .NET Framework does pass the sender and an EventArgs instance... if the event would not comply, something could break.
if you want full freedom then use simple delegates but not events.
A: First of all, it's important to note that a guideline is not a law.
All hell (or the programmer equivalent) will not break lose if you don't follow the guidelines.
As such, feel free to change the signature of your events appropriately.
However, it is just as important to know why these guidelines were added to begin with, and one big part of the answer(s) to that question is versioning.
By having the following two parts, and only those two parts:
*
*The source of the event, typed as "generic" as possible (note, event signatures were designed long before proper generics were introduced into the system, so object is as generic as can be from back then)
*An object inheriting from EventArgs
then you are designing code that is more resilient to changes.
First of all, since you're not "allowed" to add or remove parameters, all future versions of your event will still have only sender and e.
Secondly, there's a second part to the guideline regarding the e parameter. If you in a new version of your class library decides to change the signature of an event handler by changing the type of the e parameter, you're supposed to make it more specific by descending from your current type, and passing the descendant instead.
The reason for this is that existing code that already handles your current (old) type will still work.
So the entire reasoning behind the guideline is to:
*
*Stay consistent (as others have mentioned)
*Design for the future (by making sure code written against version X of your class still works when you release version X+1, without manual changes to that code)
Now, if any of this is not a concern for your case, feel free to not follow the guideline.
In fact, you can make an event out of an Action and it'll work just fine.
A:
Why? People always ask this. In this end, this is just about a
pattern. By having event arguments packaged in a class you get better
versioning semantics. By having a common pattern (sender, e) it is
easily learned as the signature for all events. I think back to how
bad it was with Win32—when data was in WPARAM versus LPARAM, and
so on. The pattern becomes noise and developers just assume that event
handlers have scope to the sender and arguments of the event.
-Chris Anderson, in Framework Design Guidelines: Conventions, Idioms, and Patterns for Reusable .NET Libraries
If you're a .NET developer and you haven't read that book, you're missing out. It gives you a window ;) into the minds of the Microsoft .NET Framework designers, and a lot of best practices (including the reasoning behind them).
(Plus, you can run FxCop to verify that these practices are being followed.)
A: I think the reason for the pattern is to enforce some consistency. The sender parameter allows re-use of a single handler for multiple publishers (buttons, tables).
To address your points:
1) simply don't use it. That is common and doesn't really hurt any good practice.
2) that's OK, again ignore the sender
3) is in total contradiction of what you said under 2) ...
And for the rest it is the same as 1). You could even consider passing null as sender.
4) "then why include it" - there are other use cases that do require the sender.
But do note this is just a guideline for libraries confirming to the BCL.
Your case sounds more like a specific application (not a library) so feel free to use any parameter scheme you like. The compiler won't complain.
A: Guidelines such as this allow for predictability on the part of the consumer of the event. It also allows for handling of additional scenarios you may never have considered when you created the event, especially if your library is used by third party developers.
It allows the method handling the event to always have the correct object instance at hand as well as basic information regarding why the event was fired.
A: It's just good practice, but you'll be fine as long as you don't need to know about the object that fired the event or any other info related to the object. I for one always include it since you never know when you'll need it.
My suggestion is to stick with it, it does not hurt at all.
A: There would have been nothing wrong, semantically, with having event handlers that are interested in where events came from use a derivative of EventArgs which included such a field. Indeed, there are many situations where that would be cleaner than passing Sender as a separate parameter (e.g. if a keyboard-shortcut processor needs to fire a Click handler for a button, the event shouldn't really be considered to have been raised by the button, but rather raised on the button's behalf). Unfortunately, incorporating that information within an EventArgs-derived type would make it necessary to create a new instance of an EventArgs-derived type every time an event is raised, even if it could otherwise use EventArgs.Empty. Using a separate parameter to pass the information eliminates the need to have every event create a new object instance in that common case.
Although it might have been possible to have handlers that care about where an event came from use a parameter for that, and have those that don't care about it omit the parameter, that would have required that any helper methods and classes which assist with handling event subscriptions would need to have versions for events which did or did not include the parameter. Having all events take two parameters, one of which is of type Object and one of which is of a type derived from EventArgs makes it possible for one helper method or class to be capable of handling all events.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547450",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: Facebook login through android I write an Android application that integrates facebook, but failing in the login to facebook step. What I'm doing basically is to perform authorization and then ask if the session is valid. The answer is always negative. If I'm trying a simple request like:
String response = facebookClient.request("me");
I am getting this response:
{"error":{"message":"An active access token must be used to query
information about the current user.","type":"OAuthException"}}
Maybe I have the wrong hash key (through I read pretty good threads how to get it right). I'd like to know if this is a way to insure key is matching.
I based my code on this - Android/Java -- Post simple text to Facebook wall?, and add some minor changes. This is the code:
public class FacebookActivity extends Activity implements DialogListener
{
private Facebook facebookClient;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.main);//my layout xml
}
public void login(View view)
{
facebookClient = new Facebook("my APP ID");
facebookClient.authorize(this, this);
if (facebookClient.isSessionValid() == true)
Log.d("Valid:", "yes");
else
Log.d("Valid:", "no");
}
}
A: Note that authorize method is asynchronous.
You should implement an onComplete method of DialogListener and make all the work you need (such as graph API me request) there.
A: Use following code in your app:
public class FacebookLogin {
private AsyncFacebookRunner mAsyncRunner;
private Facebook facebook;
private Context mContext;
private String mFName;
public static final String[] PERMISSIONS = new String[] {"email", "publish_checkins", "publish_stream","offline_access"};
public FacebookLogin(Context mContext) {
this.mContext=mContext;
facebook=new Facebook(YOUR_APP_ID);
mAsyncRunner = new AsyncFacebookRunner(facebook);
}
public void Login() {
facebook.authorize((Activity) mContext,PERMISSIONS,Facebook.FORCE_DIALOG_AUTH,new LoginDialogListener());
}
public void Logout() throws MalformedURLException, IOException {
facebook.logout(mContext);
}
public boolean isValidUser() {
return facebook.isSessionValid();
}
class LoginDialogListener implements DialogListener {
public void onComplete(Bundle values) {
//Save the access token and access expire for future use in shared preferece
String profile=facebook.request("me")
String uid = profile.getString("id");
mFName= profile.optString("first_name");
new Session(facebook, uid, mFName).save(mContext);
}
public void onFacebookError(FacebookError error) {
displayMessage("Opps..! Check for Internet Connection, Authentication with Facebook failed.");
}
public void onError(DialogError error) {
displayMessage("Opps..! Check for Internet Connection, Authentication with Facebook failed.");
}
public void onCancel() {
displayMessage("Authentication with Facebook failed due to Login cancel.");
}
}
}
On Login complete save the facebook access token and access expire in your shared preference and while using again facebook object later set that access token and access expire to facebook object , it will not give the error which occurs in your code.
you can use following class :
public class Session {
private static Session singleton;
private static Facebook fbLoggingIn;
// The Facebook object
private Facebook fb;
// The user id of the logged in user
private String uid;
// The user name of the logged in user
private String name;
/**
* Constructor
*
* @param fb
* @param uid
* @param name
*/
public Session(Facebook fb, String uid, String name) {
this.fb = fb;
this.uid = uid;
this.name = name;
}
/**
* Returns the Facebook object
*/
public Facebook getFb() {
return fb;
}
/**
* Returns the session user's id
*/
public String getUid() {
return uid;
}
/**
* Returns the session user's name
*/
public String getName() {
return name;
}
/**
* Stores the session data on disk.
*
* @param context
* @return
*/
public boolean save(Context context) {
Editor editor =
context.getSharedPreferences(ConstantsFacebook.KEY, Context.MODE_PRIVATE).edit();
editor.putString(ConstantsFacebook.TOKEN, fb.getAccessToken());
editor.putLong(ConstantsFacebook.EXPIRES, fb.getAccessExpires());
editor.putString(ConstantsFacebook.UID, uid);
editor.putString(ConstantsFacebook.NAME, name);
editor.putString(ConstantsFacebook.APP_ID, fb.getAppId());
editor.putBoolean(ConstantsFacebook.LOGIN_FLAG,true);
if (editor.commit()) {
singleton = this;
return true;
}
return false;
}
/**
* Loads the session data from disk.
*
* @param context
* @return
*/
public static Session restore(Context context) {
if (singleton != null) {
if (singleton.getFb().isSessionValid()) {
return singleton;
} else {
return null;
}
}
SharedPreferences prefs =
context.getSharedPreferences(ConstantsFacebook.KEY, Context.MODE_PRIVATE);
String appId = prefs.getString(ConstantsFacebook.APP_ID, null);
if (appId == null) {
return null;
}
Facebook fb = new Facebook(appId);
fb.setAccessToken(prefs.getString(ConstantsFacebook.TOKEN, null));
fb.setAccessExpires(prefs.getLong(ConstantsFacebook.EXPIRES, 0));
String uid = prefs.getString(ConstantsFacebook.UID, null);
String name = prefs.getString(ConstantsFacebook.NAME, null);
if (!fb.isSessionValid() || uid == null || name == null) {
return null;
}
Session session = new Session(fb, uid, name);
singleton = session;
return session;
}
/**
* Clears the saved session data.
*
* @param context
*/
public static void clearSavedSession(Context context) {
Editor editor =
context.getSharedPreferences(ConstantsFacebook.KEY, Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
singleton = null;
}
/**
* Freezes a Facebook object while it's waiting for an auth callback.
*/
public static void waitForAuthCallback(Facebook fb) {
fbLoggingIn = fb;
}
/**
* Returns a Facebook object that's been waiting for an auth callback.
*/
public static Facebook wakeupForAuthCallback() {
Facebook fb = fbLoggingIn;
fbLoggingIn = null;
return fb;
}
public static String getUserFristName(Context context) {
SharedPreferences prefs =
context.getSharedPreferences(ConstantsFacebook.KEY, Context.MODE_PRIVATE);
String frist_name = prefs.getString(ConstantsFacebook.NAME, null);
return frist_name;
}
public static boolean checkValidSession(Context context) {
SharedPreferences prefs =
context.getSharedPreferences(ConstantsFacebook.KEY, Context.MODE_PRIVATE);
Boolean login=prefs.getBoolean(ConstantsFacebook.LOGIN_FLAG,false);
return login;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Java simple asynchronous HTTPS client I need to develop an application that comunicates with an https server.
This application needs to do some asynchronous data transfert.
I first tried to use an HttpsURLConnection and manage the returned inputStream using a separate thread with an observable object. The observer class than would call the update method that would do some stuff.
The problem with this approach is that i read here: HTTPUrlConnection error (Can't open OutputStream after reading from an inputStream) that HttpUrlConnection can't handle more than a single write/read. That post didn't help me anyway.
I read about Jetty and the Apache HttpClient, but those libraries are 2.8 and 4 megabytes, that is more than 10 times bigger than the application i have to write.
So: I'm looking for a really simple and possibly lightweight java libraries to handle an asynchronous https connection, or a way to use multiple times a connection like the HttpURLConnection (the second solution would be more appreciated as my program doesn't need to do anything more complex and i don't have to import any other libraries).
btw: i'm using the sun httpServer to make the https server if it is useful to know.
If you need me to post some parts of my code to make you better understand what i'm making just ask.
Thanks
A: If the library size truly matters, you could consider using HttpCore. HttpCore is a set of low level HTTP transport components Apache HttpClient is based on. It's footprint is approximately 200-250 KB.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547467",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Twitter4j TwitterStream doesn't get all tweets I am trying to get all the tweets on twitter through the twitter4j TwitterStream object. I'm not sure that I am getting all the tweets. For testing the delay after which the streaming API returns the tweet, I posted a tweet from my account on twitter. But I didn't receive that tweet even after a long time.
Does the twitter4j catch each and every tweet posted on twitter or it loses a good percentage of the tweets? Or am I doing something wrong here?
Here's the code that I am using to get the tweets:
StatusListener listener = new StatusListener(){
int countTweets = 0; // Count to implement batch processing
public void onStatus(Status status) {
countTweets ++;
StatusDto statusDto = new StatusDto(status);
session.saveOrUpdate(statusDto);
// Save 1 round of tweets to the database
if (countTweets == BATCH_SIZE) {
countTweets = 0;
session.flush();
session.clear();
}
}
public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {}
public void onTrackLimitationNotice(int numberOfLimitedStatuses) {}
public void onException(Exception ex) {
ex.printStackTrace();
}
public void onScrubGeo(long arg0, long arg1) {
// TODO Auto-generated method stub
}
};
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setDebugEnabled(true)
.setOAuthConsumerKey(Twitter4jProperties.CONSUMER_KEY)
.setOAuthConsumerSecret(Twitter4jProperties.CONSUMER_SECRET)
.setOAuthAccessToken(Twitter4jProperties.ACCESS_TOKEN)
.setOAuthAccessTokenSecret(Twitter4jProperties.ACCESS_TOKEN_SECRET);
TwitterStream twitterStream = new TwitterStreamFactory(cb.build()).getInstance();
twitterStream.addListener(listener);
session = HibernateUtil.getSessionFactory().getCurrentSession();
transaction = session.beginTransaction();
// sample() method internally creates a thread which manipulates TwitterStream and calls these adequate listener methods continuously.
twitterStream.sample();
A: I'm open to contradiction on this, but I believe it works like this...
Streaming API only gives a sample of tweets for non-partners. It's the "garden hose" as opposed to the "firehose" which a few Twitter partners get. But you can apply for full access.
.sample() gives this "garden hose". Your twitter account won't have access to the firehose, although I think there is a twitterStream for the firehose if you did have access.
Search for "statuses/sample" on this page for the specifics: https://dev.twitter.com/docs/streaming-api/methods
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547470",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Get function name as symbol (not as string) - C preprocessor Is there a way in C to get the function name on which I can use token-pasting
(I know __FUNCTION__ and __func__, but they don't expand to name at pre-processing,
and I do not want the name as a string).
I want to be able to do something like:
prefix_ ## __func_name__ , so that, in a function by name func1(), I can access the
symbol prefix_func1
(maybe I can still use string, and then use dlsym, but want to know if there are
simpler alternatives in GCC, not worrying about portability).
A: You could make the function identifier a macro, as in
#define FUNC1 func1
void FUNC1(void)
{
...
}
and then use FUNC1 for token pasting.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547479",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Route-me on Xcode 4.X doesn't compile for distribution (app store) Route-me on Xcode 4.X doesn't compile for distribution (app store)
This is the error:
ld: library not found for -lMapView
collect2: ld returned 1 exit status
Command /Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/llvm-gcc-4.2 failed with exit code 1
What to do?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547482",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Resultset Shows first 12 Rows empty of jTable - Java I have created a Method in a same class, which take SQL Query as a parameter but there is a problem:
First time when I call
ABC(String sqlQuery)//Method Definition
this Method is working fine for me.And when I implement action performed event on a button with the following code. then there is problem.
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
jScrollPane1.getViewport().remove(jTable1);
ABC(sqlQuery_f2);// Call Mothod and pass parameter
jTable1=new JTable(data,column);
jScrollPane1.getViewport().add(jTable1);
}
When the first time ABC Method is called , the result shows 12 records in jTable and When I call again with the above code on actionperformed, it start record from 13th row to onward and first 12 Row are empty.
When I second time call the Method by Passing Query as a Parameter, It should be start from the first Row and also no row should be there at start even empty rows.
Note: I am using NetBeans and the follwing code is in non-Editable area :
jTable1.setModel(new DefaultTableModel(data, column));
And I have also declare two arrays named data and Column
Resolution ?
A: According to your scenerio, I think when you first call this method(), you probably use a counter to fill the table according to the row count. Next time the counter already has value = 12, then it increments starting from 13.
I think you need to set counter = 0 at the end of this method.
The name counter is assumed to be an int variable, but may be you have some other name.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547486",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: render :partial returning an array when defined in ApplicationController but string when in ApplicationHelper This method:
def admin_buttons
render :partial => 'portable/admin/admin_buttons'
end
returns this (not html_safe) when defined in ApplicationControler and made a helper with helper_method:
["my partial's output "]
But it returns the expected string normally when defined in ApplicationHelper.
I don't understand. This is new behavior as far as I know in rails 3.1
A: Simply put, don't call the controller's render in helpers. It just does not work that way
render in the controller and render in a helper can't be used interchangeably. This isn't new in Rails 3.1.
When you call render in the controller it eventually does call render on the view, the result of which is stored as its response_body. The response body is eventually returned in the way Rack expects, as a string array (what you see as your output).
These links may shed some more light on how this works:
- The controller's definition of render (metal)
- It's superclass method, where response_body is set (abstract_controller)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547492",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Jquery UI slider not working My Jquery slider is not working.
Here is my header code:
<head>
<link href="/stylesheets/public.css?1316972296" media="screen" rel="stylesheet" type="text/css" />
<link href="/stylesheets/tipTip.css?1263394346" media="screen" rel="stylesheet" type="text/css" />
<script src="/javascripts/jquery.js?1316972671" type="text/javascript"></script>
<script src="/javascripts/jquery-ui.js?1316972675" type="text/javascript"></script>
<script src="/javascripts/jquery_ujs.js?1312204886" type="text/javascript"></script>
<script src="/javascripts/application.js?1316972551" type="text/javascript"></script>
<script src="/javascripts/jquery.tablesorter.min.js?1314102048" type="text/javascript"></script>
<script src="/javascripts/jquery.tipTip.minified.js?1269274200" type="text/javascript"></script>
<meta name="csrf-param" content="authenticity_token"/>
<meta name="csrf-token" content="OALn13CELwr3umFrj2BVDeLzw8VhZ2Hmjm/+g2SrGRs="/>
<script type="text/javascript">
$(document).ready(function() {
$("#slider").slider({
value: 100,
min: 0,
max: 1000,
step: 100,
slide: function(event, ui) {
if (ui.value == $(this).slider('option', 'max')) {
$(ui.handle).html('Ubegrænset');
$('#sliderValue').val('99999');
} else {
$(ui.handle).html(ui.value);
$('#sliderValue').val(ui.value);
}
}
}).find('a').html($('#slider').slider('value'));
$('#sliderValue').val($('#slider').slider('value'));
$('.tip').tipTip(defaultPosition: "top");
});
</script>
</head>
And in my page I have:
<div id="slider"></div>
<input id="sliderValue" />
A: The following line is syntactically incorrect:
$('.tip').tipTip(defaultPosition: "top");
You probably mean:
$('.tip').tipTip({ defaultPosition: "top" });
Updated Sample: http://jsfiddle.net/andrewwhitaker/z3xV3/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547499",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: IE6 text selection issues I am running into some weird problems with IE6 when I am trying to select text from the main div at http://mincovlaw.com/doc/canadacopyrightact. In IE6, I can only select the whole DIV at once, not line by line, like in other browsers.
No such problem exists in any IE7, FF3.6, Chrome 16 or Safari.
I did add some user-select: none;'s to a few divs on the page, but the same situation existed even before then.
Is there a simple fix to the problem? I would like to fix this for IE6 users, but not at the cost of revamping the whole layout.
A: My advice? Give up on IE6. Don't support it. IE6 is now less than 5% of the market (2% in some surveys). It's not worth the effort to maintain it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547501",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: iPhone json library to map the json to my own objects I seek a iPhone json library that parse json strings into Custom Objects (such as Employee, Course, etc, not into NSDictionary or NSArray)
Thanks.
A: I don't think one exists. How would you design a general one, without knowing in advance about the kinds of objects that you'll need to parse into? And more critically, JSON is only designed to encode basic data types; it is not intended to be a full object serialization framework (those are usually language specific or have language-specific bindings). However, it should be very easy to write a converter to your custom objects.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547503",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Passing Variable through function to main() I'm very new to C# but am learning more and more every day. Today, I'm trying to build a simple console calculator and need help passing a variable from the function to Main() so I can use it in an if-else to determine what function should execute.
public static void Main(string[] args)
{
int decision = Introduction();
Console.Clear();
Console.WriteLine(decision);
Console.ReadLine();
}
public static int Introduction()
{
int decision = 0;
while (decision < 1 || decision > 7)
{
Console.Clear();
Console.WriteLine("Advanced Math Calculations 1.0");
Console.WriteLine("==========================");
Console.WriteLine("What function would you like to perform?");
Console.WriteLine("Press 1 for Addition ++++");
Console.WriteLine("Press 2 for Subtraction -----");
Console.WriteLine("Press 3 for Multiplication ****");
Console.WriteLine("Press 4 for Division ////");
Console.WriteLine("Press 5 for calculating the Perimeter of a rectangle (x/y)");
Console.WriteLine("Press 6 for calculating the Volume of an object (x/y/z)");
Console.WriteLine("Press 7 for calculating the standard deviation of a set of 10 numbers");
decision = int.Parse(Console.ReadLine());
if (decision < 1 || decision > 7)
{
decision = 0;
Console.WriteLine("Please select a function from the list. Press Enter to reselect.");
Console.ReadLine();
}
else
{
break;
}
}
return decision;
}
When I try to use decision up in Main() it says "The name decision does not exist in the current context".
I'm stumped and tried googling it to no avail.
Cheers
SUCCESS!
A: Return the value from Introduction. The value is local to the method and to use it elsewhere you need to return it and assign to a local variable. Alternatively, you could make decision a static class variable, but that's not a particularly good practice, at least in this case. The Introduction method (not a particularly good name, IMO, it should probably be GetCalculationType() since that is what it is doing) typically shouldn't have any side-effects.
public static void Main( string[] args )
{
int decision = Introduction();
...
}
public static int Introduction()
{
int decision = 0;
...
return decision;
}
A: Main() is the entry point for your app. It then calls your method Introduction() which adds a new stack frame on the stack. Because you declare the decision variable inside your Introduction method, the Main method has no knowledge of it.
If you instead declare your decision variable outside both methods, you should be able to reference it from either:
int decision;
static void Main(string[] args)
{
// code here
}
static void Introduction()
{
// code here
}
A: You can't use the decision variable in main since it is local to the function Introduction.
You could make decision a static class variable but better would be to return the value from Introduction and assign it to a local variable in main.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547505",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: getch equivalent in assembly language I am prigramming in assembly Language, x86 in C++ and I need to know the getch equivalent in assembly language instead of C++ language as I dont want to use any function from the C++ programming language.
I found the code on the web but it saves the given value to a variable and created in C++. I want to use the function only to stop the program until any key is pressed. I dont have to use the entered key value in further programming.
A: This is an OS-specific question. For example if you're using Linux, you can issue a read system call like this:
; Allocate some stack buffer...
sub esp, 256
mov eax, 3 ; 3 = __NR_read from <linux/asm/unistd.h>
mov ebx, 0 ; File descriptor (0 for stdin)
mov ecx, esp ; Buffer
mov edx, 256 ; Length
int 80h ; Execute syscall.
This is actually the more antiquated way to issue a syscall on x86 Linux, but it's the one I know off the top of my head. There's also sysenter which is faster. And there is a shared library mapped into every process that abstracts the syscall interface based on what your hardware supports. (linux-gate.so.)
As a matter of taste, I would argue against the approach of doing system calls from assembly language. It is much simpler to do it from C. Call into the assembly code (or produce inline assembly) for the stuff that absolutely needs to be in assembly language. But in general for most practical matters you will find it better not to waste your time talking to OS interfaces in assembly. (Unless it's a learning exercise, in which case I'm all for it.)
Update: You mentioned as a comment to @Anders K. that you are writing something to put on the MBR. You should have mentioned this earlier in the question. One approach is to use a BIOS call: I believe the one you want is int 16h with ah=0. Another would be to install a keyboard interrupt handler. Here's what the BIOS call would look like:
xor ah, ah ; ah = 0
int 16h ; call BIOS function 16h
; al now contains an ASCII code.
; ah now contians the raw scancode.
A: Looking at your previous questions, I'm assuming this is for your boot loader. In that case, you do not have any OS system calls available, so you'll have to rely on the BIOS. In particular, int 16h can be used to access basic BIOS keyboard services on IBM-compatible PCs.
A: This may not be what you are looking for but why don't you just look at the assembly listing after compiling the c++ code? Most compilers have asm output as an option.
A: There's not really such a thing. `getch' is just a piece of the standard C RTL; it is some C code in the library surrounding one or more system calls, depending on the system you are running on. There is no processor instruction defined to mean 'read a character from wherever some user is typing.' You can learn to call the CRTL routine from assembly, or you can research the corresponding system calls and learn to call them.
A: For a boot loader, you should not be using calls like getch. If you need to process a buffer one character at a time, then write a loop that steps through, one byte at a time. If you absolutely must interact with the console, then write a C++ console program, step through it in the debugger, and see what code is executed by the runtime library. It will likely be an interrupt instruction and may have arguments set up before the interrupt instruction. On a PC the interrupt will call into the BIOS to do the actual console IO.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547506",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: problem with 2 button layout in android I have two buttons (buy and share) in my layout and I want them to occupy equal space. However, "share" button is occupying much more space than "buy" button. Can any one kindly point out my mistake ? Thanks.
<Button
android:id="@+id/shareButton"
android:text="Share"
android:background="@drawable/ebutton"
android:layout_width="wrap_content"
android:layout_height="50px"
android:paddingTop="10dip"
android:paddingBottom="10dip"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:layout_alignParentBottom="true"
>
</Button>
<Button
android:id="@+id/buyButton"
android:layout_toRightOf="@+id/shareButton"
android:text="Buy"
android:background="@drawable/ebutton"
android:layout_width="wrap_content"
android:layout_height="50px"
android:paddingTop="10dip"
android:paddingBottom="10dip"
android:paddingLeft="10dip"
android:paddingRight="10dip"
android:layout_alignParentBottom="true"
>
</Button>
A: Put both buttons in a LinearLayout and define a weightSum of 2 for the LinearLayout, then set the weight of each button to 1 and the two views will be scaled to occupy half of the parent.
<LinearLayout android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:weightSum="2">
<Button android:id="@+id/buyBtn"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:text="Buy"/>
<Button android:id="@+id/shareBtn"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:text="Share"/>
</LinearLayout>
This is a really powerful layout technique as you can define a what fraction of a parent a view should occupy. For example if you wanted 3 buttons with the first occupying half the screen and the other two occupying a quarter you could set the parent weightSum to 4, and the weight of the first to 2 and the weight of the other two buttons to 1.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547508",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do I prevent browser caching with Play? Part of my app provides a file to be downloaded using the redirect() method. I have found that Chrome (and not Firefox or IE, weirdly) is caching this file so that the same version gets downloaded even if it has changed server-side. I gather that there is a way to tell a browser not to cache a file, e.g. like this in the HTML, or by adding something to the HTTP header. I could probably figure those out in a lower-level web framework, but I don't know how to get at the header in Play!, and the HTML option won't work because it's not an HTML file.
It seems like there's always a clever and simple way to do common tasks in Play!, so is there a clever and simple way to prevent caching in a controller?
Thanks!
Edit:
Matt points me to the http.cacheControl setting, which controls caching for the entire site. While this would work, I have no problem with most of the site being cached, especially the CSS etc. If possible I'd like to control caching for one URL at a time (the one pointing to the downloading file in this case). It's not exactly going to be a high-traffic site, so this is just academic interest talking.
Ideally, I'd like to do something like:
public static void downloadFile(String url) {
response.setCaching(false); // This is the method I'm looking for
redirect(url); // Send the response
}
A: I haven't tested it, but it looks like the http.cacheControl configuration setting might work.
http.cacheControl
HTTP Response headers control for static files: sets the default max-age in seconds, telling the user’s browser how long it should cache the page. This is only read in prod mode, in dev mode the cache is disabled. For example, to send no-cache:
http.cacheControl=0
Default: 3600 – set cache expiry to one hour.
A: It is actually this:
response().setHeader("Cache-Control", "no-cache");
A: Tommi's answer is ok, but to make sure it works in every browser, use:
response().setHeader("Cache-Control", "no-cache, max-age=0, must-revalidate, no-store");
A: Play framework response object has a setHeader method. You can add the headers you want like this, for example:
response.setHeader("Cache-Control", "no-cache");
A: response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate, pre-check=0, post-check=0, max-age=0, s-maxage=0"); // HTTP 1.1.
A: On play currently 2.5.x to 2.8.x
you can set cache life of both assets folder or assets file in configuration.
For folder-
play.assets.cache."/public/stylesheets/"="max-age=100"
play.assets.cache."/public/javascripts/"="max-age=200"
for specific file -
play.assets.cache."/public/stylesheets/bootstrap.min.css"="max-age=3600"
--- documentation
https://www.playframework.com/documentation/2.8.x/AssetsOverview
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547509",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: when two 16-bit signed data are multiplied, what should be the size of resultant? I have faced an interview question related to embedded systems and C/C++. The question is:
If we multiply 2 signed (2's complement) 16-bit data, what should be the size of resultant data?
I've started attempting it with an example of multiplying two signed 4-bit, so, if we multiply +7 and -7, we end up with -49, which requires 7 bits. But, I could not formulate a general relation.
I think I need to understand binary multiply deeply to solve this question.
A: First, n bits signed integer contains a value in the range -(2^(n-1))..+(2^(n-1))-1.
For example, for n=4, the range is -(2^3)..(2^3)-1 = -8..+7
The range of the multiplication result is -8*+7 .. -8*-8 = -56..+64.
+64 is more than 2^6-1 - it is 2^6 = 2^(2n-2) ! You'll need 2n-1 bits to store such POSITIVE integer.
Unless you're doing proprietary encoding (see next paragraph) - you'll need 2n bits:
One bit for the sign, and 2n-1 bits for the absolute value of the multiplication result.
If M is the result of the multiplication, you can store -M or M-1 instead. this can save you 1 bit.
A: This will depend on context. In C/C++, all intermediates smaller than int are promoted to int. So if int is larger than 16-bits, then the result will be a signed 32-bit integer.
However, if you assign it back to a 16-bit integer, it will truncate leaving only bottom 16 bits of the two's complement of the new number.
So if your definition of "result" is the intermediate immediately following the multiply, then the answer is the size of int. If you define the size as after you've stored it back to a 16-bit variable, then answer is the size of the 16-bit integer type.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547512",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: linux command line: cut (with empty fields) I have a file (input.txt) with columns of data separated by spaces. I want to get the 9th column of data and onwards.
Normally I would do:
cut -d " " -f 9- input.txt
However, in this file, sometimes the fields are separated by multiple spaces (and the number of spaces varies for each row / column). cut doesn't seem to treat consecutive spaces as one delimiter.
What should I do instead?
A: sed -r 's/ +/ /g' input.txt|cut -d " " -f 9-
A: You could use sed to replace n whitespaces with a single whitespace:
sed -r 's/\ +/\ /g' input.txt | cut -d ' ' -f 9-
Just be sure there aren't any tabs between your columns.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547513",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to securely erase a file in iOS? When I encrypt a file I want to overwrite its contents, not only delete it. My intended purpose for this is to securely erase the file. Is there a way to do this in iOS?
A: Open the file memory mapped and overwrite the data, then delete the file using NSFileManager:
NSFileHandle *file = [NSFileHandle fileHandleForUpdatingAtPath: filename];
[file writeData: data];
[file closeFile];
Where data is an NSData object
A: Check NSFileManager:
- (BOOL)removeItemAtPath:(NSString *)path error:(NSError **)error
For example:
NSFileManager *manager = [NSFileManager defaultManager];
NSString *filePath;
NSError *error;
if ([manager fileExistsAtPath:filePath])
{
[manager fileExistsAtPath:filePath error:&error];
if (error)
{
NSLog(@"Error occured while [removing file]: \"%@\"\n",[error userInfo]);
}
}
For writing in the same file:
NSOutputStream *fileStream = [NSOutputStream outputStreamToFileAtPath:filePath append:NO];
[fileStream open];
[fileStream write:&dataBytes maxLength:dataLength];
[fileStream close];
Where dataBytes is what you want to rewrite with.
A: To overwrite the old data, open the file using [NSFileHandle fileHandleForWritingAtPath:] (write-only access) or fileHandleForUpdatingAtPath: (read-write access). You can then either use the standard write with [myFileHandle fileDescriptor], or use [myFileHandle writeData:] to write a NSData object.
For deleting the overwritten file, use [[NSFileManager defaultManager] removeItemAtPath:].
As for what to write: I suggest you use a pre-generated a file of a convenient size (multiple of 512) and repeatedly overwrite your old file with the content of your "garbage data" file. Using the random number generator on iOS would only make sense for small files as it's too slow. You also don't gain any (serious) additional security by using random data, so you could as well overwrite the old file with a poem.
A: It is NOT necessary to overwrite a file multiple times. This is especially not necessary for Flash memory, as it will use a different block to write the new data anyway. But it's also NOT true for traditional hard drives. It's totally sufficient to oerwrite a file ONCE.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547517",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Turning the same column from 3 rows into 3 columns in another table There are three tables, table a, table b, and table c. Table b combines id's from the other two tables to define a 1-to-(1 to 3) relationship between a and c. So any a will have between 0 and 3 c's.
Performing joins and multiple selects to do validation on objects based on these relationships is too costly. I am trying to get rid of table b altogether, and define the relationships, in order of c.id, in table a.
What is the update query I'm supposed to run? I tried this:
UPDATE a SET c_a = (SELECT c_id from b WHERE a_id = a.id LIMIT 0,1 ORDER BY c_id asc);
UPDATE a SET c_b = (SELECT c_id from b WHERE a_id = a.id LIMIT 1,1 ORDER BY c_id asc);
UPDATE a SET c_c = (SELECT c_id from b WHERE a_id = a.id LIMIT 2,1 ORDER BY c_id asc);
but that failed, because you cannot use LIMIT in a subquery in MySQL.
How do you do this in SQL?
A: This should work if you don't mind the order:
UPDATE a a, b b
SET a.c_a = b.c_id
WHERE a.id = b.a_id
UPDATE a a, b b
SET a.c_b = b.c_id
WHERE a.id = b.a_id
and a.c_a <> b.c_id
UPDATE a a, b b
SET a.c_c = b.c_id
WHERE a.id = b.a_id
and a.c_a <> b.c_id
and a.c_b <> b.c_id
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547521",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: UI_USER_INTERFACE_IDIOM() always returns UIUserInterfaceIdiomPhone on iPad 4.3 Simulator? I am new to iOS development and following along with the book "Learning Cocos2d, A Hands-on Guide to Building iOS Games with Cocos2d, Box2d, and Chipmunk".
I have noticed that the UI buttons and viking characher I have rendered in chapter 2 do not match the book... the apparent cause is that the book instructs you to use the UI_USER_INTERFACE_IDIOM() macro to determine whether you are running an iPad or an iPhone, but it appears that no matter whether I set the scheme in xcode to use iPad 4.3 or iPhone 4.3, the macro always reports that I am running on the phone, not the pad.
Is there some sort of problem with the macro? Is this because I am running only on the simulator? I do not have an actual device on which to test any of this. What am I to do when this macro fails like this?
A: You need to make sure that your project is configured to build a "Universal" app. An iPhone app running on the iPad will still identify its UI idiom as "iPhone".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547524",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: How to test a Facebook application on Google App Engine locally (code 191 error)? I want to test and develop locally, while having the application on the air, and I'd rather not use two separate application id's because this means I have to change the code every time I deploy a new version and then change it back.
I understand that I can change the host file so that localdev.{{my application URL}} would refer to localhost and the URL will be valid, so I won't get the 191 code, but the Google App Engine launcher forces me to use port 8080, and this can't be defined in the host files. If I try to enter localdev.{{my application URL}}:8080 I get the 191 error code again.
Is there any way to use port 80 with the Google App Engine launcher?
Or is there another solution?
UPDATES:
*
*I managed to run locally on port 80 by using the Python file from the Google App Engine directory and not the Google App Engine launcher GUI. However, Facebook doesn't recognize localdev.{{my application URL}} as the URL, and it still gives me the same error code, 191.
*Once I changed the host file into {{my application URL}} without the "localdev." it worked, so this must mean the URLs must match exactly, and not just the domain. Is this true? Anyway, it isn't optimal, because it means I have to change the host file all the time, but it's something you can live with...
A: I have 2 Facebook apps, one with my real URL (for production), and one with http://127.0.0.1/ (for development). Then I have a utility function in my code which checks self.request.host, and selects the appropriate app id and secret.
The reason I use http://127.0.0.1/ and not http://localhost/ or http://localhost:8080/ is that I found only http://127.0.0.1/ would work in Internet Explorer (other browsers seemed fine with those other two URLs, provided they matched the Facebook app).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547525",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android Filter ListView I need a little help with a problem that I have.I'm trying to get a specific part of a list view which I am using in my application.Here is what I have in my list view :
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.plovdiv);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
ListView schedule = (ListView) findViewById(R.id.pld_schedule);
String TIME = "";
ArrayList <HashMap<String, Object>> items = new ArrayList<HashMap<String,Object>>();
HashMap<String, Object> hm; hm = new HashMap<String, Object>();
Calendar c = Calendar.getInstance();
int hours = c.get(Calendar.HOUR);
int minutes = c.get(Calendar.MINUTE);
Log.i("Time","Hours : "+hours+" minutes : "+minutes);
hm = new HashMap<String, Object>();
hm.put(TIME, "06:00");
items.add(hm);
hm = new HashMap<String, Object>();
hm.put(TIME, "06:30");
items.add(hm);
hm = new HashMap<String, Object>();
hm.put(TIME, "07:00");
items.add(hm);
hm = new HashMap<String, Object>();
hm.put(TIME, "07:30");
items.add(hm);
hm = new HashMap<String, Object>();
hm.put(TIME, "08:00");
items.add(hm);
hm = new HashMap<String, Object>();
hm.put(TIME, "09:15");
items.add(hm);
hm = new HashMap<String, Object>();
hm.put(TIME, "10:00");
items.add(hm);
hm = new HashMap<String, Object>();
hm.put(TIME, "10:45");
items.add(hm);
hm = new HashMap<String, Object>();
hm.put(TIME, "11:30");
items.add(hm);
hm = new HashMap<String, Object>();
hm.put(TIME, "12:15");
items.add(hm);
hm = new HashMap<String, Object>();
hm.put(TIME, "13:00");
items.add(hm);
hm = new HashMap<String, Object>();
hm.put(TIME, "13:45");
items.add(hm);
hm = new HashMap<String, Object>();
hm.put(TIME, "14:30");
items.add(hm);
hm = new HashMap<String, Object>();
hm.put(TIME, "15:15");
items.add(hm);
hm = new HashMap<String, Object>();
hm.put(TIME, "16:00");
items.add(hm);
hm = new HashMap<String, Object>();
hm.put(TIME, "16:30");
items.add(hm);
hm = new HashMap<String, Object>();
hm.put(TIME, "17:00");
items.add(hm);
hm = new HashMap<String, Object>();
hm.put(TIME, "17:30");
items.add(hm);
hm = new HashMap<String, Object>();
hm.put(TIME, "18:00");
items.add(hm);
hm = new HashMap<String, Object>();
hm.put(TIME, "18:40");
items.add(hm);
hm = new HashMap<String, Object>();
hm.put(TIME, "19:30");
items.add(hm);
hm = new HashMap<String, Object>();
hm.put(TIME, "20:00");
items.add(hm);
hm = new HashMap<String, Object>();
hm.put(TIME, "20:40");
items.add(hm);
hm = new HashMap<String, Object>();
hm.put(TIME, "21:40");
items.add(hm);
hm = new HashMap<String, Object>();
hm.put(TIME, "22:30");
items.add(hm);
SimpleAdapter adapter = new SimpleAdapter( this, items, R.layout.main_listview,
new String[]{TIME}, new int[]{ R.id.text});
schedule.setAdapter(adapter);
schedule.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
I want to show the items in list view which are bigger as number from the current time.
example It's 10:30 now, so I want to show only the items which are after 10:30 as a value in my list view : 10:45 , 11:30 and etc. I've tried with
String time= hours+" : "+minutes;
adapter.getFilter().filter(time);
,but it's not doing what I want.
So any suggestions how to do that?
A: The filtering process calls the toString method on each object in the list for matching. So your object's toString() should be returning the time string.
What you can do now is wrap your fields in a class and override its toString() where you'll return the time member.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547533",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Virtual dtor segmentation fault I've got the following code in C++:
#include <iostream>
class Number
{
public:
virtual void foo(){std::cout << "Number foo\n";};
Number (){ std::cout << "Number ctor" << std::endl;}
virtual ~Number(){ std::cout << "Number dtor" << std::endl;}
};
class Complex : public Number
{
public:
virtual void foo(){std::cout << "Complex foo\n";};
Complex (double r=0, double i=0) : _r (r), _i (i)
{ std::cout << "Complex ctor" << std::endl; };
virtual ~Complex(){ std::cout << "Complex dtor" << std::endl;}
private:
double _r,_i;
};
int main()
{
Number *numArr = new Complex [2];
delete [] numArr;
return 0;
}
When the destructors are declared as virtual, the application is quitting with segmentation fault. When it is not declared as virtual, than the Number class destructors are invoked (which is obvious...). But, when the destructors are declared as virtual, AND when i'm removing the doubles in the Complex class, there is no segmentation fault and the destructors are called in the expected order (Complex, Number), So i guess the problem is related to the size of the object, can anyone please give me an explanation?
Thanks,
Amit.
A: Number *numArr = new Complex [2];
delete [] numArr;
Actually, the delete operation invokes undefined behaviour.
§5.3.5/3 says,
In the first alternative (delete object), if the static type of the operand is different from its dynamic type, the static type shall be a base class of the operand’s dynamic type and the static type shall have a virtual destructor or the behavior is undefined. In the second alternative (delete array) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.)
What it actually means is this:
Number *object= new Complex();
delete object; //well-defined
//BUT
Number *array = new Complex[N];
delete [] array; //undefined
A: You cannot have polymorphic arrays in C++. Arrays rely on pointer arithmetic and pointer arithmetic relies on the compiler knowing object sizes. Any access to any element of the array beyond the zeroth is undefined in your case.
A: I'm not entirely sure, but this is what I suspect...
I wonder if this is related to the fact that an array of derived classes should not be casted to an array of base classes (they're not the same, see: http://www.parashift.com/c++-faq-lite/proper-inheritance.html#faq-21.3): how would delete know the size of the object it is deleting, to adjust the pointer for numArr[0] and numArr[1] (to find the v-table and pass this to the d-tor)
Apparently, the standard explicitly names this as undefined (5.3.5):
In the second alternative (delete array ) if the dynamic type of the object to be deleted differs from its static type, the behavior is undefined.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547538",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: ASP.NET MVC Apply web.config transformss on "Publish" I'm using VS2010 and I have a Web application that I deploy using the "Publish" command.
I have defined a couple of transformations in the Web.Release.Config file to change the connection string and other settings that need to change in the "live" server.
The problem I'm seeing is that when I execute the "Publish" command it doesn't apply the transformations defined in the web.release.config file.
Any idea on how to achieve this?
Thanks
A: On visual studio, there should be a select box top on the menu. You need to select the type of your build (Release, Debug, etc.).
Something like below :
Be careful that it is set to Release.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547541",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Change axis ticks formatting and add lines to plot I have an x-axis which is categorical. I would like to have the ticks along the axis be boxing the labels, as opposed to centered above them. I would also like to have vertical lines in the plot separating each category along the x-axis.
Here is an example data set:
df <- read.table(tc <- textConnection("
x y
Cat1 2.3
Cat2 2.7
Cat3 1.0
Cat1 0.9
Cat2 9.3
Cat3 3.3"), header = TRUE); close(tc)
Here is the resultant plot:
ggplot(df,aes(x,y))+
geom_point()+
theme_bw(base_size=16)+
opts(panel.grid.major=theme_blank())
And here is roughly what I would like the plot to look like:
Thanks for any help you can provide!
A: Just need to add a few lines to your plotting code
# YOUR CODE
pl0 = ggplot(df,aes(x,y))+
geom_point()+
theme_bw(base_size=16)+
opts(panel.grid.major=theme_blank())
# MY ADDITION
pl1 = pl0 + opts(axis.ticks = theme_blank()) +
geom_vline(xintercept = 1.5) +
geom_vline(xintercept = 2.5)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547542",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: replace output of lines through external command Suppose I have several lines of python code:
for i in range(10):
print "item {}".format(i)
is there a way I can get the output of the lines directly in vim without having to copy the text into the interpreter and copy the output back?
The lines are usually just a part of the file, not the hole file.
A: The real answer (the others were close)
Do a visual selection then
:'<,'>!python -
(quickest way: Vj!python -Enter)
A: You should be able to do :read !python myscript.py and get the output pasted into your current buffer. This vim wikia entry provides more info.
A: Try:
:w !python -
That should execute the entire file by itself, or just a selection if you have something highlighted.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547548",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Display all phone contacts with a check box ![I am developing an application in which I want to display all contacts with a checkbox, as shown in pic I can display all contacts but not with checkbox please help me.][1]
A: If I understood you correctly, you are trying to display user's contacts in the ListView. In this case you have to create an adapter (most probably CursorAdapter) which you then connect to the ListView. For more information check out this tutorial http://developer.android.com/training/contacts-provider/retrieve-names.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547551",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Creating masks across browsers I see that there are ways to do this in webkit browsers, but I don't see ways to do it in others. Is this simply a feature that hasn't been implemented in all the browsers?
I don't have standard images, so clip won't work. I may have to render everything ahead of time, which will make my work exponential, but you deal with what you have, right?
I'd also want to be able to activate this stuff from javascript. :/
Thanks if you can provide support.
A: Just off the top of my head - and without an actual problem from you for us to solve - here's a possible way to accomplish what you want...
HTML
<div class="myImage">
<img src="path_to_image" title="Lorem ipsum" alt="Dolar sit amet" />
<div class="myMask">
</div><!-- /myMask -->
</div><!-- /myImage -->
CSS
.myImage {
position: relative;
}
.myMask {
position:absolute;
top: 0;
left: 0;
background-color: transparent;
background-image: url('path_to_masking_image');
}
Alternatively, use an <img /> inside the myMask div, and remove the background-image property from the CSS.
The way it's currently laid out, you would need two images: the image itself in all its glory, and the mask.
The way you would accomplish the 'masking effect' is to have the mask image be a static solid color that matches background of the container its in - ie white, black, whatever.
Kapeesh? This would work in all browsers, which is what you asked for. The background-clip property has -webkit and -moz selectors, but is not supported in browsers like IE or (to my knowledge) Opera.
A: Here are my 2 cents, if it is indeed CSS Sprites you are after.
<head>
<style type="text/css"><!--
#imagemask {
background-image: url(image.png);
background-repeat: no-repeat;
background-color: transparent;
height: 40px;
width: 40px;
}
.mask1 { background-position: top left; }
.mask2 { background-position: 0 40px; }
.mask3 { background-position: 0 80px; }/* And so on, however your image file is 'layed out' */
--></style>
<script type="text/javascript">
function mask1(){ document.getElementById("imagemask").setAttribute("class", "mask1"); }
function mask2(){ document.getElementById("imagemask").setAttribute("class", "mask1"); }
function mask3(){ document.getElementById("imagemask").setAttribute("class", "mask1"); }
</script>
</head>
<body>
<a href="#" onclick="javascript:mask1()">mask 1</a>
<a href="#" onclick="javascript:mask2()">mask 2</a>
<a href="#" onclick="javascript:mask3()">mask 3</a>
<div id="imagemask" class="mask1"></div>
</body>
*
*We define the div#imagemask to contain 1 image file as a background and set it to not repeat around, as that would sort of defy the point.
*We define how to "move around" the image inside the "mask" (div) with fixed width and height.
*As a reference, I've then added the javascript you need to switch between the masks on the fly. I wrote that in about 10 seconds, you could probably write something a little more elegant if you want.
*Add the links with onclick= events
*Finally, add the div#imagemask to the body.
Given that I don't know the width or height of your image file or it's target masking, you'll have to do some substantial edits to this code. But you get the idea :)
A: I'm just going to skip the CSS variant in favor of this:
Example of a working mask: http://gumonshoe.net/NewCard/MaskTest.html
I acquired a javascript class from another website tutorial:
http://gumonshoe.net/js/canvasMask.js
It reads the image data and applies the alpha pixels from the mask to the target image:
function applyCanvasMask(image, mask, width, height, asBase64) {
// check we have Canvas, and return the unmasked image if not
if (!document.createElement('canvas').getContext) return image;
var bufferCanvas = document.createElement('canvas'),
buffer = bufferCanvas.getContext('2d'),
outputCanvas = document.createElement('canvas'),
output = outputCanvas.getContext('2d'),
contents = null,
imageData = null,
alphaData = null;
// set sizes to ensure all pixels are drawn to Canvas
bufferCanvas.width = width;
bufferCanvas.height = height * 2;
outputCanvas.width = width;
outputCanvas.height = height;
// draw the base image
buffer.drawImage(image, 0, 0);
// draw the mask directly below
buffer.drawImage(mask, 0, height);
// grab the pixel data for base image
contents = buffer.getImageData(0, 0, width, height);
// store pixel data array seperately so we can manipulate
imageData = contents.data;
// store mask data
alphaData = buffer.getImageData(0, height, width, height).data;
// loop through alpha mask and apply alpha values to base image
for (var i = 3, len = imageData.length; i < len; i = i + 4) {
imageData[i] = alphaData[i];
}
// return the pixel data with alpha values applied
if (asBase64) {
output.clearRect(0, 0, width, height);
output.putImageData(contents, 0, 0);
return outputCanvas.toDataURL();
}
else {
return contents;
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547552",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: jquery form validation - error class to parent container I am using Jörn's jQuery validation - which you can view the full code for by downloading it here.
I'm running into a bit of a problem, as I'm not entirely familiar with Javascript.
Here's an example of my HTML
<div class="field">
<label for="myInput">My Input</label>
<input id="myInput" name="myInput" type="text" />
<span class="helptext">
This is some help text for My Input...
</span>
</div>
Essentially, the above HTML is repeated for each "section" of the form. .helptext is hidden via CSS, unless the parent div has a class of .error.
For example:
<div class="field error">
Here is what I believe to be the relevant code for the validation plugin - How would I make the error class be added to the parent div.field?
defaults: {
messages: {},
groups: {},
rules: {},
errorClass: "error",
validClass: "valid",
errorElement: "span.helptext",
focusInvalid: true,
errorContainer: $( ["div.field"] ),
errorLabelContainer: $( [] ),
onsubmit: true,
ignore: [],
ignoreTitle: false,
...
A: You can use the highlight/unhighlight handlers to add/remove classes, like this:
highlight: function(element, errorClass, validClass) {
$(element).parent('.field').addClass(errorClass).removeClass(validClass);
},
unhighlight: function(element, errorClass, validClass) {
$(element).parent('.field').removeClass(errorClass).addClass(validClass);
}
Hope this helps, d.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547556",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: numpy uint8 pixel wrapping solution For an image processing class, I am doing point operations on monochrome images. Pixels are uint8 [0,255].
numpy uint8 will wrap. For example, 235+30 = 9. I need the pixels to saturate (max=255) or truncate (min=0) instead of wrapping.
My solution uses int32 pixels for the point math then converts to uint8 to save the image.
Is this the best way? Or is there a faster way?
#!/usr/bin/python
import sys
import numpy as np
import Image
def to_uint8( data ) :
# maximum pixel
latch = np.zeros_like( data )
latch[:] = 255
# minimum pixel
zeros = np.zeros_like( data )
# unrolled to illustrate steps
d = np.maximum( zeros, data )
d = np.minimum( latch, d )
# cast to uint8
return np.asarray( d, dtype="uint8" )
infilename=sys.argv[1]
img = Image.open(infilename)
data32 = np.asarray( img, dtype="int32")
data32 += 30
data_u8 = to_uint8( data32 )
outimg = Image.fromarray( data_u8, "L" )
outimg.save( "out.png" )
Input image:
Output image:
A: You can use OpenCV add or subtract functions (additional explanation here).
>>> import numpy as np
>>> import cv2
>>> arr = np.array([100, 250, 255], dtype=np.uint8)
>>> arr
Out[1]: array([100, 250, 255], dtype=uint8)
>>> cv2.add(arr, 10, arr) # Inplace
Out[2]: array([110, 255, 255], dtype=uint8) # Saturated!
>>> cv2.subtract(arr, 150, arr)
Out[3]: array([ 0, 105, 105], dtype=uint8) # Truncated!
Unfortunately it's impossible to use indexes for output array, so inplace calculations for each image channel may be performed in this, less efficient, way:
arr[..., channel] = cv2.add(arr[..., channel], 40)
A: Use numpy.clip:
import numpy as np
np.clip(data32, 0, 255, out=data32)
data_u8 = data32.astype('uint8')
Note that you can also brighten images without numpy this way:
import ImageEnhance
enhancer = ImageEnhance.Brightness(img)
outimg = enhancer.enhance(1.2)
outimg.save('out.png')
A: Basically, it comes down to checking before you add. For instance, you could define a function like this:
def clip_add(arr, amt):
if amt > 0:
cutoff = 255 - amt
arr[arr > cutoff] = 255
arr[arr <= cutoff] += amt
else:
cutoff = -amt
arr[arr < cutoff] = 0
arr[arr >= cutoff] += amt
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547557",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "36"
} |
Q: Loading .obj file in OpenGL in Visual Studio 2010 In which directory should I store the .obj models in Visual Studio 2010?
I am using the OpenGL Mathematics (GLM) library to use them in OpenGL, and when I try to load the object it shows
Error11error LNK2019: unresolved external symbol _glmReadOBJ referenced in function _SDL_main
A: Your question seems to have no relation to your actual problem. You're not getting this error when you "try to load the object"; this is a linker error. You get this when you try to compile and link your code. It has nothing to do with where the ".obj" files are stored, because you haven't created a functioning executable yet.
The linker error is telling you that you probably did not link to the GL Mesh library correctly.
A: I know this is resolved already but, for future reference if you look at the readme.txt that comes with GLM the "GLM Usage" section has the following:
GLM is a header only library, there is nothing to build, just include it.
#include <glm/glm.hpp>
So if you are using VStudio you'll just need to add the directory containing the GLM headers as a "Additional Include Directory" (Right Click the Project, Select Properties, Select "General" under "C/C++", should be top entry.) Good deal.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547561",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: codeigniter set_rules allow more characters I am building a registration system and i have come to a problem.
I want to allow dots(.) into my username but i cant find a way to do this...
This is just an example which i may want to use in order features of my app as well.
This is what i got so far:
$this->load->library('form_validation');
$this->form_validation->set_rules('username', 'Username', 'trim|required|alpha_numeric|min_length[6]|xss_clean');
Thanks
A: You'll have to create your own custom function in your controller:
class Form extends CI_Controller
{
function index()
{
$this->load->library('form_validation');
// 'callback_valid_username' will call your controller method `valid_username`
$this->form_validation->set_rules('username', 'Username', 'trim|required|callback_valid_username|min_length[6]|xss_clean');
if ($this->form_validation->run() == FALSE)
{
// Validation failed
}
else
{
// Validation passed
}
}
function valid_username($str)
{
if ( ! preg_match('/^[a-zA-Z0-9.]*$/', $str) )
{
// Set the error message:
$this->form_validation->set_message('valid_username', 'The %s field should contain only letters, numbers or periods');
return FALSE;
}
else
{
return TRUE;
}
}
}
For more information on custom validation function, read the docs:
http://codeigniter.com/user_guide/libraries/form_validation.html#callbacks
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547565",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to start Azure Storage Emulator from within a program I have some unit tests that use Azure Storage. When running these locally, I want them to use the Azure Storage emulator which is part of the Azure SDK v1.5. If the emulator isn't running, I want it to be started.
To start the emulator from the command line, I can use this:
"C:\Program Files\Windows Azure SDK\v1.5\bin\csrun" /devstore
This works fine.
When I try to start it using this C# code, it crashes:
using System.IO;
using System.Diagnostics;
...
ProcessStartInfo processToStart = new ProcessStartInfo()
{
FileName = Path.Combine(SDKDirectory, "csrun"),
Arguments = "/devstore"
};
Process.Start(processToStart);
I've tried fiddling with a number of ProcessStartInfo settings, but nothing seems to work. Is anybody else having this problem?
I've checked the Application Event Log and found the following two entries:
Event ID: 1023
.NET Runtime version 2.0.50727.5446 - Fatal Execution Engine Error (000007FEF46B40D2) (80131506)
Event ID: 1000
Faulting application name: DSService.exe, version: 6.0.6002.18312, time stamp: 0x4e5d8cf3
Faulting module name: mscorwks.dll, version: 2.0.50727.5446, time stamp: 0x4d8cdb54
Exception code: 0xc0000005
Fault offset: 0x00000000001de8d4
Faulting process id: 0x%9
Faulting application start time: 0x%10
Faulting application path: %11
Faulting module path: %12
Report Id: %13
A: This program worked fine for me. Give it a try, and if it works for you too, work backwards from there. (What about your app is different from this?)
using System.Diagnostics;
public class Program
{
public static void Main() {
Process.Start(@"c:\program files\windows azure sdk\v1.5\bin\csrun", "/devstore").WaitForExit();
}
}
A: Updated 7/12/2022:
If you are running Visual Studio 2022, azurite.exe is the replacement for the now-deprecated AzureStorageEmulator.exe which can be found here:
C:\Program Files\Microsoft Visual Studio\2022\Community\Common7\IDE\Extensions\Microsoft\Azure Storage Emulator\azurite.exe
NB: if you are running Professional (or another) Edition, you'll need to replace Community with Professional (or the appropriate edition name) in the path.
Updated 1/19/2015:
After doing more testing (i.e., running several builds), I've discovered that WAStorageEmulator.exe's status API is actually broken in a couple of significant ways (which may or may not have impact on how you use it).
The status reports False even when an existing process is running if the user differs between the existing running process and the user used to launch the status process. This incorrect status report will lead to a failure to launch the process that looks like this:
C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator>WAStorageEmulator.exe status
Windows Azure Storage Emulator 3.4.0.0 command line tool
IsRunning: False
BlobEndpoint: http://127.0.0.1:10000/
QueueEndpoint: http://127.0.0.1:10001/
TableEndpoint: http://127.0.0.1:10002/
C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator>WAStorageEmulator.exe start
Windows Azure Storage Emulator 3.4.0.0 command line tool
Error: Port conflict with existing application.
Additionally, the status command appears only to report the endpoints specified in WAStorageEmulator.exe.config, not those of the existing running process. I.e., if you start the emulator, then make a change to the config file, and then call status, it will report the endpoints listed in the config.
Given all of these caveats, it may, in fact, simply be better to use the original implementation as it appears to be more reliable.
I will leave both so others can choose whichever solution works for them.
Updated 1/18/2015:
I have fully rewritten this code to properly leverage WAStorageEmulator.exe's status API per @RobertKoritnik's request.
public static class AzureStorageEmulatorManager
{
public static bool IsProcessRunning()
{
bool status;
using (Process process = Process.Start(StorageEmulatorProcessFactory.Create(ProcessCommand.Status)))
{
if (process == null)
{
throw new InvalidOperationException("Unable to start process.");
}
status = GetStatus(process);
process.WaitForExit();
}
return status;
}
public static void StartStorageEmulator()
{
if (!IsProcessRunning())
{
ExecuteProcess(ProcessCommand.Start);
}
}
public static void StopStorageEmulator()
{
if (IsProcessRunning())
{
ExecuteProcess(ProcessCommand.Stop);
}
}
private static void ExecuteProcess(ProcessCommand command)
{
string error;
using (Process process = Process.Start(StorageEmulatorProcessFactory.Create(command)))
{
if (process == null)
{
throw new InvalidOperationException("Unable to start process.");
}
error = GetError(process);
process.WaitForExit();
}
if (!String.IsNullOrEmpty(error))
{
throw new InvalidOperationException(error);
}
}
private static class StorageEmulatorProcessFactory
{
public static ProcessStartInfo Create(ProcessCommand command)
{
return new ProcessStartInfo
{
FileName = @"C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\WAStorageEmulator.exe",
Arguments = command.ToString().ToLower(),
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
}
}
private enum ProcessCommand
{
Start,
Stop,
Status
}
private static bool GetStatus(Process process)
{
string output = process.StandardOutput.ReadToEnd();
string isRunningLine = output.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries).SingleOrDefault(line => line.StartsWith("IsRunning"));
if (isRunningLine == null)
{
return false;
}
return Boolean.Parse(isRunningLine.Split(':').Select(part => part.Trim()).Last());
}
private static string GetError(Process process)
{
string output = process.StandardError.ReadToEnd();
return output.Split(':').Select(part => part.Trim()).Last();
}
}
And the corresponding tests:
[TestFixture]
public class When_starting_process
{
[Test]
public void Should_return_started_status()
{
if (AzureStorageEmulatorManager.IsProcessRunning())
{
AzureStorageEmulatorManager.StopStorageEmulator();
Assert.That(AzureStorageEmulatorManager.IsProcessRunning(), Is.False);
}
AzureStorageEmulatorManager.StartStorageEmulator();
Assert.That(AzureStorageEmulatorManager.IsProcessRunning(), Is.True);
}
}
[TestFixture]
public class When_stopping_process
{
[Test]
public void Should_return_stopped_status()
{
if (!AzureStorageEmulatorManager.IsProcessRunning())
{
AzureStorageEmulatorManager.StartStorageEmulator();
Assert.That(AzureStorageEmulatorManager.IsProcessRunning(), Is.True);
}
AzureStorageEmulatorManager.StopStorageEmulator();
Assert.That(AzureStorageEmulatorManager.IsProcessRunning(), Is.False);
}
}
Original post:
I took Doug Clutter's and Smarx's code one step further and created a utility class:
The code below has been updated to work on both Windows 7 and 8 and now points at the new storage emulator path as of SDK 2.4.**
public static class AzureStorageEmulatorManager
{
private const string _windowsAzureStorageEmulatorPath = @"C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\WAStorageEmulator.exe";
private const string _win7ProcessName = "WAStorageEmulator";
private const string _win8ProcessName = "WASTOR~1";
private static readonly ProcessStartInfo startStorageEmulator = new ProcessStartInfo
{
FileName = _windowsAzureStorageEmulatorPath,
Arguments = "start",
};
private static readonly ProcessStartInfo stopStorageEmulator = new ProcessStartInfo
{
FileName = _windowsAzureStorageEmulatorPath,
Arguments = "stop",
};
private static Process GetProcess()
{
return Process.GetProcessesByName(_win7ProcessName).FirstOrDefault() ?? Process.GetProcessesByName(_win8ProcessName).FirstOrDefault();
}
public static bool IsProcessStarted()
{
return GetProcess() != null;
}
public static void StartStorageEmulator()
{
if (!IsProcessStarted())
{
using (Process process = Process.Start(startStorageEmulator))
{
process.WaitForExit();
}
}
}
public static void StopStorageEmulator()
{
using (Process process = Process.Start(stopStorageEmulator))
{
process.WaitForExit();
}
}
}
A: The file name in v4.6 is "AzureStorageEmulator.exe". The full path is: "C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\AzureStorageEmulator.exe"
A: For Windows Azure Storage Emulator v5.2, the following helper class can be used to start the emulator:
using System.Diagnostics;
public static class StorageEmulatorHelper {
/* Usage:
* ======
AzureStorageEmulator.exe init : Initialize the emulator database and configuration.
AzureStorageEmulator.exe start : Start the emulator.
AzureStorageEmulator.exe stop : Stop the emulator.
AzureStorageEmulator.exe status : Get current emulator status.
AzureStorageEmulator.exe clear : Delete all data in the emulator.
AzureStorageEmulator.exe help [command] : Show general or command-specific help.
*/
public enum StorageEmulatorCommand {
Init,
Start,
Stop,
Status,
Clear
}
public static int StartStorageEmulator() {
return ExecuteStorageEmulatorCommand(StorageEmulatorCommand.Start);
}
public static int StopStorageEmulator() {
return ExecuteStorageEmulatorCommand(StorageEmulatorCommand.Stop);
}
public static int ExecuteStorageEmulatorCommand(StorageEmulatorCommand command) {
var start = new ProcessStartInfo {
Arguments = command.ToString(),
FileName = @"C:\Program Files (x86)\Microsoft SDKs\Azure\Storage Emulator\AzureStorageEmulator.exe"
};
var exitCode = executeProcess(start);
return exitCode;
}
private static int executeProcess(ProcessStartInfo startInfo) {
int exitCode = -1;
try {
using (var proc = new Process {StartInfo = startInfo}) {
proc.Start();
proc.WaitForExit();
exitCode = proc.ExitCode;
}
}
catch {
//
}
return exitCode;
}
}
[Thanks to huha for the boilerplate code to execute a shell command.]
A: FYI - The 1.6 default location is C:\Program Files\Windows Azure Emulator\emulator as stated on the MSDN docs.
A: We are running into the same issue. We have the concept of a "smoke test" which runs between groups of tests, and which ensure the environment is in a good state before the next group starts. We have a .cmd file that kicks off the smoke tests, and it works just fine starting the devfabric emulator, but the devstore emulator only runs as long as the .cmd process runs.
Apparently the implementation of the DSServiceSQL.exe is different than DFService.exe. DFService seems to run like a windows service - kick it off, and it keeps running. DSServiceSQL dies as soon as the process that started it dies.
A: maybe caused by file not found?
try this
FileName = Path.Combine(SDKDirectory, "csrun.exe")
A: I uninstalled all of the Windows Azure bits:
*
*WA SDK v1.5.20830.1814
*WA Tools for Visual Studio: v1.5.40909.1602
*WA AppFabric: v1.5.37
*WA AppFabric: v2.0.224
Then, I downloaded and installed everything using the unified installer. Everything came back except the AppFabric v2. All the version numbers are the same. Reran my tests and still having a problem.
And then...(this is weird)...it would work every now and then. Rebooted the machine and now it works. Have shutdown and rebooted a number of times now...and it just works. (sigh)
Thanks to everyone who provided feedback and/or ideas!
The final code is:
static void StartAzureStorageEmulator()
{
ProcessStartInfo processStartInfo = new ProcessStartInfo()
{
FileName = Path.Combine(SDKDirectory, "csrun.exe"),
Arguments = "/devstore",
};
using (Process process = Process.Start(processStartInfo))
{
process.WaitForExit();
}
}
A: Here we go: Pass the string "start" to the method ExecuteWAStorageEmulator().
The NUnit.Framework is used for the Assert only.
using System.Diagnostics;
using NUnit.Framework;
private static void ExecuteWAStorageEmulator(string argument)
{
var start = new ProcessStartInfo
{
Arguments = argument,
FileName = @"c:\Program Files (x86)\Microsoft SDKs\Windows Azure\Storage Emulator\WAStorageEmulator.exe"
};
var exitCode = ExecuteProcess(start);
Assert.AreEqual(exitCode, 0, "Error {0} executing {1} {2}", exitCode, start.FileName, start.Arguments);
}
private static int ExecuteProcess(ProcessStartInfo start)
{
int exitCode;
using (var proc = new Process { StartInfo = start })
{
proc.Start();
proc.WaitForExit();
exitCode = proc.ExitCode;
}
return exitCode;
}
See also my new self-answered question
A: There's now a neat little NuGet package to assist with starting/stopping the Azure Storage Emulator programmatically: RimDev.Automation.StorageEmulator.
The source code is available in this GitHub repository, but you can essentially do things like this:
if(!AzureStorageEmulatorAutomation.IsEmulatorRunning())
{
AzureStorageEmulatorAutomation emulator = new AzureStorageEmulatorAutomation();
emulator.Start();
// Even clear some things
emulator.ClearBlobs();
emulator.ClearTables();
emulator.ClearQueues();
emulator.Stop();
}
It feels like the cleanest option to me.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547567",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
} |
Q: GWT DisclourePanel I have got a DisclourePanel with a button on it. But when I call button.getParent()
I always get a SimplePanel. With other Panel like VerticalPanel it works.
Does Anyone know why?
A: DisclosurePanel extends type Composite meaning it is a widget that can be composed of many widgets. It consists of a header and a SimplePanel both stacked in a VerticalPanel. Any content you give it, is placed in this SimplePanel, in your case a button, thus SimplePanel is returned by getParent()
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547574",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Exception while using java youtube api I am using java youtube api , I have this exception when i am just trying to do the first line of the connection
YouTubeService service = new YouTubeService("");
I am getting this
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: Servlet execution threw an exception
root cause
java.lang.NoClassDefFoundError: com/google/gdata/client/media/MediaService
java.lang.ClassLoader.defineClass1(Native Method)
java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
java.lang.ClassLoader.defineClass(ClassLoader.java:615)
java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2820)
org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1150)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1523)
tst.Main.doGet(Main.java:197)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
tst.Main.service(Main.java:98)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
root cause
java.lang.ClassNotFoundException: com.google.gdata.client.media.MediaService
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1678)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1523)
java.lang.ClassLoader.defineClass1(Native Method)
java.lang.ClassLoader.defineClassCond(ClassLoader.java:631)
java.lang.ClassLoader.defineClass(ClassLoader.java:615)
java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
org.apache.catalina.loader.WebappClassLoader.findClassInternal(WebappClassLoader.java:2820)
org.apache.catalina.loader.WebappClassLoader.findClass(WebappClassLoader.java:1150)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1645)
org.apache.catalina.loader.WebappClassLoader.loadClass(WebappClassLoader.java:1523)
tst.Main.doGet(Main.java:197)
javax.servlet.http.HttpServlet.service(HttpServlet.java:621)
tst.Main.service(Main.java:98)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
note The full stack trace of the root cause is available in the Apache Tomcat/7.0.21 logs.
I put the gdata-youtube .... etc in WEB-INF/lib
also I tried to put the same in the java build path and its the same
so whats the problem ?
A: you are missing dependent libraries. Add the core and media libraries as well -
gdata-client-X.X.jar
gdata-youtube-X.X.jar
gdata-core-X.X.jar
gdata-media-X.X.jar
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547580",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Save array positions I have tree where user can drag and drop element and change elements positions.
After every change I'm sending this serialize array and I want to save it .
Example tree :
Economics
Blogging
General Dev
Japan
Productivity
Humanities
Education
Science
Haskell
Earth
PHP
I'm sending serialize tree throught ajax so I have array linke this.
'0' => "1"
'1' => "2"
'2' => "3"
'3' => "4"
'4' ...
'0' => "5"
'1' ...
'0' ...
'0' => "6"
'1' ...
'0' => "7"
'1' ...
'0' => "8"
'1' ...
'0' ...
'0' => "9"
'1' ...
'0' => "10"
'1' ...
'0' => "11"
Array value is table row id.
how insert this array into database with correct position ?
A: I would suggest using traditional tree storing approach:
create table catalogue (
id int not null auto_increment primary key,
name varchar(255),
catalogue_id int,
ord int
);
So first of you need to fill up db properly, then rest should be easy to handle.
actual code.
Client side:
<ul id="enclosure_0" class="sortable">
<li id="item_1">Level0 - Item 1</li>
<li id="item_2">Level0 - Item 2</li>
<li id="item_3">Level0 - Item 3</li>
<li id="item_4">Level0 - Item 4</li>
<li id="item_5">Level0 - Item 5
<ul id="enclosure_5" class="sortable">
<li id="item_6">Level1 - Item 1</li>
<li id="item_7">Level1 - Item 2</li>
<li id="item_8">Level1 - Item 3</li>
<li id="item_9">Level1 - Item 4</li>
</ul>
</li>
</ul>
<script>
$(document).ready(function(){
$(".sortable").sortable({
stop: function(ev, ui){
var list = $(this).sortable("toArray");
$.get("sort.php", {items: list, parent_id: $(this).attr('id')}, function(data){window.alert("stored");});
}
});
});
</script>
Server side (sort.php):
<?php
/* you have new order in $_GET["items"], you have parent id in $_GET["parent_id"] */
/* easiest way:
* */
preg_match("/enclosure_([0-9])+/", $_GET["parent_id"], $tmp);
$parent_id = (int) $tmp[1];
$counter = 0;
foreach ($_GET["items"] as $item){
$counter++;
preg_match("/item_([0-9]+)/", $item, $tmp);
$item_id = (int) $tmp[1];
$db->query("update catalogue set ord = $counter where id = $item_id");
/* alternatively, somewhat safer */
$db->query("update catalogue set ord = $counter where id = $item_id and catalogue_id = $parent_id");
}
Notes and assumptions:
1) catalogue_id should be 0 for top level categories
2) I believe you are smart enough to get the client side dynamically rendered.
3) Assumes ord is 1 based.
4) php not tested, but should be ok
A: I would not try to keep the rows in the DB table in the right order, I would add a "position" column to the table. I assume you already have a "parent" column to persist the hierarchy.
When the user rearranges item, just update the position columns.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547581",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Regular expression for string of digits with no repeated digits? I'm reading through the dragon book and trying to solve an exercise that is stated as follows
Write regular definitions for the following languages:
*
*All strings of digits with no repeated digits. Hint: Try this problem first with a few digits, such as { 0, 1, 2 }.
Despite having tried to solve it for hours, I can't imagine a solution, beside the extremely wordy
d0 -> 0?
d1 -> 1?
d2 -> 2?
d3 -> 3?
d4 -> 4?
d5 -> 5?
d6 -> 6?
d7 -> 7?
d8 -> 8?
d9 -> 9?
d10 -> d0d1d2d3d4d5d6d7d8d9 | d0d1d2d3d4d5d6d7d9d8 | ...
Hence having to write 10! alternatives in d10. Since we shall write this regular definition, I doubt that this is a proper solution. Can you help me please?
A: Here's one possible construction:
*
*A regex for a string that contains at the most a single '0' digit looks like (1-9)* (0|epsilon) (1-9)* - so any number of 1-9 digits, followed by zero or 1 '0's followed by any number of 1-9 digits.
*We can now move forward by noticing that if there's only a single '1' digit it will be either to the left or to the right of the '0' digit (or the epsilon representing the missing zero digit). So we can construct a regular expression having these two cases or'ed (|) together.
*We can now drill further down saying that if there's only a single '2' digit it can be to the right or the left of the 1 digit in it's two possible relative locations to the '0' digit.
*So we're building a binary tree and the number of ORed regex is on the order of 2^10 which is the same order of the FSM accepting this language. An FSM for accepting the language should have (2^10 + 1) states with each state n can be seen as it's binary representation n0n1n2n3n4n5n6n7n8n9 meaning n0 = seen digit '0', n1 = seen digit '1'. and a repeat digit transitioning to the single non-accepting state. The initial state being zero.
If you're allowed to complement then a regex that has more than a single '0' digit would be (0-9)* 0 (0-9)* 0 (0-9)*, repeat for all digits, complement.
You can definitely be a lot more compact for Peter Taylors interpretation of no two consecutive digits that are the same. Clearly the state for that problem is much smaller.
SUCCINCTNESS OF THE COMPLEMENT AND INTERSECTION OF
REGULAR EXPRESSIONS
"A study in [2] reveals that most of the one-unambiguous regular
expression used in practice take a very simple form: every alphabet
symbol occurs at most once. We refer to those as single-occurrence
regular expressions (SOREs) and show a tight exponential lower bound
for intersection."
...
"In this section, we show that in defining the complement of a single
regular expression, a double-exponential size increase cannot be
avoided in general. In contrast, when the expression is
one-unambiguous its complement can be computed in polynomial time."
A: Instead of trying to write a definition that only defines what you want, what if you tell it to generate a list of all strings up digits up to 10 digits in length, including duplicates, and then subtract the ones that contain two zeros, two ones... etc.? Would that work?
A: So the question didn't necessarily ask you to write a regular expression, it asked you to provide a regular definition, which I interpret to include NFA's. It turns out it doesn't matter which you use, as all NFA's can be shown to be mathematically equivalent to regular expressions.
Using the digits 0, 1, and 2, a valid NFA would be the following (sorry for the crummy diagram):
Each state represents the last digit scanned in the input, and there are no loops on any of the nodes, therefore this is an accurate representation of a string with no repeated digits from the set {0,1,2}. Extending this is trivial (although it requires a large whiteboard :) ).
NOTE: I am making the assumption that the string "0102" IS valid, but the string "0012" is not.
This can be converted to a regular expression (although it will be painful) by using the algorithm described here.
A: (I don't know which variant of regular expressions you are referring to, if any, thus I will provide hints for the most general form of regular expressions.)
I find it a rather odd application of regular expressions since this is exactly one of the cases where they don't really provide a big benefit over other (more trivial to understand) solutions.
However, if you absolutely want to use regex, here's a hint (no solution since it's an exercise, let me know if you need more hints):
Regex allows you to recognize regular languages, which are generally accepted by deterministic finite state machines. Try to find a state machine which accepts exactly the words in the specified pattern. It'll require 2^10 = 1024 states but not 10! = 3628800.
A: A regular definition is a sequence of definitions on the form
d1 -> r1
d2 -> r2
...
dn -> rn
Now make the following definitions:
Zero -> 0
One -> Zero (1 Zero)* | (Zero 1)+ | 1 (Zero 1)* | (1 Zero)+
Two -> One (2 One)* | (One 2)+ | 2 (One 2)* | (2 One)+
Three -> Two (3 Two)* | (Two 3)+ | 3 (Two 3)* | (3 Two)+
Four -> Three (4 Three)* | (Three 4)+ | 4 (Three 4)* | (4 Three)+
...
Nine -> Eight (9 Eight)* | (Eight 9)+ | 9 (Eight 9)* | (9 Eight)+
A: Not sure what you mean by "Regular Expression" in your question title. But if the regex engine supports negative lookahead, this is easily accomplished. (Here's a PHP snippet)
$re = '/# Match string of digits having no repeated digits.
^ # Anchor to start of string.
(?![^0]*0[^0]*0) # Assert 0 does not occur twice.
(?![^1]*1[^1]*1) # Assert 1 does not occur twice.
(?![^2]*2[^2]*2) # Assert 2 does not occur twice.
(?![^3]*3[^3]*3) # Assert 3 does not occur twice.
(?![^4]*4[^4]*4) # Assert 4 does not occur twice.
(?![^5]*5[^5]*5) # Assert 5 does not occur twice.
(?![^6]*6[^6]*6) # Assert 6 does not occur twice.
(?![^7]*7[^7]*7) # Assert 7 does not occur twice.
(?![^8]*8[^8]*8) # Assert 8 does not occur twice.
(?![^9]*9[^9]*9) # Assert 9 does not occur twice.
[0-9]+ # Match string of only digits.
$ # Anchor to end of string.
/x';
A: I don't think there is a neat way to write a regular expression to solve this problem without listing all the possibilities. But I find a way to reduce the complexity from O(N!) to O(2^N) by defining the DFA in the following way. In the DFA I'm going to construct, a state represent whether any digit has appeared or not.
Take strings consisting of {0, 1, 2} for example, 0 represent '0' has appeared once, 0' represent '0' hasn't appeared. All the states will look like this {012, 0'1'2', 0'12, 01'2, 012',012', 01'2, 0'12}. There will be 2^3=8 states at all. And the DFA looks like as follows:
DFA for strings with no repeating digits
You can easily extend it to {0,1,2,...,9}. But there will be 1024 states at all. However, I think it's the most compact DFA with an intuitive proof. For the reason that each state has unique meaning and can't be merged further.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547583",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "19"
} |
Q: Dictionary style replace multiple items I have a large data.frame of character data that I want to convert based on what is commonly called a dictionary in other languages.
Currently I am going about it like so:
foo <- data.frame(snp1 = c("AA", "AG", "AA", "AA"), snp2 = c("AA", "AT", "AG", "AA"), snp3 = c(NA, "GG", "GG", "GC"), stringsAsFactors=FALSE)
foo <- replace(foo, foo == "AA", "0101")
foo <- replace(foo, foo == "AC", "0102")
foo <- replace(foo, foo == "AG", "0103")
This works fine, but it is obviously not pretty and seems silly to repeat the replace statement each time I want to replace one item in the data.frame.
Is there a better way to do this since I have a dictionary of approximately 25 key/value pairs?
A: Note this answer started as an attempt to solve the much simpler problem posted in How to replace all values in data frame with a vector of values?. Unfortunately, this question was closed as duplicate of the actual question. So, I'll try to suggest a solution based on replacing factor levels for both cases, here.
In case there is only a vector (or one data frame column)
whose values need to be replaced and there are no objections to use factor we can coerce the vector to factor and change the factor levels as required:
x <- c(1, 1, 4, 4, 5, 5, 1, 1, 2)
x <- factor(x)
x
#[1] 1 1 4 4 5 5 1 1 2
#Levels: 1 2 4 5
replacement_vec <- c("A", "T", "C", "G")
levels(x) <- replacement_vec
x
#[1] A A C C G G A A T
#Levels: A T C G
Using the forcatspackage this can be done in a one-liner:
x <- c(1, 1, 4, 4, 5, 5, 1, 1, 2)
forcats::lvls_revalue(factor(x), replacement_vec)
#[1] A A C C G G A A T
#Levels: A T C G
In case all values of multiple columns of a data frame need to be replaced, the approach can be extended.
foo <- data.frame(snp1 = c("AA", "AG", "AA", "AA"),
snp2 = c("AA", "AT", "AG", "AA"),
snp3 = c(NA, "GG", "GG", "GC"),
stringsAsFactors=FALSE)
level_vec <- c("AA", "AC", "AG", "AT", "GC", "GG")
replacement_vec <- c("0101", "0102", "0103", "0104", "0302", "0303")
foo[] <- lapply(foo, function(x) forcats::lvls_revalue(factor(x, levels = level_vec),
replacement_vec))
foo
# snp1 snp2 snp3
#1 0101 0101 <NA>
#2 0103 0104 0303
#3 0101 0103 0303
#4 0101 0101 0302
Note that level_vec and replacement_vec must have equal lengths.
More importantly, level_vec should be complete , i.e., include all possible values in the affected columns of the original data frame. (Use unique(sort(unlist(foo))) to verify). Otherwise, any missing values will be coerced to <NA>. Note that this is also a requirement for Martin Morgans's answer.
So, if there are only a few different values to be replaced you will be probably better off with one of the other answers, e.g., Ramnath's.
A: We can also use dplyr::case_when
library(dplyr)
foo %>%
mutate_all(~case_when(. == "AA" ~ "0101",
. == "AC" ~ "0102",
. == "AG" ~ "0103",
TRUE ~ .))
# snp1 snp2 snp3
#1 0101 0101 <NA>
#2 0103 AT GG
#3 0101 0103 GG
#4 0101 0101 GC
It checks the condition and replaces with the corresponding value if the condition is TRUE. We can add more conditions if needed and with TRUE ~ . we keep the values as it is if none of the condition is matched. If we want to change them to NA instead we can remove the last line.
foo %>%
mutate_all(~case_when(. == "AA" ~ "0101",
. == "AC" ~ "0102",
. == "AG" ~ "0103"))
# snp1 snp2 snp3
#1 0101 0101 <NA>
#2 0103 <NA> <NA>
#3 0101 0103 <NA>
#4 0101 0101 <NA>
This will change the values to NA if none of the above condition is satisfied.
Another option using only base R is to create a lookup dataframe with old and new values, unlist the dataframe, match them with old values, get the corresponding new values and replace.
lookup <- data.frame(old_val = c("AA", "AC", "AG"),
new_val = c("0101", "0102", "0103"))
foo[] <- lookup$new_val[match(unlist(foo), lookup$old_val)]
A: Here's something simple that will do the job:
key <- c('AA','AC','AG')
val <- c('0101','0102','0103')
lapply(1:3,FUN = function(i){foo[foo == key[i]] <<- val[i]})
foo
snp1 snp2 snp3
1 0101 0101 <NA>
2 0103 AT GG
3 0101 0103 GG
4 0101 0101 GC
lapply will output a list in this case that we don't actually care about. You could assign the result to something if you like and then just discard it. I'm iterating over the indices here, but you could just as easily place the key/vals in a list themselves and iterate over them directly. Note the use of global assignment with <<-.
I tinkered with a way to do this with mapply but my first attempt didn't work, so I switched. I suspect a solution with mapply is possible, though.
A: Using dplyr::recode:
library(dplyr)
mutate_all(foo, funs(recode(., "AA" = "0101", "AC" = "0102", "AG" = "0103",
.default = NA_character_)))
# snp1 snp2 snp3
# 1 0101 0101 <NA>
# 2 0103 <NA> <NA>
# 3 0101 0103 <NA>
# 4 0101 0101 <NA>
A: map = setNames(c("0101", "0102", "0103"), c("AA", "AC", "AG"))
foo[] <- map[unlist(foo)]
assuming that map covers all the cases in foo. This would feel less like a 'hack' and be more efficient in both space and time if foo were a matrix (of character()), then
matrix(map[foo], nrow=nrow(foo), dimnames=dimnames(foo))
Both matrix and data frame variants run afoul of R's 2^31-1 limit on vector size when there are millions of SNPs and thousands of samples.
A: If you're open to using packages, plyr is a very popular one and has this handy mapvalues() function that will do just what you're looking for:
foo <- mapvalues(foo, from=c("AA", "AC", "AG"), to=c("0101", "0102", "0103"))
Note that it works for data types of all kinds, not just strings.
A: Here is a quick solution
dict = list(AA = '0101', AC = '0102', AG = '0103')
foo2 = foo
for (i in 1:3){foo2 <- replace(foo2, foo2 == names(dict[i]), dict[i])}
A: One of the most readable way to replace value in a string or a vector of string with a dictionary is str_replace_all, from the stringr package. The 'pattern' argument of str_replace_all can be a dictionnary, expressed as a list: stringr::str_replace_all(string = dataset$string, pattern = c("regex" = "desired value")). This way, no need to specify the 'replacement' argument.
Beware: this method is based on regex, which is very useful and flexible (see here) but requires attention to what you are doing and to the results obtained (see point #2 in the code below).
# 1. Example of dictionnary ↓
dictio_replace= c("AA" = "0101",
"AC" = "0102",
"AG" = "0103")
#2 ↓ (OPTIONAL) Add begin & end of string anchors ("^" & "$" in regex)
names(dictio_replace) = paste0("^", names(dictio_replace), "$")
# 3. ↓ Replace all pattern, according to the dictionary-values
foo$snp1 <- stringr::str_replace_all(string = foo$snp1,
pattern= dictio_replace)
# ↑ We only use the 'pattern' option here: 'replacement' is useless since we provide a dictionnary.
Repeat step #3 with foo$snp2 & foo$snp3. If you have more vectors to transform it's a good idea to use another func' like a for loop or apply family, in order to replace values in each of the columns/vector in the dataframe without repeating yourself.
Note that without specifying the beginning and the end of the string with ^ & $ in the regex-dictionnary, "AAAA" will be replaced by "01010101", since "AAAA" contains "AA" twice. With the ^ & $ anchors surrounding "AA", "AAAA" will not be replaced at all.
A: Used @Ramnath's answer above, but made it read (what to be replaced and what to be replaced with) from a file and use gsub rather than replace.
hrw <- read.csv("hgWords.txt", header=T, stringsAsFactor=FALSE, encoding="UTF-8", sep="\t")
for (i in nrow(hrw))
{
document <- gsub(hrw$from[i], hrw$to[i], document, ignore.case=TRUE)
}
hgword.txt contains the following tab separated
"from" "to"
"AA" "0101"
"AC" "0102"
"AG" "0103"
A: Since it's been a few years since the last answer, and a new question came up tonight on this topic and a moderator closed it, I'll add it here. The poster has a large data frame containing 0, 1, and 2, and wants to change them to AA, AB, and BB respectively.
Use plyr:
> df <- data.frame(matrix(sample(c(NA, c("0","1","2")), 100, replace = TRUE), 10))
> df
X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
1 1 2 <NA> 2 1 2 0 2 0 2
2 0 2 1 1 2 1 1 0 0 1
3 1 0 2 2 1 0 <NA> 0 1 <NA>
4 1 2 <NA> 2 2 2 1 1 0 1
... to 10th row
> df[] <- lapply(df, as.character)
Create a function over the data frame using revalue to replace multiple terms:
> library(plyr)
> apply(df, 2, function(x) {x <- revalue(x, c("0"="AA","1"="AB","2"="BB")); x})
X1 X2 X3 X4 X5 X6 X7 X8 X9 X10
[1,] "AB" "BB" NA "BB" "AB" "BB" "AA" "BB" "AA" "BB"
[2,] "AA" "BB" "AB" "AB" "BB" "AB" "AB" "AA" "AA" "AB"
[3,] "AB" "AA" "BB" "BB" "AB" "AA" NA "AA" "AB" NA
[4,] "AB" "BB" NA "BB" "BB" "BB" "AB" "AB" "AA" "AB"
... and so on
A: Not overly original, but should provide an intuitive interface to accomplish replacing multiple values in Base R:
# Function performing a mapping replacement:
# replaceMultipleValues => function()
replaceMultipleValues <- function(df, mapFrom, mapTo){
# Extract the values in the data.frame:
# dfVals => named character vector
dfVals <- unlist(df)
# Get all values in the mapping & data
# and assign a name to them: tmp1 => named character vector
tmp1 <- c(
setNames(mapTo, mapFrom),
setNames(dfVals, dfVals)
)
# Extract the unique values:
# valueMap => named character vector
valueMap <- tmp1[!(duplicated(names(tmp1)))]
# Recode the values in data.frame: res => data.frame
res <- data.frame(
matrix(
valueMap[dfVals],
nrow = nrow(df),
ncol = ncol(df),
dimnames = dimnames(df)
)
)
# Explicitly define the returned object: data.frame => env
return(res)
}
# Recode values in data.frame:
# res => data.frame
res <- replaceMultipleValues(
foo,
c("AA", "AC", "AG"),
c("0101", "0102", "0103")
)
# Print data.frame to console:
# data.frame => stdout(console)
res
Data:
# Import data: foo => data.frame
foo <- data.frame(snp1 = c("AA", "AG", "AA", "AA"), snp2 = c("AA", "AT", "AG", "AA"), snp3 = c(NA, "GG", "GG", "GC"), stringsAsFactors=FALSE)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547597",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "58"
} |
Q: http post successfully logged in? I am trying to login to a webside which needs 3 parameters in the post command.
Token, usr_name and usr_password.
The token always has the following value "545616f1e29bc538843ec7aa908122b1e".
I am getting this value by doing a HttpGet on the loginpage and store it as a string.
If i do a login through the url as follows https://www.xxxxx.com/xxxx/restricted/form/formelement=0123?usr_name=myuser&usr_password=mypass&token=545616f1e29bc538843ec7aa908122b1e the login succeeds.
How do i get a.m link build together and know afterwards that i successfully logged in?
Thanks for any tips and helping me out.
My code:
try {
String webPage = "https://xxxxxxxx.com/xx/Authenticationserv";
String name = username; // user input through editbox
String password1 = password; // user input through editbox
String authString = name + ":" + password1 + ":" + token + "=" + value;
System.out.println("auth string: " + authString);
byte[] authEncBytes = Base64.encodeBytesToBytes(authString.getBytes());
String authStringEnc = new String(authEncBytes);
System.out.println("Base64 encoded auth string: " + authStringEnc);
URL url = new URL(webPage);
URLConnection urlConnection = url.openConnection();
urlConnection.setRequestProperty("Authorization", "Basic " + authStringEnc);
InputStream is = urlConnection.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
int numCharsRead;
char[] charArray = new char[1024];
StringBuffer sb1 = new StringBuffer();
while ((numCharsRead = isr.read(charArray)) > 0) {
sb1.append(charArray, 0, numCharsRead);
}
String result = sb1.toString();
System.out.println("/// BEGIN ///");
System.out.println(result);
System.out.println("/// END ///");
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
A: Actually I think you need to use POST method to log in in your website.I had the same problem a few weeks ago and I've did this :
HttpClient httpclient;
HttpPost httppost;
ArrayList<NameValuePair> postParameters;
httpclient = new DefaultHttpClient();
httppost = new HttpPost("your login link");
postParameters = new ArrayList<NameValuePair>();
postParameters.add(new BasicNameValuePair("username_hash", "fcd86e8cc9fc7596f102de7b2b922e80c6e6fac9"));
postParameters.add(new BasicNameValuePair("password_hash", "b66936348bd0bd44fa44f5ca7dcceb909545e47f"));
httppost.setEntity(new UrlEncodedFormEntity(postParameters));
HttpResponse response = httpclient.execute(httppost);
Log.w("Response ","Status line : "+ response.toString());
So you are setting up your post params with an ArrayList and you can get the responce from the server if you logged in via HttpResponse.And another thing : I'm setting up the username and password in the code,because it is just to how you the idea.If you have any questions feel free to ask.
Hope it helps!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547599",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Multiple EAGLViews but only one copy of each texture - how? I have an app running on iPad which is using lots of textures, rendering into one EAGLView. Now I need a second EAGLView, sharing textures with the first.
I can get both views rendering fine, in parallel, on screen, by fixing some design mistakes in Apple's code (e.g. the default ViewController needs some tweaks to support multiple child EAGLView objects). But I can't get the textures to be shared.
I cannot duplicate the textures (that would double memory usage - and we're using most of the mem already).
I can't find any documentation from Apple on how to share textures between multiple EAGLView's - there are "hints" that this is what EAGLShareGroup is for, allowing each GLView to have its own context, but the two contexts to share a ShareGroup - but nothing explicit that I could find.
I've tried following the answer to this question: Textures not drawing if multiple EAGLViews are used
...but it wasn't really an answer. It pointed to EAGLSharegroup without actually explaining how to use it - it seems to make no difference at all. It also pointed indirectly to a page about rendering from multiple threads - which is a completely different problem, and I don't have any of the problems listed there (app crashes etc).
A: It turns out that Apple's undocumented EAGLShareGroup ( http://developer.apple.com/library/ios/#documentation/OpenGLES/Reference/EAGLSharegroup_ClassRef/Reference/EAGLSharegroup.html ) ... cannot be instantiated without knowing its secret init method(s).
I have no idea what that is - it's undocumented - but you can get an EAGLContext to instantiate the first sharegroup for you, and then make that your shared, global sharegroup.
So, the following will never work:
EAGLShareGroup *group = [[EAGLShareGropu alloc] init];
EAGLContext *context1 = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2 sharegroup:group];
EAGLContext *context2 = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2 sharegroup:group];
HOWEVER, the following works perfectly:
EAGLContext *context1 = [[EAGLContext alloc] initWithAPI:kEAGLRenderingAPIOpenGLES2];
EAGLContext *context2 = [[EAGLContext alloc] initWithAPI:[context1 API] sharegroup:context1.sharegroup];
(edited to make context2 use context1's API too - as per Apple's ES programming guide, as per Pivot's comment)
A: There are two options, create the second context using the same sharegroup as the first Use Adam's second code example for that.
Alternatively, you can use the same context for both views. To do this, you should probably have the context be owned by the ViewController. Then, when you want to use the context to render to a particular view, you call glBindFramebuffer() on that view's framebuffer object, and call -presentRenderbuffer on the view-specific colorbuffer. This case is probably slightly more efficient than using two shared contexts.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547603",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Speeding up SQL to Linq ToList I have a SQL table with about 380,000 rows.
In SQL SMSS I perform this query:
SELECT Longitude, Latitude, street FROM [Stops].[dbo].[Members]
WHERE ABS(Latitude - 51.463419) < 0.005 AND ABS(Longitude - 0.099) < 0.005
It returns about 20 results almost instantly.
I have a WCF webserice to expose my Data to my Windows phone application:
public class Service1 : IService1
{
double curLatitude = 51.463;
double curLongitude = 0.099;
public List<Member> GetMembers()
{
DataClassesDataContext db = new DataClassesDataContext();
var members = from member in db.Members
where (Convert.ToDouble(member.Latitude) - curLatitude) < 0.005 && (Convert.ToDouble(member.Longitude) - curLongitude) < 0.005
select member;
return members.ToList();
}
}
I beleive it is doing the same query, but also adding the items to a List.
The problem is, is that it takes 7+ minutes then I get some strange exception so never completes. The WCF service tester in VS2010 just fills up with memory and uses lots of CPU when permforming this.
My feeling is that the ToList is doing something odd?
A: You are missing the abs-part in your LINQ version.
Some side notes.
You can track the SQL query in at least two possible ways.
*
*Use SQL profiler and check the query there (then you can paste the query in SQL Management Studio and compare the output to your query above).
*Insert db.Log = Console.Out; (or another TextWriter) and check the output window in Visual Studio.
You should dispose your DataClassesDataContext, the best way is to put it in a using block:
public List<Member> GetMembers()
{
using(DataClassesDataContext db = new DataClassesDataContext())
{
var members = from member in db.Members
where (Convert.ToDouble(member.Latitude) - curLatitude) < 0.005
&& (Convert.ToDouble(member.Longitude) - curLongitude) < 0.005
select member;
return members.ToList();
}
}
A: There are a number of issues here:
*
*(edit: ignore this point; I misread the 380,000 as being the data being fetched) that is a very large volume of data to query and bring over the network; how long, for example, does it take in Query Analyzer? It will take at least that long anywhere
*when loading that into LINQ-to-SQL you have materialisation overheads, and the identity-manager overhead; the latter can be solved by disabling object tracking on the data-context; the former is trickier - if you suspect this is significant (it can be, sometimes) maybe something like "dapper" can load this instead (it has a far more efficient materialiser, and does not include an identity manager)
*WCF has to serialize this data, which can take quite a lot of CPU and memory - it then needs to come over the network (which takes bandwidth). If you are free to change the format, other serializers might save both CPU and bandwidth here.
So; the first thing to do is identify where the time is going.
*
*I would start by running it from Query Analyser; maybe an index is missing?
*set ObjectTrackingEnabled to false
*after that, separate the data-access from WCF to see which is the culprit - time just the data-to-a-list step
*after that, time DataContractSerializer serialising this data and measure the size of the data when serialized (personally, I'd then compare to protobuf-net - but that might not be an option, depending on your scenario)
*an then measure the time on the network
Any or all of those might need optimising here.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547604",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Problems with pagination in JQuery I need to be able to parse an XML file with JQuery, show 3 posts at the time and have pagination that links to the rest of the posts.
Below in the code, I am parsing a local XML file that I have downloaded from slashdot. The code displays the right amount of posts and creates the links to paginate but when you click the pagination links, they do not work for some reason. I am still a JQuery n00b so I have problems figuring out what is wrong. Seems like JQuery does not have a really good debugging tool?
p.s. You can download http://slashdot.org/slashdot.xml to your local so you can test the code if you want.
here is the code
<html>
<head>
<script type="text/javascript" src="jquery-1.6.4.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "slashdot.xml",
dataType: "xml",
success: parseXml
});
});
function parseXml(xml)
{
//find every story
var count = 0;
$(xml).find("story").each(function()
{
count++;
var title = $(this).find('title').text()
var url = $(this).find('url').text()
var fullLink = '<li><a href="'+url+'">' + title + '</a></li>';
//document.write('<a href="'+url+'">' + title + '</a><br/>');
$("#content").append(fullLink);
});
var show_per_page = 3;
var number_of_items = count;
var number_of_pages = Math.ceil(number_of_items/show_per_page);
$('#current_page').val(0);
$('#show_per_page').val(show_per_page);
var navigation_html = '<a class="previous_link" href="javascript:previous();">Prev</a> ';
var current_link = 0;
while(number_of_pages > current_link){
navigation_html += '<a class="page_link" href="javascript:go_to_page(' + current_link +')" longdesc="' + current_link +'">'+ (current_link + 1) +'</a>';
current_link++;
}
navigation_html += '<a class="next_link" href="javascript:next();"> Next</a>';
$('#page_navigation').html(navigation_html);
$('#page_navigation .page_link:first').addClass('active_page');
$('#content').children().css('display', 'none');
$('#content').children().slice(0, show_per_page).css('display', 'block');
function previous(){
new_page = parseInt($('#current_page').val()) - 1;
//if there is an item before the current active link run the function
if($('.active_page').prev('.page_link').length==true){
go_to_page(new_page);
}
}
function next(){
new_page = parseInt($('#current_page').val()) + 1;
//if there is an item after the current active link run the function
if($('.active_page').next('.page_link').length==true){
go_to_page(new_page);
}
}
function go_to_page(page_num){
//get the number of items shown per page
var show_per_page = parseInt($('#show_per_page').val());
//get the element number where to start the slice from
start_from = page_num * show_per_page;
//get the element number where to end the slice
end_on = start_from + show_per_page;
//hide all children elements of content div, get specific items and show them
$('#content').children().css('display', 'none').slice(start_from, end_on).css('display', 'block');
/*get the page link that has longdesc attribute of the current page and add active_page class to it
and remove that class from previously active page link*/
$('.page_link[longdesc=' + page_num +']').addClass('active_page').siblings('.active_page').removeClass('active_page');
//update the current page input field
$('#current_page').val(page_num);
}
//$("#content").append('count:' + count);
}
</script>
</head>
<body>
<!-- we will add our HTML content here -->
<input type="hidden" id="current_page"></input>
<input type="hidden" id="show_per_page"></input>
<div id="content">
</div>
<div id="page_navigation"></div>
</body>
</html>
A: First, your html is invalid. Input tags are self-closing and li items need to be inside of a list ul or ol not a div element.
<input type="hidden" id="current_page" />
<input type="hidden" id="show_per_page" />
<ul id="content"></ul>
Second, your click events aren't getting handled because go_to_page, next and previous are not in the global scope. You should create those elements and attach click handlers.
$("<a href='#'>Prev</a>").click(previous).appendTo("#page_navigation");
while (number_of_pages > current_link) {
$("<a href='#' class='page_link'>").text(++current_link).click(go_to_page).appendTo("#page_navigation")
}
$("<a href='#'>Next</a>").click(next).appendTo("#page_navigation");
Another tip, restructure the prev and next functions to just click on the previous or next page number. That way, this in go_to_page always points to the paging link.
function previous(e) {
e.preventDefault(); //Don't follow the link
$(".active_page").prev(".page_link").click();
}
function next(e) {
e.preventDefault();
$(".active_page").next(".page_link").click();
}
function go_to_page(e) {
e.preventDefault();
//Get the zero-based index instead of using an attribute
var page_num = $(this).index(".page_link");
//get the number of items shown per page
var show_per_page = parseInt($('#show_per_page').val());
//get the element number where to start the slice from
start_from = page_num * show_per_page;
//get the element number where to end the slice
end_on = start_from + show_per_page;
//hide all children elements of content div, get specific items and show them
$('#content').children().hide().slice(start_from, end_on).show();
//Since this always points to the page link, use that instead of looking for it
$(this).addClass("active_page").siblings(".active_page").removeClass("active_page");
//update the current page input field. Don't need this anymore since we can use the .active_page class to identify it.
//$('#current_page').val(page_num);
}
JSFiddle with the AJAX part removed.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547605",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Safely insert string into HTML using JavaScript The insertion looks like this:
a_span.innerHTML() = input.value
To prevent any kind of attacks in PHP I use htmlspecialchars. Should I use this
for protection or native escape is enough?
A: First off, I'm assuming you intended to write a_span.innerHTML = input.value, since innerHTML isn't a function.
Secondly, you should use document.createTextNode() instead of innerHTML if you're worried about your text being interpreted as HTML entities. Something like a_span.innerHTML="";a_span.appendChild(document.createTextNode(input.value)); should work okay.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547606",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: App Crashes when trying to add cells to tableView I am using an NSMutableArray to populate my tableView.The array's name is cells. I have a button that adds cells, but when i press the button, the app crashes. The code in my button is:
- (IBAction)outlet1:(id)sender {
[cart.cells addObject:@"1"];
[cart.myTableView reloadData];
}
this button is on a seperate page from the table view, so cart is referring to the tableView page. Any help would be appreciated! Thanks
A: The exception message means that someone is trying to call a method named outlet1 that has no argument (note the missing colon) while your method's signature is outlet1:. You have probably missed the colon of the selector when adding the target/action to your button.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547617",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Adding an id to the tag is not working I'm trying to add an id attribute to the <circle> tag using jQuery's .attr():
r.circle(x, y, 6).attr({fill: "#ff0000", stroke: "none", id: "cir1"}),
The problem is that it adds the fill and stroke attributes but not id. I know because I look at the Google Chrome DEV and it's not showing the id!
A: According to the documentation, you can't add an id using attr. See here:
http://raphaeljs.com/reference.html#attr
If you need the id as a hook, perhaps you could set a title, which is allowed.
An aside:
It's hard to tell from the docs if this is allowed, but maybe you can add the id as a custom attr by placing it in quotes?
"id" : "cir1"
A: Apparently, you can't set the id thru attr.
Just get the node reference and set it directly.
r.circle(...).node.id = 'cir1';
A: This works fine for me.
Proof: open this test page and open your developer console. You will see "yay 1 circle" in the output, which is the result of this JavaScript code:
var head = $('circle:eq(1)');
head.attr({id:'yay'});
console.log(
head[0].id,
$('#yay').length,
document.getElementById('yay').tagName
);
From this you can see that the id attribute is both a) being set on the DOM element, and b) working as a means for accessing the element through either jQuery or DOM methods.
Can you provide a working test case, perhaps using Raphael, showing this failing?
A: In some instances you do not need an ID.
You can use the keyword this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547618",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Help with MySql trigger or alternative I am trying to bring together two separate designs here so I understand the overall approach may not be ideal. Basically through user input in PHP table1 and part of table2 is populated and then in turn I need the rest of table2 and table3 to be populated automatically.
I have the following db
with this trigger
DELIMITER |
CREATE TRIGGER new_trigger AFTER INSERT on table2
FOR EACH ROW BEGIN
INSERT INTO table3(att1, DateCreated, DateUpdated)
VALUES('PG', now(), now());
UPDATE table2 SET table3Id = table3.LAST_INSERT_ID();
END;
|
DELIMITER ;
although MySQL accepts the trigger as written without any errors I get this error when the app runs:
General error: 1442 Can't update table 'table2' in stored function/trigger
because it is already used by statement which invoked this stored function/trigger
I believe this comes from MySQL triggers can't manipulate the table they are assigned to. So if this is the reason for the error how else can I achieve the same results?
EDIT: (ANSWER)
Thanks to the help from mootinator here and in chat. Here is his solution that works as I need it to.
CREATE TRIGGER new_trigger BEFORE INSERT on table2
FOR EACH ROW BEGIN
INSERT INTO table3(att1, DateCreated, DateUpdated)
VALUES('PG', now(), now());
SET NEW.table3Id = LAST_INSERT_ID();
END;
A: You can't use an AFTER trigger because the new change you make would (potentially) cause the AFTER trigger to be run again in an infinite loop. You have to use a BEFORE trigger to edit the row before it gets written.
Try eg:
CREATE TRIGGER new_trigger BEFORE INSERT on table2
FOR EACH ROW BEGIN
INSERT INTO table3(att1, DateCreated, DateUpdated)
VALUES('PG', now(), now());
SET NEW.table3Id = LAST_INSERT_ID();
END;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547620",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Event anonymous function parameters not working correctly PictureBox[,] picBoard = new PictureBox[3, 3];
for(int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
{
picBoard[i, j] = new PictureBox();
picBoard[i, j].Click += new EventHandler(
(sender, e) => Debug.WriteLine(i.ToString() + " " + j.ToString()));
}
I am trying to make picBoard[i, j] print the position it has in the 2D array when clicked. The problem is that each PictureBox prints "3 3" when clicked. This doesn't make any sense to me, since i and j are never equal to 3. I tried replacing i with 500 in Debug.Writeline(), and it performs as expected ( always prints "500 3" ).
A: They are captured by the anonymous method and once you leave the loop their value is 3. And when the callback is actually executed, well, their value is 3. To fix your code you need local variables to close over:
PictureBox[,] picBoard = new PictureBox[3, 3];
for(int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
{
var x = i;
var y = j;
picBoard[i, j] = new PictureBox();
picBoard[i, j].Click += new EventHandler(
(sender, e) => Debug.WriteLine(x.ToString() + " " + y.ToString()));
}
A: You are closing over the loop variables, their value is only evaluated when the lambda executes at which point the loop has completed, that's why you see all 3's - make a local copy instead:
for(int i = 0; i < 3; i++)
for (int j = 0; j < 3; j++)
{
int localI = i;
int localJ = j;
picBoard[i, j] = new PictureBox();
picBoard[i, j].Click += new EventHandler(
(sender, e) => Debug.WriteLine(localI.ToString() + " " + localJ.ToString()));
}
As a reference read "Closing over the loop variable considered harmful" for why this happens.
A: I love this problem!
That's because the event handler is a closure and it's capturing the value of i and j. That means that when the loop finishes, both i and j have a value of 3. So when you click, it shows 3,3.
To avoid this, you need to make a local copy of the variable with something like this (I don't know a lot about .net syntax)
var newI = i
var newJ = j
(sender, e) => {
Debug.WriteLine(newI.ToString() + " " + newJ.ToString()));
}
This will make a copy of i an j with the correct values.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547621",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to register a controller with parameterized constructor, programatically? (in Castle Windsor - ASP.NET MVC) I want to register controllers programatically in Global.asax.cs.
with MvcContrib.Castle.WindsorControllerFactory
private static IWindsorContainer _Container;
protected virtual void InitializeWindsor()
{
try
{
if (_Container == null)
{
_Container = new WindsorContainer();
ControllerBuilder.Current.SetControllerFactory(new MvcContrib.Castle.WindsorControllerFactory(_Container));
RegisterActiveRecord();
RegisterRepositories();
RegisterServices();
RegisterControllers();
RegisterComponents();
}
I have done it by
private void RegisterControllers()
{
try
{
_Container.Register(
AllTypes.Of<IController>()
.FromAssembly(typeof(HomeController).Assembly)
.Configure(c => c.LifeStyle.Transient)
);
It works fine for all controllers with default constructors.
But, I have a controller (LoginController) with parameterzied construtor.
public class LoginController : Controller
{
private IUser _User;
public LoginController(IUser objUser)
{
_User = objUser;
}
When I tried to view it in browser (http://localhost:2011/Login), it gives me following error.
**No parameterless constructor defined for this object**
Stack Trace:
[MissingMethodException: No parameterless constructor defined for this object.]
System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck) +0
System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache) +98
System.RuntimeType.CreateInstanceDefaultCtor(Boolean publicOnly, Boolean skipVisibilityChecks, Boolean skipCheckThis, Boolean fillCache) +241
System.Activator.CreateInstance(Type type, Boolean nonPublic) +69
System.Activator.CreateInstance(Type type) +6
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +491
[InvalidOperationException: An error occurred when trying to create a controller of type 'NAATEELib.Controllers.LoginController'. Make sure that the controller has a parameterless public constructor.]
System.Web.Mvc.DefaultControllerFactory.GetControllerInstance(RequestContext requestContext, Type controllerType) +628
System.Web.Mvc.DefaultControllerFactory.CreateController(RequestContext requestContext, String controllerName) +204
Please guide me. I do not want to modify .config (xml) files.
thanks.
A: It seems you forgot to use a Windsor controller factory (the stack trace shows DefaultControllerFactory).
Take a look at this Windsor - ASP.NET MVC tutorial, in particular part 2.
EDIT: OP edited the question, code is already using MvcContrib's Windsor controller factory. Either the registrations are wrong (recommend using MvcContrib's RegisterControllers) or the controller factory isn't correctly installed.
A: Below changes, I have done to get rid of this problem.
I have:
*
*Migrated to System.Web.Mvc 3
*Used MVCContrib.Extras.3.0.51.0
*Written WindsorControllerFactory, since, MVCContrib 3 excluded it.
*Used RegisterControllers extension method of container
public class WindsorControllerFactory : DefaultControllerFactory
{
private IWindsorContainer _container;
/// <summary>
/// Creates a new instance of the <see cref="WindsorControllerFactory"/> class.
/// </summary>
/// <param name="container">The Windsor container instance to use when creating controllers.</param>
public WindsorControllerFactory(IWindsorContainer container)
{
if (container == null)
{
throw new ArgumentNullException("container");
}
_container = container;
}
protected override IController GetControllerInstance(RequestContext context, Type controllerType)
{
if (controllerType == null)
{
throw new HttpException(404, string.Format("The controller for path '{0}' could not be found or it does not implement IController.", context.HttpContext.Request.Path));
}
var controller = (IController)_container.Resolve(controllerType) as Controller;
return controller;
}
public override void ReleaseController(IController controller)
{
var disposable = controller as IDisposable;
if (disposable != null)
{
disposable.Dispose();
}
_container.Release(controller);
}
}
and in Global.asax.cs, to register controllers,
_Container.RegisterControllers(typeof(HomeController).Assembly);
A: tugberk solution is great, but if you want a simple way, you can define a parameter less constructor for your LoginController and initialize it with default value like this:
public LoginController():this(new MyUser()) // MyUser is an implementation of IUser
{
}
public LoginController(IUser objUser)
{
_User = objUser;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547627",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: MySQL/PHP Relating Database Content by Keywords I read here a lot but this is the first I've asked a question.
I'm developing a website, with LAMP, that is essentially all about user submitted articles. I would like to relate some articles together by tags (or keywords) so that I may show a viewer some content that is related.
I had an idea of creating a field within the MySQL database table, where the articles resides, called "tags" that consists of a comma delimited list of keywords. They would relate to the article and describe it's content in some fashion. Yet I discovered this wasn't a bright idea as I wouldn't be able to index this very well.
So, how would I go about this, any ideas?
ps. Just seen the little box to the right on this site called, "Similar Questions" what I'm trying to achieve is a lot like that...
A: It's a many-to-many relationship, and can be modelled using a separate table with a foreign key to the article ID, and a column for a tag. Multiple tags are added to an article by adding multiple rows to the table.
For example, if you have two articles where:
*
*Article 1 has tags "foo" and "bar" and
*Article 2 has tags "bar" and "baz"
then the table might look like this:
article_tags
article_id tag
1 foo
1 bar
2 bar
2 baz
You can even store the tag names in a separate table:
tags
id name
1 foo
2 bar
3 baz
article_tags
article_id tag_id
1 1
1 2
2 2
2 3
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547628",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Inject/simulate WPF routed mouse click events I have some straight WPF 3.5 controls handling left mouse clicks that I need to use within a Surface app (SDK 1.0). The problem I am facing is that do not work by default. I am thinking of wrapping each control in a SurfaceContentControl and translating ContactTouchDown or ContactTapGesture events to corresponding MouseDown events.
The problem boils down to - how to "inject" or simulate arbitrary routed mouse events? I have tried InputManager.Current.ProcessInput() but didn't get very far. Any help is appreciated.
A: Try to use AutomationPeer classes. For example ButtonAutomationPeer is for Button. The code below initiates a click.
ButtonAutomationPeer peer = new ButtonAutomationPeer(button);
IInvokeProvider provider = (IInvokeProvider)peer.GetPattern(PatternInterface.Invoke);
provider.Invoke();
A: evpo's idea is an interesting one (though if you're working with custom controls, they rarely come with AutomationPeer classes).
You can't simply 'inject' mouse input by sending WM_MOUSE* events to your app... WPF would indeed process the message but when it goes to figure out the position of mouse for that event, it will query the actual mouse API instead of trying what you stick in the WM.
So really all you can do is tell windows to move the actual mouse cursor and act as though the button is being clicked/released. Some code you can use for that is in http://www.codeproject.com/KB/system/globalmousekeyboardlib.aspx
That said, while you can technically do this, it sucks... you've got an expensive multitouch device but are 1) showing a mouse cursor on it 2) limiting arbitrary parts of it to being used 'single touch' (and only one of those arbitrary parts at a time and 3) coming up with an arbitrary method of determining which finger you will treat as the mouse-controlling one
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547630",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: ImageIcon doesnt show up on top left app window I have this code:
public DesktopApplication1View(SingleFrameApplication app)
{
super(app);
pbu.registriere(this);
ImageIcon icon = new ImageIcon("resources/BilKa_Icon_32.png");
this.getFrame().setIconImage(icon.getImage());
initComponents();
Im wondering why the image icon doesnt show up on the top left of the app window. It`s still the Java cup of coffee logo instead.
Is there anything wrong?
Thank you
A: One likely possibility is your resource path could be incorrect. Depending on what your file hierarchy, and whether your class files are in a jar, etc. you might need a "/" at the beginning of the path before the res to make the path absolute instead of relative. Tutorial: http://download.oracle.com/javase/1.5.0/docs/guide/lang/resources.html
If you are fairly confident you are reading the image correctly (a good test would be to make a dummy component inside your window and see whether you can load the image into that), you should look into following through the Frame/Top Level Window Tutorial, particularly the parts about window decorations. In particular, one thing you may not be doing (I can't tell from your snippet) is that it appears you might need to set JFrame.setDefaultLookAndFeelDecorated(true); before the frame is created...which you would not be able to do using this.getFrame(), but need to do somewhere earlier in your initialization code.
A: Mike K is right, ImageIcons can be loaded dynamically, and images can have a zero size when they are first initialised. Also note that in Unix and in a JAR, the names are case sensitive.
try this:
try{
ImageIcon icon = new ImageIcon("resources/BilKa_Icon_32.png");
MediaTracker mt=new MediaTracker(this);
mt.addImage(icon.getImage(),0);
mt.waitForAll();
this.getFrame().setIconImage(icon.getImage());
}catch(InterruptedException excp){}
--
OK apologies I have edited the addImage - it takes an extra parameter ID which can be any number.
As to your error "no such constructor", it is telling you that you need to pass a Component to the constructor. Your app window is a component, so you should pass that here as a parameter. I used this because most people put this code inside the class that extends Frame, Window or JFrame. So use
MediaTracker mt=new MediaTracker(this.getFrame());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547631",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: is removeChild recursive? I create many new page elements (in some arbitrary hierarchy) using document.createElement and have been using element.removeChild() to erase elements I no longer want. I was wondering if this would correctly clean up all of the sub-elements as well, or if I should be using some sort of recursive function. Javascript uses a garbage collector, so I shouldn't need to worry about this, right?
A: Using element.removeChild(childElement) will remove the nodes from your document tree. If you've got a reference to the element, however, the element will not be garbage-collected (GC).
Consider:
Example 1 (horrible practice):
<body><script>
var d = document.createElement("div");
document.body.appendChild(d);
document.body.removeChild(d);
//The global scope won't disappear. Therefore, the variable d will stay,
// which is a reference to DIV --> The DIV element won't be GC-ed
</script></body>
Example 2 (bad practice):
function foo(){
var s = document.createElement("span");
document.body.appendChild(s);
s.innerHTML = "This could be a huge tree.";
document.body.addEventListener("click", function(ev){
alert(eval(prompt("s will still refer to the element:", "s")));
//Use the provided eval to see that s and s.innerHTML still exist
// Because this event listener is added in the same scope as where
// DIV `d` is created.
}, true);
document.body.removeChild(s);
}
foo();
Example 3 (good practice):
function main(){
//Functions defined below
addDOM();
addEvent();
remove();
//Zero variables have been leaked to this scope.
function addDOM(){
var d = document.createElement("div");
d.id = "doc-rob";
document.body.appendChild(d);
}
function addEvent(){
var e = document.getElementById("doc-rob");
document.body.addEventListener("click", function(ev){
e && alert(e.tagName);
//Displays alert("DIV") if the element exists, else: nothing happens.
});
}
function remove(){
var f = document.getElementById("doc-rob");
f.parentNode.removeChild(f);
alert(f);//f is still defined in this scope
Function("alert('Typeof f = ' + typeof f);")(); //alert("Typeof f = undefined")
}
}
main();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547634",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: external reference to third-party library (Jar) inside another Jar without wrap the second inside the first I'm writing a small fragment of code that aims at using AppleScriptEngine in order to communicate with Growl. I would obtain a jar file called MyApplication.jar with all my classes but I need to refer AppleScriptEngine.jar (developed by Apple and stored in /System/Library/Java/Extension)... Here the problem: AppleScriptEngine.jar is present in each Os x distribution so I would like refer to it inside MyApplication.jar MANIFEST.MF without adding AppleScriptEngine.jar inside my .jar file. This basically for two reasons: first of all AppleScriptEngine is a proprietary file of Apple, second I hope there is a way to refer an existing file inside the file system. I read a lot about the right composition of a jar file and in each example I found there is the external jar file packaged inside the coder's jar file.
I tryed to modify the class-path attribute inside my MANIFEST in order to point directly to the AppleScriptEngine.jar in this way:
Manifest-Version: 1.0
Rsrc-Class-Path: ./
Class-Path: /System/Library/Java/Extensions/AppleScriptEngine.jar
Rsrc-Main-Class: core.MyApplicationLauncher
Main-Class: org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader
Rsrc-Class-Path should be the local reference inside my jar, but giving the absolute path to Class-Path I sholud be able to refer to each file inside my system. Maybe there is something wrong in the way I define the path, or maybe I can refer only files that are nested inside my jar. Inside eclipse obviously all works fine because it has references to JRE System Library wich contains AppleScriptEngine.jar too. So, maybe there is a way to refer directly to JRE System Library inside my MANIFEST file. I wasn't able to find the answer after many hours of surfing.Has anyone an idea to overcome that impasse?
A: Finally I find the solution after a lot of trials and errors. My mistake was try to add the absolute path of AppleScriptEngine.jar as attribute to Class-Path; instead the right solution is to add as attribute of Class-Path only the absolute path of the folder that contains the Jar file we are interested in (the external one) and then add the name of that Jar file as value of Rsrc-Class-Path. I believe this is the right way to refer externals libraries in each case in which the file is already located in the file system. Here my MANIFEST.MF:
Manifest-Version: 1.0
Rsrc-Class-Path: ./ AppleScriptEngine.jar
Class-Path: . /System/Library/Java/Extensions/
Rsrc-Main-Class: core.NotifierLauncher
Main-Class: org.eclipse.jdt.internal.jarinjarloader.JarRsrcLoader
NOTE that after Class-Path: there is a blank space before the dot and after the dot. This is because the blank space is the way used inside the MANIFEST file to separate different arguments. There isn't a friendly documentation about that argument
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547635",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to find if the image has black rectangles of size greater than 5*5 I am trying to write a program in c# or c++, which finds if the image (png or jpg) has a rectangle which is black in color and is greater than size 5 * 5 pixels. If there are multiple such rectangles in an image, it should be able to give me the coordinates of all such rectangles which are black in color.
A: You could try an Image Correlation:
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547636",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: cakephp logout redirect I have a cakephp app that when I logout it add's admin/login ti the url of the logging in screen. Then when I log in again it says missing controler. I already have a redirect to the Auth logout. If I change that will it still logout?
Original login url:
mydomain.com/res/admin
Url after logout
mydomain.com/res/admin/users/login
After I log in to admin:
mydomain.com/res/admin/admin/login
user controller:
function admin_logout() {
$this->redirect($this->Auth->logout());
}
A: In AppController you can do something like this
public $components = array(
'Session',
'Auth' => array(
'loginRedirect' => array('controller' => 'posts', 'action' => 'index'),
'logoutRedirect' => array('controller' => 'users', 'action' => 'login', 'login'),//redirect url
'authorize' => array('Controller')
)
);
and in UserController
public function logout() {
$this->redirect($this->Auth->logout());
}
this worked for me.
A: I solved this by putting a logout redirect in the beforefilter.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547639",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to make the text bold using jquery I have this out put.
<option value="18277">Dollar Max Hospice~Mx</option>
<option value="12979">Routine Adult Physical Exam Visit Limit</option>
<option value="12841">Is Reverse Sterilization Covered Out of Network?</option>
<option value="12918">MD CDH PPO Variables 2</option>
<option value="12917">DC CDH PPO Variables 2</option>
<option value="12833">Is Sterilization Covered No Network?</option>
<option value="12834">Is Sterilization Covered In Network</option>
I have a search box and button when i hit Dollar I need to bold the text in my list box. I need to itterate the list box data and make that text as bold.
A: Using the jQuery, you can apply the css:
font-weight:Bold;
So just do:
$myElement.css("font-weight","Bold");
A: For me on FF6 at least, it will show as a normal font in the select box, however in the actual list itself it will show bold if you do:
$('select option[value="18277"]').css({ 'font-weight': 'bold' });
A: You can't bold an individual <option> in a <select> control. It's annoying, but that's how it is.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547643",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
} |
Q: Pass variable in document.getElementByid in javascript I have a variable account_number in which account number is stored. now i want to get the value of the element having id as account_number. How to do it in javascript ?
I tried doing document.getElementById(account_number).value, but it is null.
html looks like this :
<input class='transparent' disabled type='text' name='113114234567_name' id='113114234567_name' value = 'Neeloy' style='border:0px;height:25px;font-size:16px;line-height:25px;' />
and the js is :
function getElement()
{
var acc_list = document.forms.editBeneficiary.elements.bene_account_number_edit;
for(var i=0;i<acc_list.length;i++)
{
if(acc_list[i].checked == true)
{
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
alert(document.getElementById("'" + ben_name.toString() + "'").value);
}
}
}
here bene_account_number_edit are the radio buttons.
Thanks
A: Are you storing just an integer as the element's id attribute? If so, browsers tend to behave in strange ways when looking for an element by an integer id. Try passing account_number.toString(), instead.
If that doesn't work, prepend something like "account_" to the beginning of your elements' id attributes and then call document.getElementById('account_' + account_number).value.
A: Why are you prefixing and post-fixing ' characters to the name string? ben_name is already a string because you've appended '_name' to the value.
I'd recommend doing a console.log of ben_name just to be sure you're getting the value you expect.
the way to use a variable for document.getElementById is the same as for any other function:
document.getElementById(ben_name);
I don't know why you think it would act any differently.
A: There is no use of converting ben_name to string because it is already the string.
Concatenation of two string will always give you string.
var account_number = acc_list[i].value.toString();
var ben_name = account_number + "_name";
try following code it will work fine
var ben_name=acc_list[i]+ "_name";
here also
alert(document.getElementById("'" + ben_name.toString() + "'").value);
try
alert(document.getElementById(ben_name).value);
I have tested similar type of code which worked correctly. If you are passing variable don't use quotes. What you are doing is passing ben_name.toString() as the value, it will definitely cause an error because it can not find any element with that id viz.(ben_name.toString()). In each function call, you are passing same value i.e. ben_name.toString() which is of course wrong.
A: I found this page in search for a fix for my issue...
Let's say you have a list of products:
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_1">149.95</p>
<a href="#" title="Western Digital 1TB" class="gray-btn-sm add-to-cart text-shadow">add to cart</a>
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_2">139.95</p>
<a href="#" title="Western Digital 1TB" class="gray-btn-sm add-to-cart text-shadow">add to cart</a>
</div>
<div class="rel-prod-item">
<img src="assets/product-photos/title-of-the-related-product_thumbnail.jpg" alt="Western Digital 1TB" />
<p class="rel-prod-title">Western Digital 1TB</p>
<p class="rel-prod-price" id="price_format_3">49.95</p>
<a href="#" title="Western Digital 1TB" class="gray-btn-sm add-to-cart text-shadow">add to cart</a>
</div>
The designer made all the prices have the digits after the . be superscript. So your choice is to either have the cms spit out the price in 2 parts from the backend and put it back together with <sup> tags around it, or just leave it alone and change it via the DOM. That's what I opted for and here's what I came up with:
window.onload = function() {
var pricelist = document.getElementsByClassName("rel-prod-price");
var price_id = "";
for (var b = 1; b <= pricelist.length; b++) {
var price_id = "price_format_" + b;
var price_original = document.getElementById(price_id).innerHTML;
var price_parts = price_original.split(".");
var formatted_price = price_parts[0] + ".<b>" + price_parts[1] + "</b>";
document.getElementById(price_id).innerHTML = formatted_price;
}
}
And here's the CSS I used:
.rel-prod-item p.rel-prod-price b {
font-size: 50%;
position: relative;
top: -4px;
}
I hope this helps someone keep all their hair :-)
Here's a screenshot of the finished product
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547644",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to scrape a huge amounts of tweets I am building a project in python that needs to scrape huge and huge amounts of Twitter data. Something like 1 million users and all their tweets need to be scraped.
Previously I have used Tweepy and Twython, but hit the limit of Twitter very fast.
How do sentiment analysis companies etc. get their data? How do they get all those tweets? Do you buy this somewhere or build something that iterates through different proxies or something?
How do companies like Infochimps with for example Trst rank get all their data?
* http://www.infochimps.com/datasets/twitter-census-trst-rank
A: I don't know if this will work for what you're trying to do, but the Tweets2011 dataset was recently released.
From the description:
As part of the TREC 2011 microblog track, Twitter provided identifiers
for approximately 16 million tweets sampled between January 23rd and
February 8th, 2011. The corpus is designed to be a reusable,
representative sample of the twittersphere - i.e. both important and
spam tweets are included.
A: If you want the latest tweets from specific users, Twitter offers the Streaming API.
The Streaming API is the real-time sample of the Twitter Firehose. This API is for those developers with data intensive needs. If you're looking to build a data mining product or are interested in analytics research, the Streaming API is most suited for such things.
If you're trying to access old information, the REST API with its severe request limits is the only way to go.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547646",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to make X.509 certificate? I am trying to make a X.509 certificate. I am using makecert.exe to make this. I use this command to make my X.509 certificate
makecert.exe -sr LocalMachine -ss My -a sha1 -n CN=MyServerCert -sky exchange –pe
But i don`t know there X.509 certificate is storeing.
I need to use this X.509 certificate in my c# code. The code is :
host.Credentials.ServiceCertificate.Certificate = new X509Certificate2("MyServerCert.p12", "password");
But i don`t know what is password and it throw this exception "The system cannot find the file specified."
A: I always use the SelfCert tool from PluralSight. You can download it here. The same pages also give usage and code examples.
Great free tool, can't do without it.
A: It is nice that you have find that makecert command but perhaps if you would also check makecert documentation you have found where the certificate is stored because it is defined in the paramaters of your command:
*
*sr says that certificate will be generated for LocalMachine store location
*ss says that certificate will be stored in Personal (My) store
The certificate is stored in certificate store so use MMC.exe to find it:
*
*Open Start menu
*In Search / Run type mmc and run it
*In File menu select Add / Remove snap-in
*Select Certificates snap-in with scope of Local computer and confirm selection
Now in Personal store for your LocalMachine select certificate called MyServerCert and from context menu select All Tasks > Export. During Exporting check that you want export private key but don't check extended security or private key deletion. You will also have to select path where exported certificate will be stored and password for access to a private key.
From VS command prompt you can also run this command which will do the export for you as well:
certutil.exe -privatekey -p password -exportpfx "MyServerCert" C:\Temp\MyServerCert.pfx
It should export your certificate with private key to Temp directory and password to certificate will be password.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547647",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Android SQLiteDatabase NullpointerException Okay full code now:
DBOpenHelper:
public class DBOpenHelper extends SQLiteOpenHelper {
private SQLiteDatabase mDatabase;
private static final int DATABASE_VERSION = 1;
private static String DATABASE_NAME = "RTDB";
private static final String DB_TABLE_NAME1 = "playertable";
private static final String DB_TABLE_NAME2 = "itemtable";
private static final String DB_CREATE_TABLE_PT =
"CREATE TABLE IF NOT EXISTS" + DB_TABLE_NAME1 + " ("
+ "ID INT(1) NOT NULL ,"
+ "Name VARCHAR(30) ,"
+ "HP INT(3) ,"
+ "Satisfaction INT(3) ,"
+ "Hygiene INT(1) , "
+ "IsAlive INT(1) "
+ " )"
;
private static final String DB_CREATE_TABLE_IT = "CREATE TABLE IF NOT EXISTS"
+ DB_TABLE_NAME2 + " ("
+ "Money INT(3) ,"
+ "Gas INT(3) ,"
+ "Food INT(3) ,"
+ "Toiletries INT(3) ,"
+ "Spareparts INT(3) ,"
+ "Meds INT(3) ,"
+ "Tents INT(3) ,"
+ "Ration INT(1) ,"
+ "Trabbihp INT(3) ,"
+ "Trabbispeed INT(2) ,"
+ " )"
;
public DBOpenHelper(Context context, String databaseName) {
super(context, databaseName, null, DATABASE_VERSION);
}
@Override
public void onCreate(SQLiteDatabase db) {
mDatabase = db;
mDatabase = SQLiteDatabase.openOrCreateDatabase(DATABASE_NAME,null);
mDatabase.execSQL(DB_CREATE_TABLE_PT);
mDatabase.execSQL(DB_CREATE_TABLE_IT);
DB.savePlayer(Resource.playerArray);
}
@Override
public void onUpgrade(SQLiteDatabase arg0, int arg1, int arg2) {
}
}
DB:
public class DB {
static Context context;
private static DBOpenHelper dbHelper = new DBOpenHelper(context, "RTDB");
public static SQLiteDatabase db = dbHelper.getWritableDatabase();
private static ContentValues itemValues = new ContentValues();
private static ContentValues playerValues = new ContentValues();
// Speichern der Spieler in der Datenbank - playerarray muss �bergeben werden
public static void savePlayer(Player player[]){
for(int i = 0; i<3; i++){
playerValues.put("ID", i);
playerValues.put("Name", player[i].getName());
playerValues.put("HP", player[i].getHp());
playerValues.put("Satisfaction", player[i].getsatisfaction());
playerValues.put("Hygiene", player[i].isHygieneInt());
playerValues.put("IsAlive", player[i].isAliveInt());
}
db.insert("playertable", null, playerValues);
}
// Speichern der Items
//TODO Position fehlt noch
public static void saveItems(){
itemValues.put("Money", Resource.money);
itemValues.put("Gas", Resource.gas);
itemValues.put("Food", Resource.food);
itemValues.put("Toiletries", Resource.toiletries);
itemValues.put("Spareparts", Resource.spareparts);
itemValues.put("Meds", Resource.meds);
itemValues.put("Tents", Resource.tents);
itemValues.put("Ration", Resource.ration);
itemValues.put("Trabbihp", Resource.trabbihp);
itemValues.put("Trabbispeed", Resource.trabbispeed);
db.insert("itemtable",null,itemValues);
}
// Hier werden die Items aus der Datenbank abgefragt, der zurueckgelieferte Cursor vie cursorToIntArray() in einen Int Array umgewandelt und dessen Inhalt in die Ressource Klasse geschrieben
public void loadItems(){
Cursor itemCursor = db.query("itemtable", null, null, null, null, null, null);
int[] itemIntArray = cursorToInt(itemCursor, 9);
Resource.money = itemIntArray[0];
Resource.gas = itemIntArray[1];
Resource.food = itemIntArray[2];
Resource.toiletries = itemIntArray[3];
Resource.meds = itemIntArray[4];
Resource.tents = itemIntArray[5];
Resource.ration = itemIntArray[6];
Resource.trabbihp = itemIntArray[7];
Resource.trabbispeed = itemIntArray[8];
}
//Name und Restliche Int-Werte der Playerobjekte werden separat aus der Datenbank geholt und gesetzt
public static void loadPlayer(){
String[] namecolumn = {"Name"};
String[] intcolumn = {"HP, Satisfaction, Hygiene, IsAlive"};
String[] namesToString;
for(int j=0;j<3;j++){
Cursor playerCursorName = db.query("playertable", namecolumn, "ID="+j, null, null, null, null);
namesToString = cursorToString(playerCursorName);
Resource.playerArray[j].setName(namesToString[j]);
}
for(int i=0;i<3;i++){
int[] restToInt;
Cursor playerCursorInt = db.query("playertable", intcolumn, "ID="+i, null, null, null, null);
restToInt = cursorToInt(playerCursorInt,4);
Resource.playerArray[i].setHp(restToInt[i]);
Resource.playerArray[i].setsatisfaction(restToInt[i]);
Resource.playerArray[i].setHygieneInt(restToInt[i]);
Resource.playerArray[i].setAliveInt(restToInt[i]);
}
}
public void dropTables(){
db.execSQL("DROP TABLE 'playertable';");
db.execSQL("DROP TABLE 'itemtable';");
}
private static int[] cursorToInt(Cursor cursor, int n){
int[] results = new int[n];
for(int i=0 ;i<= n-1; i++){
results[i] = cursor.getInt(i);
}
return results;
}
private static String[] cursorToString(Cursor cursor){
String[] results = new String[4];
for(int i=0 ;i<= 3; i++){
results[i] = cursor.getString(i);
}
return results;
}
}
For new readers:
The public static SQLiteDatabase db = dbHelper.getWritableDatabase(); - statement causes a nullpointerexception
DBOpenHelper is a helperclass to create the Database. It gets instances in DB.java where I created some methods to operate on the database like savePlayer etc
EDIT:
While debugging I found something in the line mentioned above
The dbHelper object points also to mContext, mDatabase etc which are - as you might have imagined - null
atm I'm trying to resolve this, but I can't find a way to set them
A: As I see you didn't initialize your database :
private static DBOpenHelper dbHelper = new DBOpenHelper(context);
public static SQLiteDatabase db = dbHelper.getWritableDatabase();
You need to have a constructor in your DBOpenHelper class where you can set the name of database for your project.You are setting your database in your DB class,but never using it :
private static String filename = "RTDB.sql";
That's why you are getting NullPointerException, because there is no database which you can get.
EDIT : You can do something like this :
public DBOpenHelper(Context context, String databaseName) {
super(context, databaseName, null, DATABASE_VERSION);
}
in that way when you are initializing your database you can set the name of database that you want to use.
A: static Context context;
private static DBOpenHelper dbHelper = new DBOpenHelper(context, "RTDB.sql");
i guess context == null.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547651",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I use UIWebView in Objective-C to display a Webpage I've been trying to implement UIWebView into my application for a while now but when I do my application crashes upon startup.
My code is:
-(void)viewDidLoad {
[super viewDidLoad];
NSString *urlAdress=@"http://www.facebook.com";
NSURL *url = [NSURL URLWithString:urlAdress];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];
The Debugger says Thread 1: Stopped at breakpoint 4
A: Your problem is that you have breakpoints set. See the blue arrow in the narrow column immediately left of your code? You have three of them set. You can disable the break point by clicking on the blue breakpoint arrow so that it dims (disabled). You can remove the breakpoint by right clicking on the blue arrow and removing it. A second way to remove it is to click and drag the breakpoint into the main window of your code, causing it to use the same dissolve animation used on the Mac OS X dock when you remove an item from it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547653",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: wxPython - Import Error - Environment Variables? I'm running Python 2.7 and wxPython 2.8 on 64-bit Windows 7 (but Python and wx are both the 32-bit versions).
I'm trying to import the module, but import wx returns an error:
Traceback (most recent call last):
File "C:/Users/Adam/Desktop/test", line 4, in <module>
import wx
File "C:\Users\Adam\Desktop\test.py", line 8, in <module>
class MyFrame(wx.Frame):
AttributeError: 'module' object has no attribute 'Frame'
From research I think I've not set up some enviroment variables correctly, but everywhere I look no one actually says what I need to add to what variables.
Thanks a lot!
A: The only thing that comes to mind is that you've called something else "wx.py". Print the value of wx.__file__ to verify, and then rename it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547654",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Why can't I define a nested class externally? I'm having trouble putting together an object model that involves nested classes, using MinGW C++. Here is an example that exposes my issue:
foo.h:
/*
* foo.h
*
* Created on: Sep 25, 2011
* Author: AutoBot
*/
#ifndef FOO_H_
#define FOO_H_
class Foo
{
public:
class Bar;
Bar bar;
} extern foo;
#endif /* FOO_H_ */
bar.h:
/*
* bar.h
*
* Created on: Sep 25, 2011
* Author: AutoBot
*/
#ifndef BAR_H_
#define BAR_H_
#include <iostream>
using namespace std;
#include "foo.h"
class Foo::Bar
{
public:
void Test() {cout <<"Test!";}
};
#endif /* BAR_H_ */
main.cpp:
/*
* main.cpp
*
* Created on: Sep 25, 2011
* Author: AutoBot
*/
#include "foo.h"
Foo foo;
int main (int argc, char *argv[])
{
foo.bar.Test();
return 0;
}
Eclipse CDT build log:
**** Build of configuration Debug for project NestedClassTest ****
**** Internal Builder is used for build ****
g++ -O0 -g3 -Wall -c -fmessage-length=0 -o src\main.o ..\src\main.cpp
In file included from ..\src\main.cpp:10:0:
..\src\/foo.h:15:6: error: field 'bar' has incomplete type
..\src\main.cpp: In function 'int main(int, char**)':
..\src\main.cpp:16:6: error: 'class Foo' has no member named 'bar'
Build error occurred, build is stopped
Time consumed: 171 ms.
So essentially it's failing to recognize the definition of bar I made in bar.h. Is this normal? Why shouldn't I be able to define nested classes this way? Is this simply a limitation of the MinGW toolchain? Any help/advice is appreciated.
Side note: in my actual program, I intend for the "foo" of it to serve as, theoretically, a singleton class. It would represent the application as a whole, and it's subsystems (or "bars") would be defined and instantiated once inside the class. I'm doing this to try to make the code more manageable. If anyone has a more feasible design pattern in mind, please tell me!
A: One of the problems you have here, is that when you do:
class Foo
{
public:
class Bar;
Bar bar;
} extern foo;
Bar bar is illegal because you are trying to use the class bar; which provides an incomplete type.
You also do not include Bar.h
A: The problem is here:
class Foo
{
public:
class Bar;
Bar bar;
};
At this point Foo::Bar is an incomplete type. And you cannot declare a variable of an incomplete type. It would be no different from trying to do this:
class Foo;
Foo foo;
They're both not allowed and for the same reason.
You could turn bar into some kind of (smart) pointer. But that's the only way to solve this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547655",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Libxml parser iphone issue I am using libxml for parsing the xml. I have referred the XMLPerformance example by apple.
Following is the part of xml document which is causing a problem as it contain the " " string. i cannot just replace this " " with any other string is i am getting data in didReceiveData delegate method and i am parsing that data.
Is there any solution to resolve this issue which is coming because of special character?
<ParentTag>
<AUTHOR>Actavis"Totowa "LLC</AUTHOR>
<SPL_INACTIVE_ING>lactose"monohydrate"/"magnesium"stearate"/"starch"pregelatinized"/"talc</SPL_INACTIVE_ING>
</ParentTag>
Any help will be appreciated.
Thanks in advance
A:
To make sure your XML is well format, you can test you XML first with any online XML validator and then later you should parse that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547659",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Android Custom Listview issue - for time schedule can I change the text color and size? I'm working on a project which is something like bus schedule.And I'm curious about one thing : Is there any way to do something like this :
This is how I want to look like my list view. My idea is to get the current time and than show when the first bus depending on current time is leaving. So if it's 12:00 am/pm I want to show that the next bus is leaving at 12:15 like this.To make the text in different color and make it bigger.
Any ideas or suggestions how can I do that or is it possible to make something like that?
Thanks in advance!
A: use custom adapter for listview and from that class's getview() method just check your current time from that get the depend time. If It available then change the text and font of that list row (textview) simple. Thanks.
A: You can set the required item as selected item. Then in onItemSelected listener you can change its text color and size. Also maintain the current selected item in a member so that you can revert the size and color when it's unselected.
Reference :
http://developer.android.com/reference/android/widget/AdapterView.OnItemSelectedListener.html
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547661",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Ajax json post to Controller across domains, "not allowed by" Access-Control-Allow-Headers I create a simple MVC Controller action, that takes some json data - then return true or false.
[AllowCrossSiteJson]
public JsonResult AddPerson(Person person)
{
//do stuff with person object
return Json(true);
}
I call it from javascript:
function saveData(person) {
var json = $.toJSON(person); //converts person object to json
$.ajax({
url: "http://somedomain.com/Ajax/AddPerson",
type: 'POST',
dataType: 'json',
data: json,
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert("ok");
}
});
}
Everything works as long as I am on the same domain, but as soon as I call it from another domain, I run into problems.
On the controller is an action filter "AllowCrossSiteJson" that sets the header "Access-Control-Allow-Origin" to "*", allowing any origin to access the controller action.
public class AllowCrossSiteJsonAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.RequestContext.HttpContext.Response.AddHeader("Access-Control-Allow-Origin", "*");
base.OnActionExecuting(filterContext);
}
}
However - I then get this error in firebug, when calling across domains:
OPTIONS http://somedomain.com/Ajax/AddPerson?packageId=3 500 (Internal Server Error)
XMLHttpRequest cannot load http://somedomain.com/Ajax/AddPerson. Request header field Content-Type is not allowed by Access-Control-Allow-Headers.
What is wrong here?
I have been looking through possible solutions for hours, and it seems to be something to do with jquery using OPTIONS (not POST as I would expect).
If that is indeed the problem, how can I fix that?
A: I'd recommend you JSONP, it's the only really cross browser and reliable solution for cross domain AJAX. So you could start by writing a custom action result that will wrap the JSON response with a callback:
public class JsonpResult : ActionResult
{
private readonly object _obj;
public JsonpResult(object obj)
{
_obj = obj;
}
public override void ExecuteResult(ControllerContext context)
{
var serializer = new JavaScriptSerializer();
var callbackname = context.HttpContext.Request["callback"];
var jsonp = string.Format("{0}({1})", callbackname, serializer.Serialize(_obj));
var response = context.HttpContext.Response;
response.ContentType = "application/json";
response.Write(jsonp);
}
}
and then:
public ActionResult AddPerson(Person person)
{
return new JsonpResult(true);
}
and finally perform the cross domain AJAX call:
$.ajax({
url: 'http://somedomain.com/Ajax/AddPerson',
jsonp: 'callback',
dataType: 'jsonp',
data: { firstName: 'john', lastName: 'smith' },
success: function (result) {
alert(result);
}
});
A: To fix the Access-Control-Allow-Origin error, you need to include the following header in your response:
Access-Control-Allow-Headers: Content-Type
Basically, any "non-simple" header needs to be included as a comma-delimited list in the header above. Check out the CORS spec for more details:
http://www.w3.org/TR/cors/
"Content-Type" needs to be included because "application/json" does not match the values defined here:
http://www.w3.org/TR/cors/#terminology
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547672",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
} |
Q: asp.net mvc 3 serverside remote validation not working on submit through fiddler I am trying to understand how remote validation works. It works great client side or in browser. This is what I did, I need to check if a username exists while registration. So I added remote validation and it worked perfectly in browser. I wanted to test it on submit, so I captured the request in Fiddler and changed the username to something that exists and then submitted the request. It accepted. RemoteValidation did not occur (of course it failed at db). Hence doesn't it validate on server side?
A:
Hence doesn't it validate on server side?
No, of course that it doesn't validate on the server. It's just an AJAX call when you modify the value of the corresponding input but when the form is submitted you should obviously perform this validation once again.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Regex extract numbers from Url (except port number) i have to extract id value of a product from url.
It is SEO Friendly (url routing).
Url can be
http://www.example.com/{param0}/{param1}/123/{param2}/{paramN}
Or
http://localhost:6847/{param0}/{param1}/123/{param2}/{paramN}
For the first url there is no problem.
But for the second i want to extract ONLY the 123 or (ID) <-(It is an Integer).
I know that if i want to extract only numbers i can use
[0-9]+
but how can i tell regengine how to get all the numerical data from url except numbers that may have
:
before.
i use :
((!:)[0-9]+)
it is not correct.
Every advice is wellcamed:)
Thank you.
A: There needs to be more info on what delimits the 123 in your example.
On its face, (?<!:)[0-9]+ will find the first clump of digits NOT preceded by ':'
Edit Probably for more accuracy, this (?<!:\d+)[0-9]+ would be better.
Note this is if .NET allows variable length look-behind (I think it does).
For fixed length look-behind (PCRE), something like this might work: (?<![:\d])[0-9]+
Edit2
@Sanosay- After thinking about .NET type lookbehinds, the above regex needs a slight change.
It should be (?<!:\d*)[0-9]+ . Thats because in ':1234', 1 will satisfy the assertion.
Hope you figured this to be the case. I made a test case for the two regex's
@"(?<!:\d*)[0-9]+"
@"(?<![:\d])[0-9]+"
that satisfy the conditions.
The link to the ideone C# code is here: http://ideone.com/tLn2j
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547680",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Custom Detail Image View from Three20 I am pretty new with Three20. I have followed ray wenderlich's nice introduction to three20 and the examples within the three20 framework. When I click on a thumbnail in a thumbnail view (subclass of TTThumbsViewController) to launch a Details view, a standard Details image view (deployed by TTPhotoViewController or its super class). I would like to use my own implementation of a Details View instead of the default. I put the following code when I initiated the subclass of TTThumbsViewController and TTThumbsViewControllerDelegate method:
- (id)initWithDelegate:(id<TTThumbsViewControllerDelegate>)delegate {
[super initWithDelegate:delegate];
return self;
}
- (void)thumbsViewController: (TTThumbsViewController*)controller
didSelectPhoto: (id<TTPhoto>)photo {
[navigationController.pushViewController:photoDetailViewController
animated:Yes];
}
But the default TTPhotoViewController view still prevail. When I put a NSLog in the delegate method. I coud see the method was called. I think there is another delegate someone already set in TTThumViewController? Can someone recommend a way to display my detail photo view? Is there another thumbs view controller I can use? Any suggestion will be greatly appreciated.
A: I'm really new to all of this (coding, etc.) but I'll share what I've found. By looking up the definition of ttthumbsviewcontroller, I was able to find the following method(wrong term?):-
- (void)thumbsTableViewCell:(TTThumbsTableViewCell*)cell didSelectPhoto:(id<TTPhoto>)photo {
[_delegate thumbsViewController:self didSelectPhoto:photo];
BOOL shouldNavigate = YES;
if ([_delegate respondsToSelector:@selector(thumbsViewController:shouldNavigateToPhoto:)]) {
shouldNavigate = [_delegate thumbsViewController:self shouldNavigateToPhoto:photo];
}
if (shouldNavigate) {
NSString* URL = [self URLForPhoto:photo];
if (URL) {
TTOpenURLFromView(URL, self.view);
} else {
TTPhotoViewController* controller = [self createPhotoViewController];
controller.centerPhoto = photo;
[self.navigationController pushViewController:controller animated:YES];
}
}
}
In the else statement, I've found this calls the creation of the photoviewcontroller. By recalling this method (?) in the actual body of my own code and changing the body in the else statement I was able to add a custom detail view. Further down the definition of the ttthumbsnailviewcontroller, you can find that the creatPhotoViewController calls for an initiation of the PhotoViewController so calling that method(?) in the body of the code and initializing another view also works.
If someone can explain whether or not this is a good method of doing this (I have a feeling that is not), it would be appreciated. Also why does putting the method in the body of the code override the call there.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Open file location in GUI using keyboard only I know about the
[ctrl] + [alt] + t
[ctrl] + f
[alt] + f1
shortcuts to bring up the standard system browsing tools, and I use them often. I am not satisfied with them (except the terminal...of course).
My question is: is there an equivalent to the Window's shortcut
[windows-key] + e
that brings up the "Computer" window? Having access to the GUI based file browser is nice, especially when I am literally browsing for a file in an unknown location.
pwd
ls
cd
gets a little old when you're not 100% sure what you're looking for.
Please answer the question in a manner that I could add your tip to the keyboard shortcut menu, which is found by running
gnome-keybinding-properties
at the command line on debian-type distributions. If you've got something I could grab from synaptic, I'd appreciate that as well.
Thanks.
p.s. I hate the mouse. Please don't tell me to double click the Computer icon on the desktop.
A: I guess your file manager is nautilus since you mentioned gnome.
can you add custom keyboard shotcut? if yes, add this command to a custom shortcut.
nautilus computer:///
btw
if you really hate mouse, you would like to try ranger. http://savannah.nongnu.org/projects/ranger
A: Into gnome-keybinding-properties, their is a home directory shortcut. Type
[your_shortcut_for_home_directory], <alt> + <up>, <alt> + <up>
(very quickly).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547687",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: canvas or OpenGL ES? I am embarking on a project (game) and I have a question about the implementation, will be developed specifically for Android and want to know which is better (easier, faster to develop and portable). canvas or OpenGL ES
A: Unless you already have a good working knowledge of OpenGL, then using a Canvas will be easier and faster. In terms of portability it really isn't as clear cut.
That said you should probably consider using one the pre-existing game engines, if you really only about Android then you should check out http://www.andengine.org/ its a great engine with a strong community and lots of great little example games.
A: Actually I'm not really sure where I read this,but when it's about developing game if you have any knowledge of OpenGL, you better use that,because the system is separating more space for your application so it can run without lagging or crash.So you can't get an Memory Full error. (Please correct me if I'm wrong.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547688",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: jQuery Slidetoggle - force div open if closed? I am using jQuery slideToggle to show/hide comments. I need my function to always make sure the DIV is open after a comment post. How do I do this?
$.ajax({
type: "POST",
data: "trackid="+trackid,
url: "http://rt.jaxna.com/viewcomments.php",
success: function(data)
{
// alert(data);
$(".userError").append(data);
}
});
$(parent).slideToggle();
$(parentNew).slideToggle();
A: add
if($('#my_div').is(':hidden'))
{
$('#my_div').slideDown();
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547691",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to check the text of an NSTextField (Label) In Xcode I'm trying to get the text of an NSTextField (Label) to see if it says Yes or it is says No
I've tried this:
if ([LabelYesNo StringValue] == @"Yes"){
[LabelYesNo setStringValue:@"No"];
else{
[LabelYesNo setStringValue:@"Yes"];
}
}
and
if (LabelYesNo isEqualToString @"Yes"){
[LabelYesNo setStringValue:@"No"];
else{
[LabelYesNo setStringValue:@"Yes"];
}
}
and a few other variations of that. Just can't seem to get it right.... Can anyone help?
Thanks
A: [[theTextField stringValue] isEqualToString:@"Yes"];
should work
in your first code, you're comparing strings via ==. Using the C == operator will simply compare the addresses of the objects.
in your second code, your whole code is wrong, and you'are trying to compare element of type NSTextField to NSString.
see String comparison in Objective-C
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547699",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Does the release of Google Wallet change any of the capabilities available to Android developers? Recently, Google released Google Wallet and additionally released an update for Sprint Nexus S phones (CNET , NFCWorld ) to enable the secure elements on the phone, (probably the SmartMax chip).
-Can we presume that, despite Google's great protestations at Google I/O (at 55 minutes of Google I/O Presentation ), the Android phones are in fact implementing Google Wallet using the NFC chip in card emulation mode?
-Have there been attempts by third parties to gain access to the secure elements on the phones using the same means as Wallet using the new update? I'm familiar with SEEK , but currently that's impractical because it requires flashing the phone to access internal secure elements.
Thanks.
A: *
*according to my understanding the Google (or Samsung) or other TSM will be the only entities who will be ever allowed to make upload of the cardlets to the secure element, so even API will be open to the scale you can call the cardlet (I think there is JavaCard on SmartMX) you will not be upload anything there.
*Yes, Google Wallet is working in the card emulation mode - this is the only mode they can in a secure way be compatible with MasterCard PayPass
*Google will probably never allow small companies to access the secure element. They can have deal with big players, banks, Visa/MasterCard/Amex, mobile network operators, some TSM...
*Anyway we are living in the changing world, so possibilities are open - they can somehow change their mind, but I will not rely on the option that the built-in secure element will be ever opened.
BR
STeN
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547702",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Apache VirtualHost won't work (Wamp/Win7) I own two domains which I want to point to my local server here at home:
*
*www.first.com
*www.second.com
They both point to my own server here at home (Yes I've already managed the A-record config at my webhotel where I registered the domains).
I've done the following:
*
*In httpd.conf, I've uncommented the line Include conf/extra/httpd-vhosts.conf
*In httpd-vhosts.conf I have the following code:
NameVirtualHost *:80
<VirtualHost *:80>
ServerName first.com
ServerAlias www.first.com
DocumentRoot "C:/wamp/www/public/first"
</VirtualHost>
<VirtualHost *:80>
ServerName second.com
ServerAlias www.second.com
DocumentRoot "C:/wamp/www/public/second"
</VirtualHost>
*In the httpd.conf file, I've set document-root to C:\wamp\www\public, and this is the step I'm most uncertain of. What should the document root be in the httpd.conf file when the httpd-vhosts.conf file declares multiple document roots? I've tried to set the document root of httpd.conf to both C:/wamp/www/public and only C:/wamp/www/
What am I missing here? The pages won't load at all.
A: DocumentRoot for "main" server haven't sense as soon as you define Virthosts - known virthosts will be served from their definition, unknown - by first virthost in list
Create separate log-files per virthost and yes, check logs after access attept
The pages won't load at all
It's bad error-description. Which error-code you get? Do you have DirectoryIndex and index-file in virthost root? What about Allow/Disallow directives for Directory locations?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547704",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Read directory then insert to sql For some reason I am just dumb with arrays... I cannot figure them all the way out... All I want to do here is read a folder and get all the folder names inside of that folder and insert them into a mysql db. Now the db part isn't my problem. Its handling this array. I did something similar in an earlier project, and now I cannot figure out how to modify it to work here.
<?php
$main_folder = 'C:/Users/Oval Office/Music/';
$folders = glob($main_folder, GLOB_ONLYDIR);
$artists_names = array();
foreach($folders as $folder){
$artists_names[] = preg_split('/(.+)\s(\d+)/', str_replace($main_folder, '', $folder), -1, PREG_SPLIT_DELIM_CAPTURE|PREG_SPLIT_NO_EMPTY);
}
$values = array();
foreach($artists_names as $pair){
$values[] = "('".$pair[0]."')";
}
$query = 'INSERT INTO artists (title) VALUES '.implode(',', $values);
$result = mysql_query($query);
echo ($result) ? 'Inserted successfully' : 'Failed to insert the values';
?>
The Title Is Just Blank...
Thank you pekka for stearing me in the right direction, post it as a answer so I can give ya some rep.
A: I think the wild-card is missing.
Try this:
$main_folder = 'C:/Users/Oval Office/Music/*';
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: drupal 7 calculated field returns undefined index Ok, struggling now after two hours - and I still cant get it.
I'm trying to average all of the fivestar ratings I have for a node using a computed field. But i'm struggling to simply access the other fields using entity!
In the body of the node, this works fine:
$test1 = $node->field_ae_stimclasswrk[und][0]['average'];
but in the computed field area, this doesn't work:
$entity_field[0]['value'] = $entity->field_ae_stimclasswrk[$entity->language] [und][0]['average'];
Instead, when I save the node, I get this index error:
Notice: Undefined index: und in eval() (line 2 of...
It must be something syntax, but i'm completely out of ideas.
here is the field info:
[field_ae_stimclasswrk] => Array
(
[und] => Array
(
[0] => Array
(
[user] => 80
[average] => 80
[count] => 1
)
)
)
A: Just a tiny error in your code:
$entity->field_ae_stimclasswrk[$entity->language][und][0]['average'];
If you look at that closely you're actually trying to access the language element of the field twice, once with $entity->language and once with und.
It would probably be best to keep the code contextual so I would remove the [und] item in the code:
$entity->field_ae_stimclasswrk[$entity->language][0]['average'];
A: I've had the same issue. It was actually caused by a non-existent index inside $entity->field_ref[$entity->language].
For me, $entity->field_ref[$entity->language] existed for all nodes but when you add an index inside that it causes a problem for any nodes that don't use the field.
$entity->field_ref[$entity->language][0] caused the issue (note the addition of the [0] index).
To solve your problem you could try:
$test1 = (isset($node->field_ae_stimclasswrk[$node->language][0]['average']))? $node->field_ae_stimclasswrk[$node->language][0]['average'] : NULL;
Or a little easier to read:
if (isset($node->field_ae_stimclasswrk[$node->language][0]['average'])){
$test1 = $node->field_ae_stimclasswrk[$node->language][0]['average'];
} else {
$test1 = NULL;
}
This way it will bypass any nodes that don't make use of the field.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: PHP error page problem I can't figure out why this script isn't working.
<?php
if (($_GET['p'] != 'index') &&
($_GET['p'] != 'reg') &&
($_GET['p'] != 'login') &&
($_GET['p'] != 'ad') &&
(!isset($_GET['p']))):
?>
<?php endif; ?>
I want to not display the error page if the $_GET is not set, which in my experience (!isset($_GET['p'])) should do.
A: If $_GET['p'] is not set, you can't check $_GET['p'] != 'index' and all the others. You'll have to check if it's set first:
<?php if(
! isset( $_GET['p'] ) ||
($_GET['p'] != 'index' &&
$_GET['p'] != 'reg' &&
$_GET['p'] != 'login' &&
$_GET['p'] != 'ad')
): ?>
A better solution would be to put all those values in an array, and check if $_GET['p'] is in the array:
<?php if(
! isset( $_GET['p'] ) ||
! in_array(
$_GET['p'],
array('index', 'reg', 'login', 'ad')
)
): ?>
EDIT:
Now that you provided some more info, here's what you should do:
if ( ! isset($_GET['p']) )
{
// We're at the index page, so don't display anything
}
else
{
if ( in_array( $_GET['p'], array('index', 'reg', 'login', 'ad') ) )
{
// Display your content window
}
else
{
// $_GET['p'] is not a valid value, display error
}
}
A: Your condition makes no sense. You're checking for 3 possible values of $_GET['p'] and then checking if $_GET['p'] is even set. Reverse your logic:
<?php
if(isset($_GET['p']))
{
// display error page
}
else
{
// do something else
}
A: You can check if $_GET['p'] is set by
if(isset($_GET['p']) {...}
If it's set and not empty then you can check for values that you need to check.
A: Try this:
<?php
$defaultvalue=0; // for example 0
$p=isset($_GET["p"]) ? $_GET["p"] : $defaultvalue;
if(($p != 'index') && ($p != 'reg') && ($p != 'login') && ($p != 'ad')):
?>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Java JPA implementation - how are properties read/set? I am reading the Beginning Java EE6 Platform and Glassfish 3 book and I have some minor difficulties at understanding Access type on field/properties. What is the difference between the two of them?
Is it how the properties are read/set by the JPA implementation (in this case EclipseLink)? Like, if it is property access the values are read/set through possible validations etc that can be placed in the get/set method, while the field access option does not do setting/getting values through these methods but straight on the fields? And does the type get set by where I am placing the @Id annotation?
A: The @Access annotation type indicates how the JPA should set or get the field in your object. An AccessType.FIELD the JPA will set the field directly with reflection and will not use any provided setter method., very useful if your class tracks the "dirtyness" of a field through the setter methods. In contrast setting @Access(value=AccessType.PROPERTY) will instruct the JPA to use the setter and getter methods when it accesses fields.
You can prove this to yourself by adding logging or System.out.printlns to your setter methods and then making changes to the @Access annotation. For example:
@Id
@Access(value=AccessType.PROPERTY)
private Long Id;
public void setId(Long id) { System.out.println("SET"); this.Id = id; }
Will print SET and this:
@Id
@Access(value=AccessType.FIELD)
private Long Id;
public void setId(Long id) { System.out.println("SET"); this.Id = id; }
Will NOT!
It also does not matter where you place the annotations, at least in Hibernate ;-).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Why text on SWC doesn't show up when imported from FlashDevelop? I created many SWCs with graphics and code for my project so that the compiling time has a really better performance. I just found a problem, tough.
One of the SWCs is a 'text container'. It is just a set of graphics with a dynamic text field in it. When I import the SWC from Flash CS5.5 apps, it behaves normally. I mean:
var swcInstance:SwcClass = new SwcClass
swcInstance.textFiel.text = "hello world!"
addChild(swcInstance)
and the swcInstance object is shown on screen with the text in it. When I do the same on FlashDevelop, tough, it appears on screen but text is not shown. Is this a known bug? Am I doing something wrong?
EDIT:
I'm using Impact font with a drop shadow filter. Also, I made another test and Static text fields work properly.
EDIT 2:
The same problem happens partially with Arial. Some letters don't show up but others do. When I embed "All", it works fine with Arial. But even when I embed "All" with Impact it refuses to work, anything shows up.
A: Set the embedAsCFF parameter to false
Unless the SWF file was compiled with CFF, you must set the value of
the embedAsCFF property to false for the imported font.
Read more about that here: http://help.adobe.com/en_US/flex/using/WS2db454920e96a9e51e63e3d11c0bf6320a-7fec.html
And here:
http://www.flashdevelop.org/community/viewtopic.php?f=13&t=6456
A: To me it sounds like you may have these fonts included in other SWCs - if these SWCs are included first by the compiler the font they contain may hide other SWCs' fonts.
You could try un-adding all SWCs of your project, then adding them back starting with those with complete fonts.
PS: don't "embed all" chars of a font, choose the appropriate charsets - typically "Basic Latin" (US) and "Latin 1" (accented characters).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547713",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Debug.WriteLine to different "channel"? http://i.minus.com/ibsHfIOAy7lBCj.png
I want to write some stuff to VS's output window so I can see what's going on, but it just gets flooded with all this other stuff. Is there some way I can write to a different "channel"? It's got that dropdown there, which I see AnkhSVN has added itself too...can I add another one with only my stuff in there maybe?
A: Use Trace for this. You will either have an App.config file or a Web.config file in the project that is running. In this file add a trace listener.
When you call trace, which is very similar to Debug, you can specify the level (Info, Warning, Debug, Error). Based on this level you can decide where and how that information is saved.
How to Trace and Debug in Visual Studio
A: You can use the "Redirect all Output Window text to the Immediate Window" option:
Although it says all, it will only redirect Debug.WriteLine, etc.
Alternatively you can suppress the noisy messages from the output window itself:
A: If you create a visual studio addin (in default) you will have a connect.cs with a public void OnConnection(object application, ext_ConnectMode connectMode, object addInInst, ref Array custom)
You can use this application object to do what you want to do.
DTE2 app = (DTE2)application;
OutputWindowPane XXX = app.ToolWindows.OutputWindow.OutputWindowPanes.Add("XXX");
Now you can use :
XXX.OutputString("some text" + Environment.NewLine);
And this text will appear in the "channel" called "XXX"
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547714",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Django recursive imports I have two apps: pt and tasks.
pt.models has a Member model.
tasks.models has a Filters model.
Member model has a foreign key to Filters model (one for a member).
Filters has M2M field to Member as it holds some kind of filtering settings.
So, I must recursively import both models to get everything synced what is impossible in Python.
Any ideas?
A: Again, circular imports are not an error in Python, only using names that don't yet exist when doing so.
From the docs:
If you need to create a relationship on a model that has not yet been defined, you can use the name of the model, rather than the model object itself...
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Creating an array while passing it as an argument in Java Is there a way to create an array of objects as part of a constructor or method? I'm really not sure how to word this, so I've included an example. I have an enum, and one of the fields is an array of numbers. Here is what I tried:
public enum KeyboardStuff {
QWERTY(1, {0.5f, 1.3f, 23.1f}, 6);
DVORAK(5, {0.1f, 0.2f, 4.3f, 1.1f}, 91);
CHEROKEE(2, {22.0f}, 11);
private int number, thingy;
private float[] theArray;
private KeyboardStuff(int i, float[] anArray, int j) {
// do things
}
}
The compiler says that the brackets { } are invalid and should be removed. Is there a way I can pass an array as an argument without creating an array of objects beforehand?
A: Following @Dave's suggest I would use a vararg
QWERTY(1, 6, 0.5, 1.3, 23.1);
DVORAK(5, 91, 0.1, 0.2, 4.3, 1.1);
CHEROKEE(2, 11, 22.0);
private final int number, thingy;
private final double[] theArray;
private KeyboardStuff(int number, int thingy, double... theArray) {
// do things
}
It is pretty rare that using a float is better than using a double. double has less rounding error and only uses 4 more bytes.
A: You can try with new float[] { ... }.
public enum KeyboardStuff {
QWERTY(1, new float[] {0.5f, 1.3f, 23.1f}, 6);
DVORAK(5, new float[] {0.1f, 0.2f, 4.3f, 1.1f}, 91);
CHEROKEE(2, new float[] {22.0f}, 11);
private int number, thingy;
private float[] theArray;
private KeyboardStuff(int i, float[] anArray, int j) {
// do things
}
}
A: Is there a way you can pass an array without creating an array?
No, but you could use varargs to make it mostly-invisible, although that int at the end might need to move.
A: If using Lists's instead of arrays is an option, future versions of Java might start supporting a 'collection literals' syntax which unfortunately doesn't seem to have made it into Java 8:
public enum KeyboardStuff {
QWERTY(1, [0.5f, 1.3f, 23.1f], 6);
DVORAK(5, [0.1f, 0.2f, 4.3f, 1.1f], 91);
CHEROKEE(2, [22.0f], 11);
private int number, thingy;
private List<Float> values;
private KeyboardStuff(int i, List<Float> values, int j) {
// do things
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547722",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "18"
} |
Q: MySQL find the mode of multiple subsets I have a database like this:
custNum date purchase dayOfWeek
333 2001-01-01 23.23 1
333 2001-03-04 34.56 5
345 2008-02-02 22.55 3
345 2008-04-05 12.35 6
... ... ... ...
I'm trying to get the mode (most frequently occuring value) for the dayOfWeek column for each customer. Basically it would be the day of the week each customer shops the most on. Like:
custNum max(count(dayofweek(date)))
333 5
345 3
356 2
388 7
... ...
Any help would be great thanks.
A: select custNum, dayOfWeek
from tableName t
group by custNum, dayOfWeek
having dayOfWeek = (
select dayOfWeek
from tableName
where custNum = t.custNum
group by dayOfWeek
order by count(*) desc, dayOfWeek
limit 1
)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547723",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Re-size a bitmap using "Nearest Neighbor" in .net I have some low detail images I'm rendering to the screen. I'm using a bitmap as a buffer. Is there a way to re-size the bitmap (using "Nearest Neighbor") in .net?
I'm using VB.net so all .net solutions are acceptable.
A: A simple Winforms example that draws a scaled image added as a resource with the name "SmallImage" with nearest neighbor interpolation:
Public Class Form1
Public Sub New()
InitializeComponent()
Me.SetStyle(ControlStyles.ResizeRedraw, True)
Me.DoubleBuffered = True
Me.bmp = My.Resources.SmallImage
End Sub
Protected Overrides Sub OnPaint(ByVal e As System.Windows.Forms.PaintEventArgs)
e.Graphics.InterpolationMode = Drawing2D.InterpolationMode.NearestNeighbor
e.Graphics.PixelOffsetMode = Drawing2D.PixelOffsetMode.Half
Dim h = Me.ClientSize.Width * bmp.Height / bmp.Width
e.Graphics.DrawImage(bmp, New Rectangle(0, 0, Me.ClientSize.Width, h))
End Sub
Private bmp As Bitmap
End Class
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547725",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Automatic checking of jstl fmt:messages? Is there any automatic way to check that all referenced messages in my jstl are, in fact, provided in a properties file?
Of course I always add in translations as I make references to them, but I'm mainly concerned about the rare instance where I forget one, or have a typo in either the fmt:messages tag or the properties file; if it is a message that isn't displayed often (e.g. an unusual error message), then I may not realize it until someone gets the error with a ???errormessagename??? which is no good!)
A: You should always have a default property.
With that you will avoid ???Property_Key??? messages.
But I recently had the same need.
I've made a Excel sheet with automatic merging.
The way I did it is:
*
*Past the first property file content on a first sheet
*Same for second on an other sheet
*Create a macro parsing each lines, with making a split on the "=" the identify the key.
*Put the key of sheet1 on a third sheet
*Parsing sheet2 and try to match with keys in sheet3
*iF no matches, there is a translation mission, put key in a fourth sheet.
I know it's not a perfect tool, but it's realy helpfull.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: how to switch between layout at runtime in android? i have four images in a row at the top , on click of each icon i want to change the underlaying background (image) and the controls on the layout , this way it achieves tab like structure and behavior , i want to know whats the best way to achieve this ? I think i will have four layouts each layout having one image highlighted showing that tab selected and corresponding components on layout, and will change this layout when user clicks on image.
Is this a good idea to achieve this ? or i have different solution available ?
its nice if u give me some idea about necessary features or API or layout component related code
Suggestions are welcome thanks!
A: That is not a good idea. You should use android's tab architecture. Here is a example at developer.android
A: you can change layouts by switching views to invisible and visible. but it's not a good idea when you want to change 4 layouts.
*
*It becomes hard to maintain the code if you have 4 layouts switching.
*It's better to use Tabs which will help you in preserving the state of the each layout.
*Customize the tabWidget to make it look like you have 4 buttons on the top, not the tabs.
HTH.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Rails: Convert string to variable (to store a value) I have a parameter hash that contains different variable and name pairs such as:
param_hash = {"system_used"=>"metric", "person_height_feet"=>"5"}
I also have an object CalculationValidator that is not an ActiveRecord but a ActiveModel::Validations. The Object validates different types of input from forms. Thus it does not have a specific set of variables.
I want to create an Object to validate it like this:
validator = CalculationValidator.new()
validator.system_used = "metric"
validator.person_height_feet = 5
validator.valid?
my problem right now is that I really would not prefer to code each CalculationValidator manually but rather use the information in the Hash. The information is all there so what I would like to do is something like this, where MAKE_INTO_VARIABLE() is the functionality I am looking for.
validator = CalculationValidator.new()
param_hash.each do |param_pair|
["validator.", param_pair[0]].join.MAKE_INTO_VARIABLE() = param_pair[1]
# thus creating
# "validator.system_used".MAKE_INTO_VARIABLE() = "metric"
# while wanting: validator.system_used = "metric"
# ...and in the next loop
# "validator.person_height_feet".MAKE_INTO_VARIABLE() = 5
# while wanting: validator.person_height_feet = 5
end
validator.valid?
Problem:
Basically my problem is, how do I make the string "validator.person_height" into the variable validator.person_height that I can use to store the number 5?
Additionally, it is very important that the values of param_pair[1] are stored as their real formats (integer, string etc) since they will be validated.
I have tried .send() and instance_variable_set but I am not sure if they will do the trick.
A: Something like this might work for you:
param_hash.each do |param, val|
validator.instance_eval("def #{param}; @#{param} end")
validator.instance_variable_set("@#{param}", val)
end
However, you might notice there's no casting or anything here. You'd need to communicate what type of value each is somehow, as it can't be assumed that "5" is supposed to be an integer, for example.
And of course I probably don't have to mention, eval'ing input that comes in from a form isn't exactly the safest thing in the world, so you'd have to think about how you want to handle this.
A: Have you looked at eval. As long as you can trust the inputs it should be ok to use.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547729",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: codeigniter $this->db->where(); custom string problem Im trying to select some values using a custom string. below is my code
$this->db->from('posted');
$st="infor='rent' AND (typeq='in' OR typeq='out')";
$this->db->where($st);
$q = $this->db->get();
A Database Error Occurred
Error Number: 1054
Unknown column ‘infor=‘rent’’ in ‘where clause’
SELECT * FROM (`posted_ads`) WHERE `infor=‘rent’` AND (typeq=‘in’
OR typeq=‘out’)
Filename: C:\wamp\www\parklot\system\database\DB_driver.php
Line Number: 330
i think the problem is coz of
WHERE `infor='rent'`
when i manualy execute this code it works perfectly.
WHERE infor='rent'
how do i get rid of
``
because its automatically added
A: Add a third parameter to the where() and set it to FALSE
$this->db->from('posted');
$st="infor='rent' AND (typeq='in' OR typeq='out')";
$this->db->where($st, NULL, FALSE);
$q = $this->db->get();
$this->db->where() accepts an optional third parameter. If you set it to FALSE, CodeIgniter will not try to protect your field or table names with backticks.
CodeIgniter Documentation
A: While the solution works I wanna add: Be careful! You need to secure your query and escape all values! If you like to use the Query Builder
$q = $this->db->select('*')->from('posted_ads')
->where('infor', 'rent')
->or_group_start()
->where('typeq', 'in')
->where('typeq', 'out')
->group_end()
->get();
This way Codeigniter takes care of proper escaping.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: BlackBerry - Set HTTP Proxy for connection I would like to set a HttpProxy for a subsequent HttpConnection on Blackberry.
In Android I would do something like:
HttpHost proxy = new HttpHost(PROXY_IP, PROXY_PORT);
httpclient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY,
proxy);
What is the equivalent on Blackberry?
A: Unfortunately, there isn't an API for this on BlackBerry.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547732",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Memory accesses in MIPS We're studying for our midterm in Computer Organization and Design on Tuesday, and none of us understand the following question:
procedure:
addi $sp, $sp, -4
sw $ra, 0($sp)
... Some unknown work is done ...
addi $sp, $sp, 4
lw $ra, -4($sp)
jr $ra
(1-H) Again consider the above code, and assume it works. If, during execution, the ’unknown
work’ section causes 100 words to be read from memory, how many words will be read from
memory during the execution of the entire procedure? (Consider all memory accesses.
Here is the answer: 106. 100 memory reads for the unknown work, plus 5 memory reads to read the instructions shown, plus 1 memory read during the "lw" instruction.
If anyone could help us understand exactly where each of these 6 memory reads occur, it would be greatly appreciated!
A: Let's start with the obvious ones: 100 reads are performed in the "unknown work" section, that leaves 6 reads. One read is for the lw instruction (lw $ra, -4($sp)), which reads a words from memory. The final 5 reads are implicitly done by the CPU in the Instruction fetch stage.
addi $sp, $sp, -4 # 1 read (CPU reads the instruction word)
sw $ra, 0($sp) # 1 read -------------- ## --------------
... Some unknown work is done ... # 100 reads (given in question)
addi $sp, $sp, 4 # 1 read (CPU reads the instruction word)
lw $ra, -4($sp) # 2 reads (CPU reads the instruction word, lw instruction also reads)
jr $ra # 1 read (CPU reads the instruction word)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547739",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Scala: Contains in mutable and immutable sets I've discovered a strange behavior for mutable sets which I cannot understand:
I have a object which I want to add to a set. The equals method for the class is overridden. When I add two different objects to the set, which produces the same output for equals method, I get a different behavior between mutable and immutable sets for the contains method.
Here is the code snippet:
class Test(text:String){
override def equals(obj:Any) = obj match {
case t: Test => if (t.text == this.text) true else false
case _ => false
}
override def toString = text
}
val mutableSet:scala.collection.mutable.Set[Test] = scala.collection.mutable.Set.empty
mutableSet += new Test("test")
println(mutableSet)
println(mutableSet.contains(new Test("test")))
val immutableSet:scala.collection.immutable.Set[Test] = scala.collection.immutable.Set.empty
immutableSet += new Test("test")
println(immutableSet)
println(immutableSet.contains(new Test("test")))
This produces as output:
Set(test)
false
Set(test)
true
In my opinion both calls of contains should produce the same output (true).
Could anybody help me to understand the difference here or is this a bug in the scala immutable set implementation? By the way, I use scala 2.8.1.final
Thanks.
A: You need to override hashCode as well. hashCode is essential to override when you override equals.
Note there were also a few things that didn't compile, so I edited a bit more:
class Test(val text:String){ // added val
override def equals(obj:Any) = obj match {
case t: Test => if (t.text == this.text) true else false
case _ => false
}
override def toString = text
override def hashCode = text.hashCode
}
val mutableSet:scala.collection.mutable.Set[Test] = scala.collection.mutable.Set.empty
mutableSet += new Test("test")
println(mutableSet)
println(mutableSet.contains(new Test("test")))
val immutableSet:scala.collection.immutable.Set[Test] = scala.collection.immutable.Set.empty
val immutableSet2 = immutableSet + new Test("test") // reassignment to val
println(immutableSet2)
println(immutableSet2.contains(new Test("test")))
I recommend reading http://www.artima.com/pins1ed/object-equality.html for a lot more insights on doing object equality. It's eye opening.
A: Rule 1 when implementing equals(): Implement hashCode() at the same time. See Overriding equals and hashCode in Java
In the first example, you're creating a mutable set, which calls hashCode to set up the hash table.
In the second, you're using an immutable set with one entry, so Scala actually uses an optimised version of Set called Set1. Set1.contains() just compares the one entry with the passed element using equals() directly. This looks like:
/** An optimized representation for immutable sets of size 1 */
@SerialVersionUID(1233385750652442003L)
class Set1[A] private[collection] (elem1: A) extends Set[A] with Serializable {
override def size: Int = 1
def contains(elem: A): Boolean =
elem == elem1
def + (elem: A): Set[A] =
if (contains(elem)) this
else new Set2(elem1, elem)
def - (elem: A): Set[A] =
if (elem == elem1) Set.empty
else this
def iterator: Iterator[A] =
Iterator(elem1)
override def foreach[U](f: A => U): Unit = {
f(elem1)
}
}
No hashCode is called. There is also a Set2, Set3 and Set4.
So if we change your code to be:
class Test(val text:String){
override def equals(obj:Any) = {
println("equals=" + obj)
obj match {
case t: Test => if (t.text == this.text) true else false
case _ => false
}}
override def hashCode(): Int = {
println("hashCode=" + super.hashCode())
super.hashCode()
}
override def toString = text
}
println("mutable")
val mutableSet:scala.collection.mutable.Set[Test] = scala.collection.mutable.Set.empty
mutableSet += new Test("test")
println("mutableSet=" + mutableSet + " contains=" + mutableSet.contains(new Test("test")))
println("immutable")
var immutableSet:scala.collection.immutable.Set[Test] = scala.collection.immutable.Set.empty
immutableSet += new Test("test")
println("immutableSet=" + immutableSet + " contains=" + immutableSet.contains(new Test("test")))
adding a hashCode and a println in the equals, and the output is:
mutable
hashCode=30936685
hashCode=26956691
mutableSet=Set(test) contains=false
immutable
equals=test
immutableSet=Set(test) contains=true
which explains why the mutable.contains() isn't working correctly. It is looking up the object in the wrong hash table entry, equals() doesn't even get called. And, unsurprisingly, it doesn't find it.
You can implement hashCode using text.hashCode:
override def hashCode: Int = text.hashCode
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
} |
Q: UITouch equivalent for Mac I'm writing a Mac game using Cocos2D-iPhone, and need to get a click event. Is there an equivalent to UITouch for the Mac platform?
A: You need to look at both NSEvent and NSTouch - which isn't an exact match for UITouch, although close.
A: Kobold2D (improved Cocos2D version) has a simple user input API: KKInput (Class Reference). With that you can simply call at any time in any class or method:
[[KKInput sharedInput] isMouseButtonDown:kKKMouseButtonLeft];
KKInput offers the same convenient way to test for keyboard input, to get accelerometer (including filtering), gyroscope and device motion (attitude) values, and the current touches. It also supports Gesture Recognizers starting with Kobold2D Preview 5.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Changes to UIView before transitionWithView animation are ignored I have an UIView that contains two UIImageView (one is a cartoon, the other one its special shadow). "self" is the UIView object.
On tap I want to remove the UIView from its superview via a curl effect. This works very fine.
But before it is curled up, I want to remove my custom made shadow UIImageView, so that my shadow doesn't curl together with the curl effect shadow. Removing the UIImageView from the UIView right BEFORE the animation just does not work.
My code:
[myShadow setImage:nil];
[UIView transitionWithView:self duration:1.0
options:UIViewAnimationOptionTransitionCurlUp
animations:^ { [self setHidden:YES];}
completion:nil];
This doesn't remove myShadow. When I comment out the transitionWithView myShadow is removed just fine, but - of course- there is no animation following.
With the animation following the setImage:nil doesn't show any effect. I also tried [myShadow removeFromSuperview] and [myShadow release], also didn't do anything.
I was trying a lot of things and googling for over 3 hours. For example I tried
[self setNeedsDisplay];
or
animations:^ { [myShadow setImage:nil]; [self setHidden:YES];}
I played with this, but didn't get myShadow to disappear before the animation.
What can I do? Thank you.
A: I would try this when removing the shadow:
[ CATransaction begin ];
[ CATransaction setValue: [ NSNumber numberWithBool: YES ]
forKey: kCATransactionDisableActions ];
[ myShadow setImage: nil ];
[ CATransaction commit ];
[ UIView transitionWithView: self
duration: 1.0
options: UIViewAnimationOptionTransitionCurlUp
animations: ^ { [ self setHidden: YES ]; }
completion: nil ];
That should avoid any issue with the shadow animating away while the transition is happening. If that still does not work then you could try to add this after setting the shadow image to nil:
[ self displayIfNeeded ];
This is instead of [ self setNeedsDisplay ]. setNeedsDisplay does not cause anything to happen immediately but rather just marks the view as needing display, which will happen later. displayIfNeeded will cause the view to draw immediately.
It it possible that just changing setNeedsDisplay to displayIfNeeded will be all you need to do.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547747",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: smalltalk block - can I explicitly set the returning value and stop executing the block? The return value of #value: message, when sent to a block, is the value of the last sentence in that block. So [ 1 + 2. 3 + 4. ] value evaluates to 7.
I find that hard to use sometimes. Is there a way to explicitly set the returning value and stop executing the block?
For exercise, try rewriting this block without using my imaginary #return: message and see how ugly it gets. I must be missing something.
[ :one :two |
one isNil ifTrue: [ two isNil ifTrue: [ self return: nil ] ifFalse: [ self return: true ] ].
two ifNil: [ self return: false ].
(one > two)
ifTrue: [ self return: true ]
ifFalse: [ (one < two)
ifTrue: [ self return: false ]
ifFalse: [ self return: nil ]
].
]
EDIT: self return: sth really is nonsense, but it does make sense at some level :)
A: There's nothing like a guard clause - blah ifTrue: [^ foo] - inside a block, because ^ is a non-local return, returning from the method calling the block rather than the block itself.
Big blocks - like big anythings - should be refactored into smaller, more understandable/tractable subparts, but sometimes that's not always possible. I mean this answer to suggest options to try when you can't really simplify in the usual ways.
If your block is really that complicated, and you can't get it simpler (splitting it up delocalises the information too much, for instance) then perhaps you can use an explicit return value. In particular, if your block doesn't return nil you could do something like
[:one :two | | result |
result := (one isNil and: [two isNil]) ifTrue: [false].
result ifNil: ["do one thing, possibly setting result"].
result]
If your block can return nil, you'll need another sentinel value:
[:one :two | | result marker |
result := marker := Object new.
(result == marker) ifTrue: ["do one thing, possibly setting result"].
result]
Lastly - and I hesitate to suggest this - you could do this:
[1 + 2.
thisContext return: 5.
3 + 4] value
which returns 5.
(Verifying how this interacts with ^ and inlined selectors like #ifTrue:ifFalse: left as an exercise for the reader.)
A: It seems that your code tries to handles nil like an infinity value when comparing one and two. The following code may be more readable depending on the context:
a := [:one :two |
| x y |
x := one ifNil: [Float infinity].
y := two ifNil: [Float infinity].
(x = y) ifTrue: [nil] ifFalse: [x > y]]
A useful feature of #ifTrue:ifFalse:, #ifNil:ifNotNil: and similar testing methods is that they return the value of the block that gets evaluated. e.g. (4 > 1) ifTrue: ['greater'] ifFalse: ['not-greater'] evaluates to 'greater'. This feature often makes it possible to return a value from a nested block in tail position.
When the code inside a block gets too complicated I suggest your refactor it to a method. But see Frank's answer for workarounds.
Edit:
As pointed out in the comments the code above assumes numbers. I also came up with something that works with other comparable objects:
a:=
[ :one :two |
true caseOf: {
[one = two]->[nil].
[one isNil]->[true].
[two isNil]->[false]
} otherwise: [one>two]]
That #caseOf: construct is rarely used but it's certainly better than thisContext return:
A: You'd like to implement some break, continue, exit...
The usual way to control flow in Smalltalk is with blocks.
So one funny solution is to use a helper method with a Block return value to break the flow, like described here .
Object>>exitThru: aBlock
^aBlock value: [:result | ^result]
Now, let see how to use it:
| aBlock |
aBlock := [ :one :two |
self exitThru: [:exit |
one isNil ifTrue: [ two isNil ifTrue: [exit value: nil ] ifFalse: [ exit value: true ] ].
two isNil ifTrue: [ exit value: false ].
one > two ifTrue: [ exit value: true ].
one < two ifTrue: [ exit value: false ].
exit value: nil] ].
#(('abc' nil) (nil nil) (nil 'def') ('y' 'abc') ('y' 'y') ('y' 'z'))
collect:
[:pair |
aBlock value: pair first value: pair last ]
-> #(false nil true true nil false)
EDIT my first version was unnecessarily complex, can't remember what lead me to an additional indirection:
| aBlock |
aBlock := [:wrapOne :wrapTwo |
self exitThru: [:exit |
[ :one :two |
one isNil ifTrue: [ two isNil ifTrue: [exit value: nil ] ifFalse: [ exit value: true ] ].
two isNil ifTrue: [ exit value: false ].
one > two ifTrue: [ exit value: true ].
one < two ifTrue: [ exit value: false ].
exit value: nil ]
value: wrapOne value: wrapTwo ] ].
Well, more funny than usefull, I hope you will find more simple and expressive way to code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How can I stop the Clicking function While it is finish Animation? I need to know how can I stop the clicking function while it finishing the Animation
here is my code
$(function () {
$('legend').click(function () {
$(this).parent().find('.content').slideToggle("slow");
});
});
A: Change your selector slightly to exclude :animated elements using :not:
$(function () {
$('legend').click(function () {
$(this).parent().find('.content:not(:animated)').slideToggle('slow');
});
});
Working example: http://jsfiddle.net/andrewwhitaker/acKtG/
A: Here you go. Simply check for an 'animating' bool flag. During animation, return out of the click event, else set the flag and animate, then reset the flag on the animation complete callback:
$(function () {
$('legend').click(function () {
if($(this).data('animating') !== true) {
$(this).data('animating',true);
$(this).parent().find('.content').slideToggle("slow", function(){$(this).data('animating',false);});
}
else {
return false;
}
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547751",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
} |
Q: rails partial's layouts with named yield - why is yield block never used? I have a partial, with a layout:
<%= render :partial => 'home/mobile/home', :layout => 'home/mobile/page', :locals => {:page => 'abc2'}%>
The layout (page.html.erb) has yields for different blocks, such as:
<div data-role="header">
<%= yield :header %>
</div>
However, this yield block is never used, while the main-level layout file does yield as one would expect.
Is it impossible to use named content_for/yield blocks with the layouts of partials? Are there workarounds?
I would expect inheritance-- content_for :header should first look for a yield :header in the partial's layout, and failing that, the main layout file. But this is not the case. The partial layout's yield :header is simply ignored.
A: In a situation similar to yours, I replaced the yield with a call to content_for without a block. So in your example it would be simply:
<div data-role="header">
<%= content_for :header %>
</div>
That worked for me. That yields in partials don't trickle up as you suggest may be a feature or a bug - but that's still appear to be how it works in Rails 4.1.8, 3 years down the line :)
A: The workaround would be to wrap your layout into an helper method using blocks (which should be able to yield correctly).
You may want to fil a bug about the original problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547753",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
} |
Q: Form Invoke causes strange Exception I have the following method inside a Form
public void Bye()
{
if (InvokeRequired && IsHandleCreated)
{
Invoke(new Action(Bye));
return;
}
Close();
}
This form is created in the main form's thread, but this method is called from a System.Threading.Timer callback. The timer is created in the Main method, before calling Application.Run.
My application has many of these forms with the Bye method. The timer calls the Bye method of a random form each second.
If I keep the application running for a few minutes, I get an exception at the Invoke call.
The exception message is
Invoke or BeginInvoke cannot be called on a control until the window handle has been created.
The strange thing is that when the exception occurs, Visual Studio tells me that
both InvokeRequired and IsHandleCreated are false. How could it even try to call Invoke in this case?
What am I missing?
A: Change the order:
if (IsHandleCreated && InvokeRequired)
Regarding VS debugger: it may evaluate both properties to display their results in the Watch window, and at this point they may return false.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7547755",
"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.