text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Execute Javascript *after* ajax update I need to execute a certain javascript function after the ajax update has been applied. I tried jsf.ajax.addOnEvent(ch.ergon.newom.ajaxUpdate) to
get informed about the request, but that seems to be execute after the ajax response arrived, but before it got applied (that is: the content got updated).
How can I execute a JavaScript function after the content got updated by JSF-ajax?
A: Actually, this will be called three times. One before the ajax request is sent, one after the ajax response is arrived and one when the ajax response is successfully processed. You need to check the current status based on the provided data argument. You can find technical details in tables 14-4 and 14-3 of the JSF 2.0 specification.
Here's a kickoff example of how your JS function should look like when you'd like to hook on all 3 of the statuses.
function ajaxUpdate(data) {
var ajaxStatus = data.status; // Can be 'begin', 'complete' and 'success'.
switch (ajaxStatus) {
case 'begin': // This is called right before ajax request is been sent.
// ...
break;
case 'complete': // This is called right after ajax response is received.
// ...
break;
case 'success': // This is called when ajax response is successfully processed.
// ...
break;
}
}
Or when you'd like to hook on the success status only:
function ajaxUpdate(data) {
if (data.status == 'success') {
// ...
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566059",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Hide the a saved password from the source I have a login form and an option to remember the password. The password is encrypted in a cookie on the users computer. At the moment it is decrypted and placed in the password field. This isn't that flash as you merely view the source to see the users password.
Whats the best way to secure the password from the source?
A: Don't do that. ANY secure implementation of a login form will not make the password readble EVER.
You have two options:
*
*Use the cookie to log-in the user automatically. Very convenient, that's what most people want to have.
*Let the user save his password in the text field. Every browser can do that in a more or less secure way and skip the cookie.
Let me say it again: Displaying the clear text password in the code is a security risk. However, you knowing the user's password or being able to recreate it (symmetric encryption instead of hashing - what you should use) is a complicated thing, since I mistrust every website which knows my password in clear or stores it anywhere unhashed.
So, you'd go with taking the password from the user at registration time, hash it and store it in the database or whereever you like. Then, take the cookie to remember the user (means the identity, not the credentials to verify that identity).
A: *
*Don't have an option to remember the password. Browsers can do that on their own, securely. Instead, use an option to keep the user logged in. In that case, you set a cookie to maintain the user's session between server sessions that's based on a session token (usually including an encrypted username), not a password.
*You should never be able to decrypt a user's password to readable plain text. Use hashing instead of encryption. Instead of sending plain text to the server, you can hash the password on the client-side with an algorithm like SHA1. A lot of apps skip this first step, but it's preferable never to even transmit the password in clear text. Then, on the server side, hash the "password hash" again with an algorithm like HMAC-SHA1, using dynamic salt as a key. You should use different, random salt for each user's password. That way, even if two users have the same password, the salt ensures each password is saved differently. You store the password and the salt in your database for each user, so it can be used again when comparing to the user's password on each login.
*Whether you store a session token that includes a username, or a user's password (which should only be a hash of the password, and is still inadvisable) in the cookie, you should encrypt the cookie (as you state you already have) and decrypt the cookie on the server side, not the client side. If you decrypt client side, then you've given away the algorithm and key to do so, which would make the encryption a pointless exercise. Additionally, if you decrypt server side and then send the password back down the pipe to preload your login form, you expose the user's password during transmission to the browser, and do so again when they resubmit the login form from the browser.
*When the user makes the first request after returning to your site, you will get the cookie in the HTTP header, so if you use a session token instead of a password, you can immediately decrypt the cookie, verify the session token is still valid, log the user in, and take the user to a content page. This is what every site that allows a persistent session cookie does.
*If you store the password in a cookie, I assume you're also storing the username, or sending the username from the server to the browser. When you then preload the username and password in your login form in clear text, you give a thief credentials to use on your site and potentially others. You leak information about the user. If you store a session token in the cookie (which contains a username and an expiration timestamp instead of a password), and only decrypt the token on the server, then you haven't leaked any user information. Additionally, you can use an HttpOnly cookie as your client script doesn't need to read the cookie.
From your perspective, both methods accomplish essentially the same thing for your users, but an encrypted session token that includes only the username poses far fewer risks for the user than a password that is stored (encrypted or not) and/or decrypted to preload your login form.
To create a session token, create a cookie and add the username and your choice of an issue date and/or an expiration date. If you set the issue date, then you can always calculate the expiration date based on your current expiration policy on the server. If your policy changes, then it always applies to old tokens as well. If you only set the expiration date and verify the current date is less than the expiration date, then you are using whatever expiration duration policy you thought up at the time you stored the cookie. Session tokens often include the following:
*
*Username - so it's specific to a user account you can verify
*Issue Date - the current timestamp
*Expiration Date - current timestamp + expiration window
*Persistent - A property indicating whether the cookie should stay persistent or expire at the end of the current server session
*Any custom data (sans any passwords)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: find optional middle of string surrounded by lazy, regex I'm using python and regex to try to extract the optional middle of a string.
>>> re.search(r'(.*?)(HELLO|BYE)?(.*?END)', r'qweHELLOsdfsEND').groups()
('', None, 'qweHELLOsdfsEND') #what I want is ('qwe', 'HELLO', 'sdfsEND')
>>> re.search(r'(.*?)(HELLO|BYE)?(.*?END)', r'qweBLAHsdfsEND').groups()
('', None, 'qweBLAHsdfsEND') #when the middle doesn't match. this is OK
How can I extract the optional middle?
Note: This is my first post.
A: Your regex fails because the first part is happy with matching the empty string, the second part fails (which is OK since it's optional), so the third part captures all. Solution: Make the first part match anything up to HELLO or END:
>>> re.search(r'((?:(?!HELLO|BYE).)*)(HELLO|BYE)?(.*?END)', r'qweHELLOsdfsEND').groups()
('qwe', 'HELLO', 'sdfsEND')
>>> re.search(r'((?:(?!HELLO|BYE).)*)(HELLO|BYE)?(.*?END)', r'qweBLAHsdfsEND').groups()
('qweBLAHsdfs', None, 'END')
Is that acceptable?
Explanation:
(?: # Try to match the following:
(?! # First assert that it's impossible to match
HELLO|BYE # HELLO or BYE
) # at this point in the string.
. # If so, match any character.
)* # Do this any number of times.
A: You can do it like this:
try:
re.search(r'(.*?)(HELLO|BYE)(.*?END)', r'qweHELLOsdfsEND').groups()
except AttributeError:
print 'no match'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566067",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Vim: brace matching unreliable I'm using Vim to edit JSP files with JavaScript. Somehow the % key (jump to matching brace) doesn't work most of the time: Sometimes it works, sometimes it works only in one direction, but most of the time it doesn't work at all. Of course Vim is able to highlight the right matching brace, but matchit.vim doesn't seem to find it. I'm using the latest version (1.13.2) of the plugin.
Example:
<s:layout-component name="extra_styles">
@import "${mediaPath}/css/whatever.css";
.test .someclassname {
top: 5px;
left: 32px;
}
</s:layout-component>
Here it won't find the matching curly brace.
Does anyone know a solution for this?
A: I had the same problem: % wouldn't jump to matching {}. This is my workaround:
:let b:match_debug=1
% starts dancing after that.
Hope it helps.
A: I think it has something to do with the JSP syntax definition: I changed the filetype on your example to css: matchit jumps correctly from one curly brace to the other. Changing the filetype back to jsp makes matchit all dizzy.
:set ft=css.jsp seems to allow both the correct matchit behaviour and CSS omni-completion. See if it doesn't break anything on the jsp front.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566069",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Check whether a path is absolute or relative How do you check whether a path is absolute or relative, using C on Linux?
A: It's absolute if it begins with a /, otherwise relative.
A: Check if the path starts with / or not. if path starts with / you can assume it is absolute.
A: Check if the path starts with / or not. if path starts with / you can assume it is absolute otherwise it's relative means it will update from pwd(present working directory)
But in Absolute case path will update relative to root directory
A: Absolute paths tend to start with the / character. Anything else is pretty much relative from the working directory.
Even directories with .. sequences in them are considered absolute if they start with / since they end up at the same position in the file system (unless you change links and things but that's beyond the discussion of absolute and relative).
A: On Unix like systems (incl. Linux, macOS)
If it starts with a slash it's absolute, otherwise it's relative.
That is because everything is part of a single tree starting at the root (/) and file systems are mounted somewhere in this tree.
On Windows
Windows uses backslashes (though slashes are also supported these days) and drive letters. But it's bit more complex:
*
*A path starting with a drive letter followed by a colon not followed by a backslash (or slash) can be relative to that drive's current directory.
*A path starting with a backslash (or slash) is absolute but on the current drive, so in that sense it is in fact relative (to the top of the current drive).
*A path starting with 2 backslashes is an UNC path (pointing to a network location) which is always absolute, except when the path starts with \\?\ which is a special case to support longer paths.
So on Windows it's best to use the PathIsRelative() (PathIsRelativeA/PathIsRelativeW) function to determine if the path is relative or not.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: 2 submit buttons I have a webpage which has 2 submit buttons.
How do I post a value to another page based on the button clicked.
Lets say the 2 buttons on the form are yes and no. If the yes button is clicked, I want to post the value 1, if the no button is clicked, I want to post the value 0.
Does anyone know how to do this?
It does not have to post 1 and 0, it can post any value, as long as the page being posted to knows which option was selected.
A: <input type="submit" name="thisismysubmitbutton" value="yes" />
<input type="submit" name="thisismysubmitbutton" value="no" />
One displays and posts the value yes, the other displays and posts the value of no. Note that the input element needs to have a valid name attribute, else the value is not posted.
A: This seems to be what you are looking for: http://www.chami.com/tips/internet/042599i.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566082",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Web Service Authentication Inside Application First let me apologize in case I'm repeating a question, it seems I should be since it seems such a fundamental matter, but I can't seem to find an answer...
We have an application deployed on a web server (Web Logic). We have been given a task of providing a web service for one part of the application. The application already exists, uses legacy code, and generally can't be changed too much. The web service is asynchronous.
The application handles authentication and authorization internally using it's own username/password tables in a DB. When implementing the Web Service I can't seem to find any way of authenticating users based on the same mechanism already in place....
The only solution I could find is to create a custom LoginModule, which would be fine except that it by creates a security breach for the Web Logic users that aren't using our application, as well as seeming a bit of an over kill since I only want to authenticate the web service users. It seems that WebLogic authenticates the SOAP request way before it actually reaches my service end point, and I need to authenticate only when it gets to the actual application.
Am I missing something here? Is there a way for a web service to authenticate users internally?
We are using a JAX-RPC web service on WebLogic 11g.
Thanks in advance for any insights!
A: did you try the built-in RDBMS Authentication Providers?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to match the whole string in RegEx? I'm want to have two patterns:
1. "number/number number&chars"
2. "number_number"
1. "\d/\d \s"
2. "\d_\d"
These don't really work. For example the second one also matches "asdf894343_84939".
How do I force the pattern to match the WHOLE string?
A: You need to use the start-of-line ^ and end-of-line $ characters; for example, for your second pattern, use ^\d_\d$.
A: You colud use the '\A' and '\Z' flags -
Regex.IsMatch(subjectString, @"\A\d_\d\Z");
\A Matches the position before the first character in a string. Not
affected by the MultiLine setting
\Z Matches the position after the last character of a string. Not
affected by the MultiLine setting.
From - http://www.mikesdotnetting.com/Article/46/CSharp-Regular-Expressions-Cheat-Sheet
A: For second task(number_number) you can use [^a-zA-Z]\d.*_\d.*, in you example asdf894343_84939, you get 894343_84939, or if you want to get only one digit - remove .* after \d.
In your first task, you also may use \d.*/\d[^\s], for example, if you have 34/45 sss - you get 34/45. If you want to get result from whole string you must use in you pattern: ^your pattern$
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: GPS LocationManager and ListenerManager Management in a Base Activity My need is that,
all most of my activities need location of user to get updated data which is based on location. So, instead of define in all activities seperately I define a base activity (BaseActivity.java) and declared all activities have to inherite this class.
For example:
package com.example;
import com.example.tools.Utilities;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MenuItem.OnMenuItemClickListener;
import android.view.Window;
public class BaseActivity extends Activity {
protected static final String GpsTag = "GPS";
private static LocationManager mLocManager;
private static LocationListener mLocListener;
private static double mDefaultLatitude = 41.0793;
private static double mDefaultLongtitude = 29.0461;
private Location CurrentBestLocation;
private float mMinDistanceForGPSProvider = 200;
private float mMinDistanceForNetworkProvider = 1000;
private float mMinDistanceForPassiveProvider = 3000;
private long mMinTime = 0;
private UserLocation mCurrentLocation = new UserLocation(mDefaultLatitude,
mDefaultLongtitude);
private Boolean showLocationNotification = false;
protected Activity mActivity;
private BroadcastReceiver mLoggedOutReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
UserManagement.logOut(getApplication());
Utilities.setApplicationTitle(mActivity);
// finish();
}
};
private BroadcastReceiver mLoggedInReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Utilities.setApplicationTitle(mActivity);
// finish();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
super.registerReceiver(mLoggedOutReceiver, new IntentFilter(
Utilities.LOG_OUT_ACTION));
super.registerReceiver(mLoggedInReceiver, new IntentFilter(
Utilities.LOG_IN_ACTION));
mActivity = this;
if (mLocManager == null || mLocListener == null) {
mLocManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
mLocListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
Log.i(GpsTag, "Location Changed");
if (isBetterLocation(location, CurrentBestLocation)) {
sendBroadcast(new Intent(
Utilities.LOCATION_CHANGED_ACTION));
mCurrentLocation.Latitude = location.getLatitude();
mCurrentLocation.Longtitude = location.getLongitude();
if (location.hasAccuracy()) {
mCurrentLocation.Accuracy = location.getAccuracy();
}
UserManagement.UserLocation = mCurrentLocation;
mCurrentLocation.Latitude = location.getLatitude();
mCurrentLocation.Longtitude = location.getLongitude();
if (location.hasAccuracy()) {
mCurrentLocation.Accuracy = location.getAccuracy();
}
UserManagement.UserLocation = mCurrentLocation;
CurrentBestLocation = location;
}
}
@Override
public void onProviderDisabled(String provider) {
chooseProviderAndSetLocation();
}
@Override
public void onProviderEnabled(String provider) {
chooseProviderAndSetLocation();
}
@Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
};
chooseProviderAndSetLocation();
}
}
private void chooseProviderAndSetLocation() {
Location loc = null;
if (mLocManager == null)
return;
mLocManager.removeUpdates(mLocListener);
if (mLocManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
loc = mLocManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
} else if (mLocManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
loc = mLocManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
}
for (String providerName : mLocManager.getProviders(true)) {
float minDistance = mMinDistanceForPassiveProvider;
if (providerName.equals("network"))
minDistance = mMinDistanceForNetworkProvider;
else if (providerName.equals("gps"))
minDistance = mMinDistanceForGPSProvider;
mLocManager.requestLocationUpdates(providerName, mMinTime,
minDistance, mLocListener);
Log.i(GpsTag, providerName + " listener binded...");
}
if (loc != null) {
if (mCurrentLocation == null)
mCurrentLocation = new UserLocation(mDefaultLatitude,
mDefaultLongtitude);
mCurrentLocation.Latitude = loc.getLatitude();
mCurrentLocation.Longtitude = loc.getLongitude();
mCurrentLocation.Accuracy = loc.hasAccuracy() ? loc.getAccuracy()
: 0;
UserManagement.UserLocation = mCurrentLocation;
CurrentBestLocation = loc;
} else {
if (showLocationNotification) {
Utilities
.warnUserWithToast(
getApplication(),
"Default Location");
}
UserManagement.UserLocation = new UserLocation(mDefaultLatitude,
mDefaultLongtitude);
}
}
private static final int TWO_MINUTES = 1000 * 60 * 2;
protected boolean isBetterLocation(Location location,
Location currentBestLocation) {
if (currentBestLocation == null) {
// A new location is always better than no location
return true;
}
// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;
// If it's been more than two minutes since the current location, use
// the new location
// because the user has likely moved
if (isSignificantlyNewer) {
return true;
// If the new location is more than two minutes older, it must be
// worse
} else if (isSignificantlyOlder) {
return false;
}
// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation
.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;
// Check if the old and new location are from the same providerl
boolean isFromSameProvider = isSameProvider(location.getProvider(),
currentBestLocation.getProvider());
// Determine location quality using a combination of timeliness and
// accuracy
if (isMoreAccurate) {
return true;
} else if (isNewer && !isLessAccurate) {
return true;
} else if (isNewer && !isSignificantlyLessAccurate
&& isFromSameProvider) {
return true;
}
return false;
}
private boolean isSameProvider(String provider1, String provider2) {
if (provider1 == null) {
return provider2 == null;
}
return provider1.equals(provider2);
}
@Override
public boolean moveTaskToBack(boolean nonRoot) {
Utilities.warnUserWithToast(getApplicationContext(), "moveTaskToBack: " + nonRoot);
return super.moveTaskToBack(nonRoot);
}
@Override
protected void onDestroy() {
super.onDestroy();
mLocManager.removeUpdates(mLocListener);
super.unregisterReceiver(mLoggedOutReceiver);
super.unregisterReceiver(mLoggedInReceiver);
}
@Override
protected void onRestart() {
super.onRestart();
Utilities.warnUserWithToast(getApplicationContext(), "onRestart: " + getPackageName());
}
@Override
protected void onPause() {
super.onPause();
mLocManager.removeUpdates(mLocListener);
Utilities.warnUserWithToast(getApplicationContext(), "onPause: " + getPackageName());
}
@Override
protected void onResume() {
super.onResume();
Utilities.warnUserWithToast(getApplicationContext(), "onResume: " );
chooseProviderAndSetLocation();
}
@Override
protected void finalize() throws Throwable {
Utilities.warnUserWithToast(getApplicationContext(), "finalize: " );
super.finalize();
}
@Override
protected void onPostResume() {
Utilities.warnUserWithToast(getApplicationContext(), "onPostResume: ");
super.onPostResume();
}
@Override
protected void onStart() {
Utilities.warnUserWithToast(getApplicationContext(), "onStart: " );
super.onStart();
}
@Override
protected void onStop() {
Utilities.warnUserWithToast(getApplicationContext(), "onStop: ");
super.onStop();
}
public void setLocationNotification(Boolean show) {
this.showLocationNotification = show;
}
@Override
public boolean onCreateOptionsMenu(final Menu menu) {
if (menu != null && UserManagement.CurrentUser != null) {
final MenuItem miExit = menu.add("Log Out");
miExit.setIcon(R.drawable.menu_exit);
miExit.setOnMenuItemClickListener(new OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
sendBroadcast(new Intent(Utilities.LOG_OUT_ACTION));
menu.removeItem(miExit.getItemId());
return true;
}
});
}
return super.onCreateOptionsMenu(menu);
}
}
public class MainActivity extends BaseActivity {
}
This made obtain to manage common events handling such as LocationManager, onCreateOptionsMenu
It works very good. But there is a little problem. onPause, onResume, onRestart I bind and unbind locationlistener event so Gps sometime doesn't have enough time to throw the locationchanged event becuase user can pass quickly between activity and there are bind and unbind events for GPS. So I made my LocationManager and LocationListener variables to static. Now it's perfect. In all activities I have the latest location of user. It's great! But the GPS is runing ON always.
And here is the I want the thing how can I know the user send the application to back. I mean quit or pause it.
P.S: onPause, onResume events run in all activities. I need something general about the whole application.
A: Try this....
You can make use of a Service, which will run in background.
When ever your application is about to finish the service destroys.
So, place your ending logic in onDestroy() method of that Service.
@Override
public void onDestroy() {
// ending logic.
}
:)
A: Here is the code sample for Service
package com.test.examppplee;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class LocationService extends Service{
@Override
public void onCreate() {
Toast.makeText(getApplicationContext(), "onCreate", Toast.LENGTH_LONG).show();
super.onCreate();
}
@Override
public void onDestroy() {
Toast.makeText(getApplicationContext(), "onDestroy", Toast.LENGTH_LONG).show();
super.onDestroy();
}
@Override
public void onStart(Intent intent, int startId) {
Toast.makeText(getApplicationContext(), "onStart", Toast.LENGTH_LONG).show();
super.onStart(intent, startId);
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
package com.test.examppplee;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(getApplicationContext(), LocationService.class));
}
public void finish(View v){
finish();
}
public void start(View v){
startActivity(new Intent(getApplicationContext(), ServiceTestActivity.class));
}
}
package com.test.examppplee;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
public class ServiceTestActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void finish(View v){
finish();
}
public void start(View v){
startActivity(new Intent(getApplicationContext(), ServiceTestActivity2.class));
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to conditionally define the ON value of a JOIN in SQL? I am facing an issue with a conditional join.
This is my query :
SELECT table_b.name
FROM table_a
LEFT JOIN table_b
ON table_a.id = table_b.a_id
The description of my table_b :
id, a_id, ref_z, name
----------------------
1 | 0 | 1 | James
2 | 0 | 2 | John
3 | 2 | 2 | John. S
4 | 0 | 3 | Martin
5 | 6 | 3 | Martin. M
6 | 2 | 3 | Martin. M. Mr
Let's say I have a parameter @a_id.
I would like to join table_a and table_b ON table_a.id = @a_id if it exists else on 0.
So the output of the previous query will be (with @a_id = 2) :
James
John. S
Martin. M. Mr
Anyone has an idea, a blog post, a man page or anything else that can lead me to a correct query ?
Thank you,
A: where a_id = 2
your join can be shorten into using (a_id) since both columns have the same name and there is no ambiguity.
on / using should not be confused for your predicate clause (where)
A: Assuming you have only one table, this worked for me
DECLARE @t TABLE
(
id int,
a_id int,
ref_z int,
name varchar(50)
)
INSERT INTO @t VALUES (1, 0, 1, 'James'),
(2, 0, 2, 'John'),
(3, 2, 2, 'John. S'),
(4, 0, 3, 'Martin'),
(5, 6, 3, 'Martin. M'),
(6, 2, 3, 'Martin. M. Mr')
DECLARE @a_id int = 2
SELECT COALESCE(table_b.name, (SELECT table_b2.name FROM @t AS table_b2 WHERE table_b2.a_id = 0 ORDER BY table_b2.id LIMIT 1)) AS name
FROM (
SELECT ref_z
FROM @t AS table_z
GROUP BY ref_z
) AS table_z
LEFT OUTER JOIN @t AS table_b ON table_b.ref_z = table_z.ref_z AND table_b.a_id = @a_id
And the results:
James
John. S
Martin. M. Mr
Also note that this will also only display one record (the first) if there are multiple matches for a_id = 0
A: You could try using IFNULL with a sub select?:
SELECT ifnull(table_b.name,(select s.name from table_a sa inner join table_b sb on sa.a_id = sb.a_id where sb.a_id = 0 limit 1)) as name
FROM table_a
LEFT JOIN table_b
ON table_a.id = table_b.a_id;
Untested I'm afraid but hope it helps!
Also - how do you want to handle multiple rows with a_id = 0? The above will only bring back the first row if there are multiples...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to release the NSMutableArray about to return but NOT the objects inside? As the following code, I pass objects to make some data reset in this method, contained by a NSMutableArray. All good, code works.
But when I use Xcode Build and Analyze, it warns me "Potential leak" for the *newObjs.
If I add autorelease to it. I will lose my objects inside for future usage.
What should I do??
-(NSMutableArray*)resetNotGivenDrugs:(NSMutableArray *)drugObjs{
NSMutableArray *newObjs = [[NSMutableArray alloc]init];
//i can't release this though i have objects still need to be use inside
for(Drug *drug in drugObjs){
// some process to modify the Drug object that i don't want to be release
[newObjs addObject:drug];
}
return newObjs;
}
A: You should return [newObjs autorelease] rather than newObjs as the method suggests that an autoreleased object will be returned (doesn't contain new or init etc in the title). You won't lose references to the objects inside until the autorelease pool is drained, which won't be (usually) until the end of the run loop.
If you need to keep hold of the returned array, retain it in the calling method, but as I say the array and contents won't be released until you have finished executing. That's the point of autorelease.
A: Why are you returning a new array? If you are just changing properties if drug then they will be reflected in drugObjs and thus [drugObjs isEqual:newObjs] is true.
On the memory issue, you should autorelease newObjs. The caller should retain it if it needs to stay around past the end of the calling function.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WebView does not launch with a normal URL My WebView does not launch with a normal URL
I have done everything I could, The browser is simply not launching...
I have tried attaching webclient too, doesnt works. I have the internet permission in the manifest. Could anyOne help me here? :(
Its so simple and its not workin.
void somemethod()
{
WebView myWebView = new WebView(mycontext);
myWebView.loadUrl("http://stackoverflow.com/questions/5066778/android-html-image-prob");
}
A: This is not the code to launch a browser bro. This is the code to open url into the embedded webview inside the app.
To open the url in Android's default browser try this
Intent myIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(strURL));
startActivity(myIntent);
To open a url into the embedded browser, embed a webview in a layout and then call the second line in your code.
A: If you really want to use WebView instead of Browser intent, there is two way. One way is to declare a webview in layout file, connect it to Activity class and set some attributes and load the url.
Other way is to declare the WebView dynamically. In that case you have to set necessary attributes, set layout parameters and you must add it to content view. Then load the url.
Here is a tutorial Hello, WebView
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get Table in DataRelation at runtime I try to explain with an example what i need
I have a Patient and Order tables in db. Patient can have multiple orders through stored procedure i will get patient attributes and orders related to that patient and i will put it in dataset. But patient attributes will be in one Datatable and Order of that patient will be in another Datatable. In front end i need to create a class of this Relation.
like Class Patient
{
patient attributes
list of orders he has done
}
A: Assuming you are talking about System.Data.DataRelation class in the .NET Framework...
MSDN has ample information about properties on this class, including the ones you need.
http://msdn.microsoft.com/en-us/library/system.data.datarelation.aspx
using System.Data;
var myRelation = new DataRelation(...your data...);
DataTable parent = myRelation.ParentTable;
DataTable child = myRelation.ChildTable;
ForeignKeyConstraint foreignKey = myRelation.ChildKeyConstraint;
UniqueConstraint uniqueKey = myRelation.ParentKeyConstraint;
DataColumn[] childColumns = myRelation.ChildColumns;
DataColumn[] parentColumns = myRelation.ParentColumns;
etc...
That said, I would recommend elaborating on exactly what you want to do. It isn't clear from your statement " so i need to create a relationship and have to create a class from dataset. If not possible, Is there any alternate way to do that?" what your use case is. That makes it difficult to answer whatever is the core problem you want to solve.
A: Based on your edited question, I would sit down and ask yourself, do I REALLY need to generate these classes dynamically at runtime ? That seems to be the thrust of your question, but I should think that the use case would be relatively small.
It seems more likely that you just want to create entity classes that reflect what is in your database. For this you might look at an ORM like Nhibernate (and many others), or you could even roll your own. Even strongly typed DataSets are an option, after a fashion.
If you are doing something more one-off, a LINQ to SQL query can return anonymous classes based upon your data - complete with type safety etc.
Bottom line, I'm still not sure exactly what you are trying to do, or why? Is the issue "how do I get data from a database into an entity class", or is the issue "how do I create a 'has-a' relationship between two classes", or ... ?
So the former, then. I would start by re-iterating that there are relationships between classes, and there are relationships between tables. There's no reason that your classes necessarily need to be aware of the relationship in the tables, just of the relationships between themselves
That said, ORMs like Nhibernate will help you maintain the relationship between tables.
In terms of getting the data out of the database and into your entities, a simple approach is below. I won't say this is ideal, or even good, but the core ideas work. I would recommend getting familiar with the basic operations and then reading a lot more (and asking a lot more questions) to zero in on a good approach that works for your application.
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
namespace Sample
{
public class Patient
{
public int PatientId { get; set; }
public string Name { get; set; }
private IEnumerable<Order> _orders;
public List<Order> Orders { get { return new List<Order>(_orders); } }
public static Patient GetById(int patientId)
{
using (var cn = new SqlConnection("your Patient connection string"))
{
cn.Open();
using (SqlCommand cm = cn.CreateCommand())
{
cm.CommandType = CommandType.Text;
cm.CommandText = "SELECT PatientId, Name FROM Patient WHERE PatientId = @PatientId";
cm.Parameters.AddWithValue("@PatientId", patientId);
using (SqlDataReader dr = cm.ExecuteReader())
{
if (!dr.Read())
return null;
return new Patient
{
PatientId = dr.GetInt32(0),
Name = dr.GetString(1),
_orders = Order.GetAllForPatient(patientId)
};
}
}
}
}
public bool Save()
{
// save Patient to Database
foreach (var order in _orders)
order.Save();
return true;
}
}
public class Order
{
public int OrderId { get; set; }
public int PatientId { get; set; }
public string ServiceOrdered { get; set; }
public static IEnumerable<Order> GetAllForPatient(int patientId)
{
var orders = new List<Order>();
using (var cn = new SqlConnection("your Order connection string"))
{
// ... load Orders Here.
}
return orders;
}
public bool Save()
{
//save order to database;
return true;
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566106",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Symfony bhLDAPAuthPlugin doubt i'm working on a Symfony project and using the bhLDAPAuthPlugin to connect my app with the Company's Active Directory.
Its a nice plugin, easy to install and use, but i need to customize it. I have to add one parameter to the login form (i've already done this) and assign its value to the user if login succeeds (that is my trouble) but have no idea where are the user object's values assigned.
Structure of the folders and filenames are a little confusing and i don't know where to search. Please if some of you have worked with this plugin sure you can help me! i hope to have explained me well.
Thank you very much for your time!
A: I have no knowledge about this specific plugin, but I just looked in the source.
But the authentication is handled in /plugins/bhLDAPAuthPlugin/modules/bhLDAPAuth/actions/actions.class.php. In the executeSignin() to be specific, a form is created (by default a bhLDAPAuthFormSignin), and presented to the user. On POST this form is validated, and when valid, it calls the signIn($user, $remember) function on the user class.
The user class is defined apps/<yourapp>/lib/myUser.php, and probably inherits from bhLDAPAuthSecurityUser, defined in /plugins/bhLDAPAuthPlugin/trunk/lib/user/bhLDAPAuthSecurityUser.class.php.
You can override the signIn() method from bhLDAPAuthSecurityUser in myUser, setting your own properties, after calling the parent signIn().
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to implement Https(SSL Middleware) in Django I am a newbie in Django and web development. I want to implement
Exactly this Question, but in django. I have searched many blogs and questions, nowhere was i able to find,exactly how to implement this. The SSL Middleware Django, is something i couldnt grasp very well. If that is the solution, can anyone please tell me how to implement it?
Is the question clear ? or do i need to add a few things, please comment i will make the necessary changes.Any help will be highly appreciated.Thanks in advance.
P.S: I have added the ssl certificate on the server. So that is taken care of.
A: You just need to add the middleware class to the list of middleware in your settings.py and follow the instructions for your views as directed in the snippet. Here's the documentation guide to middleware.
Hope that helps you out.
A: Here's an example middleware that redirects to the SSL site if HTTP is used:
from django.http import HttpRequest
from django.shortcuts import redirect
#Require SSL com only. If we get anything else, redirect to https /
class RequireSSL(object):
def process_request(self, request):
assert isinstance( request, HttpRequest )
if not request.is_secure():
return redirect( 'https://%s/' % request.get_host() )
Then inside your settings.py:
MIDDLEWARE_CLASSES = [
'website.middleware.require_ssl.RequireSSL',
...
]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: error in gmail contextual gadget i'm working on a gmail contextual gadget (GWT) to deploy on the google market place.
the gadget is triggered correctly but when i try to get content matches it fail.
<Module>
<ModulePrefs author="xxx" author_affiliation="xxx" author_email="xxx"
directory_title="Test GMail Contextual Gadget"
title="Test Contextual Gadget">
<Require feature="google.contentmatch">
<Param name="extractors">google.com:EmailBodyExtractor</Param>
</Require>
</ModulePrefs>
<Content type="html" view="card">
....
in the browser console i see the following error:
Uncaught ReferenceError: google is not defined
any idea ?
A: I had exactly the same issue when working with contextual gadgets and GWT.
You must prefix with $wnd like this :
var matches = $wnd.google.contentmatch.getContentMatches();
see also this thread where I figured it out :
https://groups.google.com/forum/#!topic/google-apps-gadgets-api/gxNoIQUVI4k
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566113",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: If there is string.Empty why there is not char.Empty?
Possible Duplicate:
Why is there no Char.Empty like String.Empty?
I want to pass an empty char as a method parameter and I was wondering why I cannot say
char.Empty
while C# allows me to specify string.Empty ?
If not do I have '' as the only option ?
A: There is no empty char same way there is no empty number.
You can try using "null" character:
char empty = '\0';
A: You can use for identifying empty char:
default(Char)
A: There is no such thing as an empty char. You would need to use nullable types to introduce that concept.
char? c = null;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566115",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Trying to understand USB, using C I have searched for these answers but had no luck :( I have been working with a RFID device from China, so I know next to nothing about it. I am trying to write a program (actualy i'm trying to use someone else's library) to interact with it. When a tag goes over the RFID device the device types out the numbers like a HID keyboard and then presses the enter key and waits for the next one. (I am using windows 7 btw)
My questions are these:
*
*Apart from knowing the VID (Vendor ID) and PID (Product ID) Is there anything else I would need to know about the device to start reading from it.
*In a example I saw, before reading the device the example program wrote to the device first, sending 8 bytes in an array (bytes[8]) with each byte being somthing like [0] = 60, [1] = 0, [2] = 20 and so on. When the device stops being read it also sent a bunch of stop bytes. Could someone explain this a bit more to me and weather this is neccesary, and wether these start/stop bytes are device specific or it is a general start/stop thing with USB's?
*Does anybody know any good, simple source out there (or application) that is set up to do what I would like to do?
Answers to any of the questions are appreciated, thanks.
A: Before trying to partially reverse-engineer the basic USB protocol you could read the (open) USB-specification (see http://www.usb.org/) and familiarize yourself with the keywords (endpoint, URB, pipes) and principles control/bulk/isochronous/interrupt-transfers).
I liked a lot the linux-usb-implementation as it is simply implemented and easy to read: linux/include/usb.h.
To address USB devices from user-space you could use libusb (exists for Windows and Linux). This way you can access USB devices without writing a kernel-driver.
A: If your RFID reader is really a virtual USB HID keyboard than you might just register for RawInput and listen for data. In this case you really don't care about the hardware beneath and I think that somebody else already responded here how to do it.
If this approach doesn't work, it means that your RFID reader is not a realy USB HID keyboard device and you should ask your vendor for a driver, or for the structure of data sent over USB.
If you can't find neither a driver or some specs in this case you have to start to make reverse engineering over your USB device. One tool you could start with it is USBView.exe from Microsoft you can find it Windows Driver Kit - the source code, you just build it and have the application. After this you should try to get the USB descriptor structure and analyzed, you will find lots of valuable information there that can help your to understand how data is sent.
As you see a lots of Ifs...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Autocompile SASS stylesheet when a partial stylesheet is changed I've just started working on a project using SASS on a windows machine. The main stylesheet (styles.scss) inports several partials (_typography.scss etc), and styles.scss is watched by sass and gets automatically compiled to styles.css.
On a mac, any changes to the partials results in styles.scss getting recompiled, but on a pc I have to save styles.scss itself in order to get SASS to compile it. Is there a way I can get a pc to behave the same as a mac?
A: I was having a similar problem.
My file structure looked like this:
website-root
_dev
_some-partial.scss
_stuff.scss
main.scss
css
main.css
js
...
watchSass.bat
...
I keep my .scss files inside _dev, and compile them out into the css folder.
My previous batch file looked like this:
sass --watch "_dev\main.scss":"css\main.css"
I simply changed it to watch the entire folder, not the specific file, like this:
sass --watch "_dev":"css"
Now changing any .scss file causes the non-partials to be recompiled (in turn recompiling the partials they include).
Thanks to user hlb on freenode #sass for helping me sort that out!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Why would Openlayers always render over other divs? I'm having trouble getting an Openlayers div to allow other divs to appear above it.
Having tried the solution proposed here as well as the more classy-looking one here, I haven't had any luck yet. Openlayers always orders itself over other divs. I've also set the z-index for my other div (which I want on top) as high as it goes, still no effect.
Is there somewhere it could be getting overridden? Or some setting that needs an extra trick to get rid of?
EDIT: Never mind, I got an answer and the problem was that I forgot to position the element. Just remember to add "position: relative;" (for example) to any element needing a z-index. Leaving this question here for others' edification, but it has been answered elsewhere.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566132",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I copy code from Kindle PC and preserve formatting Has anyone figured out a good way to copy code from Kindle PC?
I've just downloaded a programming book to Kindle PC for the first time. The code in the book is formatted very nicely, and I'd like to copy the code directly from the Kindle PC book to Visual Studio without having to use auto-indent. For some reason when I copy text from the book, none of the whitespace, tabs, or newlines are preserved. I literally end up with this:
using System; using System.Collections.Generic; using System.Linq; namespace NumericQuery { class Program { static void Main(string[] args) { List list = new List() { 1, 2, 3 }; var query = from number in list where number < 3 select number; foreach (var number in query) { Console.WriteLine(number); } } } }
I'm frustrated because I can't download the code from the author's website since I don't have an ISBN (because I didn't buy a hardcopy).
A: I have just resolved this issue of copying code snippets from a Kindle book to a text/source code editor of your choice. This same topic was discussed in a posting on stackoverflow.com entitled "Why is Chrome rendering this HTML as a completely blank page? From Node.js, following The Node Beginner Book [closed]". That particular posting describes the exact same problem I was experiencing (same Kindle book, same code snippet, same code symptom!). Unfortunately, that posting was prematurely closed before any of the respondents could provide the exact answer, otherwise I would've responded to that posting.
However, I dug into this issue more deeply and discovered the root cause of the problem when copying code snippets from Kindle books: when you copy text from the Kindle app, it uses hex code 0xA0 for space characters, not 0x20. Hex code 0xA0 is extended ASCII for non-breaking whitespace. Well, this doesn't work when you are expecting to copy-and-paste HTML literal strings, as was the case in the aforementioned posting.
And so this explains the behavior in the aforementioned posting: the original poster indicated that he could get around the problem by hand-retyping all of the text. It's because the hand re-typing was using proper 0x20.
This had other symptoms which I didn't understand at first but are now explained: my text editor (Notepad++) was not correctly identifying the reserved keywords in my source code. Again, this is because the keywords were separated by 0xA0, not 0x20. The keyword parser in Notepad++ must be tokenizing off of 0x20.
Solution: after pasting text from Kindle, perform a search and replace using regular expression searching capabilities in your source code editor. Search for regular expression \xA0 and replace it with \x20 (or, depending on your editor just type in a single space bar character in the Replace field [that is how Notepad++ works]).
A: I would check the publisher's website. I've found that they will often post the source code that accompanies books. If they don't do this, then it makes me much less likely to buy the book. (In some cases, no amount of copy/pasting can retrieve any code, regardless of poor formatting, and so trying to get the code from the publisher is the only way).
A: I found that Kindle for PC was simply converting all the newlines to \x20 making the find and replace trick not work. My solution isn't great, but it works:
I downloaded Calibre and started using that. Suffice it to say, you can find ways to use Calibre to open whatever you need it to with some Googling.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566133",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: c++ macro concatation not worked under gcc #include <iostream>
void LOG_TRACE() { std::cout << "reach here"; }
#define LOG_LL_TRACE LOG_TRACE
#define LL_TRACE 0
#define __LOG(level) LOG_##level()
#define LOG(level) __LOG(##level)
int main()
{
LOG(LL_TRACE);
return 0;
}
The code is worked under Visual Studio, but report: test.cpp:13:1: error: pasting "(" and "LL_TRACE" does not give a valid preprocessing token.
How can I fix it?
ps: The macro expansion is supposed to be LOG(LL_TRACE) --> __LOG(LL_TRACE) --> LOG_LL_TRACE().
ps: suppose LL_TRACE must have a 0 value, do not remove it.
A: Two things make this code not compile on g++:
First, the error you're quoting is because you want to have this:
#define LOG(level) __LOG(level)
Notice no ##. Those hashmarks mean concatenate, but you're not concatenating anything. Just forwarding an argument.
The second error is that you have to remove
#define LL_TRACE 0
This line means you end up calling LOG(0) which expands into LOG_0 which isn't defined.
A: Shouldn't it be :
#define LOG(level) __LOG(level)
That works:
#include <iostream>
void LOG_TRACE() { std::cout << "reach here"; }
#define LOG_LL_TRACE LOG_TRACE
#define __LOG( level ) LOG_##level()
#define LOG(level) __LOG(level)
int main()
{
LOG( LL_TRACE );
return 0;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566136",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to call a Spring MVC controller by ui:include? I am working on a legacy project that was built with JSP. The JSP page included an HTML page via <jsp:include>. But the included page was essentially a mapping to a Spring MVC controller.
Now I switched to JSF and replaced the <jsp:include> with a <ui:include>. But now, the call to the Spring MVC servlet does not work anymore.
Obviously there is a difference between <jsp:include> and <ui:include> of JSF. Does anybody know, how I can call a spring MVC component in JSF?
A: For now, we solved this by using JQuery's load method to call the SpringMVC servlet. We refrained using ui:include for now.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566137",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Cross-domain redirect to a partially filled form on Django web application I have an HTML form in my Django web application (NOT implemented using Django forms) that does POST request.
Now I want to implement a feature so that other web apps, not necessarily django, from different domains, can send some data to my application and get redirected to the web page with this form, partially filled with that data (the data can be JSON).
Besides redirecting, after the user clicks submit on my form, I would also want to send a message to the other server with some short text information.
I am not sure what is the best way to implement this. REST interface like Piston?
Could you give me some general directions I should follow?
A: You should create a view that handles the POST data from the form and the external web apps.
You should be able to check whether the data you are getting in the view is coming from your site or another by checking request.META['HTTP_REFERER'].
If it is from your site, you can just handle the form as you usually would.
However if it is from an external site, you would instead render the template with the form in it. You can put the information you got from the external site into the context, so you can pre-fill the form in the template.
You should also include a flag in the form to say that this was from an external site, something like:
<input type="hidden" name="external_site_url" value="{{ external_site_url }}">
After that form is submitted, you can check for the existence of external_site_url. If it exists you can then send the message to the other server.
Note, because you want other apps to use your view, you'll have to disable CSRF protection on the view (https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#csrf-protection-should-be-disabled-for-just-a-few-views).
Also, by allowing other apps to use your view, you are opening yourself up to a lot of possible attacks. Be very careful with input validation and only give the view the ability to do the things it really needs -- you don't want an external app to be able to delete entries in your database for example.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566145",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Imported flash builder project unable to open swc I wanted to import an older FB project into the flash builder on my new pc, but I only have the filestructure. So I used 'import>existing projects into workspace'.
The files seem to be intact still, but the project now gives me an error regarding an swc in the bin folder: 'unable to open \'something'\bin\'something'.swc
I have no idea how to solve this, or what this even means. Can somebody lend me a hand here?
A: This would be referring to an old library project that you forgot to include in your workspace (or open). In Eclipse, when you specify a path as /your-library-project/some/path, it automatically resolves the real path to whatever you're trying to reference.
In this particular case, you were referring to the swc created by this library project and linking to it directly. To fix this issue, you'll need to find the library project and import it into your workspace.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP precision rounding question Wanted to as a simple question.
Code:
$myarray = array(5.0000);
echo round($myarray[0],2);
Ouput:
5
Why is the output 5 and not 5.00 ?
Thanks
A: It's because round actually rounds off the data you give to it, it doesn't change how that data is printed.
If you want to specify how the data is output, look into using printf, such as:
printf ("%.2f\n", $myarray[0]);
A: It doesn't show the 0's after the decimal point if there are only 0's.
5.050 would be shown as 5.05...
you can have a look at the number_format function if you want to show the 0's.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Prevent Googlebot from running a function We have implemented a new Number of Visits function on our site that saves a row in our Views database when a company profile on our site is accessed. This is done using a server-side "/addVisit" function that is run each time a page (company profile) is loaded. Unfortunately, this means we had 400+ Visits from Googlebot last night.
Since we do want Google to index these pages, we can't exclude Googlebot on these pages using robots.txt.
I have also read that running this function using a jQuery $.get() will not stop Googlebot.
Is the only working solution is to exclude known bot IPs or are there options?
Or possibly using a jQuery $.get(/addVisit) with a robots.txt exclude /addVisit will stop googlebot and other bots from running this function?
A: Create a robots.txt file in the root directory of your website, and add:
User-agent: Google
Disallow: /addVisit
You can also use * instead of Google, so that /addvisit doesn't get indexed at by any engine. Search engines start always looking for /robots.txt. If this file exists, they parse the contents and respect the applied restrictions.
For more information, see http://www.robotstxt.org/robotstxt.html.
A: If you're handling your count by a server side HTTP request, you could filter any user agents that contain the word 'Googlebot'. A quick Google search shows me a couple of Googlebot user agent examples:
Googlebot/2.1 (+http://www.google.com/bot.html)
Mozilla/5.0 (compatible; Googlebot/2.1; +http://www.google.com/bot.html)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why appears a duplicate section cell while-in-search-mode in UITableViewController? Why appears a duplicate section with one empty cell (or even maybe table) behind my cells that are the results of the search? That dummy cell appears when I'm dragging my real on-top cells to the bottom.
UPDATE: However, I do not see a duplicate tableView in my xib file:
A: Looks like duplicate and never happened to me before. Haven't you accidentally allocated another table view object? What about viewDidLoad or loadView?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Lowercase or uppercase for SQL Statements Is there a fundamental difference between these statements
"select * from users where id = 1"
OR
"SELECT* FROM users WHERE id = 1"
OR
'select * from users where id = 1'
OR
'SELECT * FROM users WHERE id = 1'
I was just wondering... I always used the 2nd method, but some collegues are bound to use other methods. What is the most common convention?
A: There is no difference in terms of how it will work, but usually I put SQL keywords in uppercase so it would be:
SELECT * FROM users WHERE id = 1
A: No.
There is no difference. It's all about your habits.
It's like to ask is there any differences between these code blocks in C++:
int main() {
}
OR
int
main()
{
}
OR
int main()
{
}
Anyways the most common way to write SQL statements is to write keywords in UPPERCASE.
A: You have two separate issues:
*
*Whether you use uppercase or lowercase for SQL keywords. This is a matter of taste. Documentation usually uses uppercase, but I suggest you just agree on either in the particular project.
*How to quote SQL in your host language. Since strings are quoted with single quotes (') in SQL, I suggest you use double quotes (") to quote SQL statements from your host language (or tripple quotes (""") if your host language is python). SQL does use double quotes, but only for names of tables, columns and functions that contain special characters, which you can usually avoid needing.
In C/C++ there is a third option for quoting. If your compiler supports variadic macros (introduced in C99), you can define:
#define SQL(...) #__VA_ARGS__
and use SQL like SQL(SELECT * FROM users WHERE id = 1). The advantage is that this way the string can span multiple lines, while quoted strings must have each line quoted separately. The tripple quotes in python serve the same purpose.
A: There is no fundamental difference between either of the above mentioned. However, the official SQL standards up until and including the latest, SQL:2008, have always used upper case to distinguish fields from operators.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: Delphi Chromium Embedded: ICefBrowser.GetMainFrame returns NIL I'd like to use TChromium component which is part of Delphi Chromium Embedded (http://code.google.com/p/delphichromiumembedded/). Unfortunately once I build the application and run it (it's inside 'bin' directory which contains all the CEF binaries, so no, it's not about missing DLL), the call to Chromium.Browser.GetMainFrame returns NIL, which actually stops me from using DCE at all.
WinXP 32, Delphi7PE. Any tips?
A: You might try posting to the DelphiChromiumEmbedded Google group. That group is actively monitored by Henri Gourvest, the lead programmer working on the Delphi encapsulation of CEF.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566166",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iPhone app - Review guidelines - Contest rules i've just had my iPhone app rejected on the 20.2 statement of the Review Guidelines:
Official rules for sweepstakes and contests, must be presented in the app and make it clear that Apple is not a sponsor or involved in the activity in any manner
Now, I have a problem. In my app I will have more than one contest, even if all based on the same ground rules. Can I put these rules in the app (like in a UITextField) taking them dynamically form a server? In this manner I could specify, for exemple, the specific period of time each contest would last without having to chose them right now... Do you think that this would be accepted or I have to put those rules directly in the bundle?
Thank you
A: it would definitely be accepted...
but, a web view would be better than a text field... open an html hosted on your server in the web view. You can add rules and declaration that apple is not involved in any way in that html and change it whenever you want... with html you'd be able to add images (or even videos .. HTML5?)...
you can also include a default html in your app which would open when theres no connectivity...
A: In way you have already done you are able to violate apple guidelines at any moment.
Consider updating your app instead of downloading contests from server.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Backbone.js appending more models to collection I have a following code that fetches data from the server and add to the collection.
// common function for adding more repos to the collection
var repos_fetch = function() {
repos.fetch({
add: true,
data: {limit:curr_limit, offset:(curr_offset*curr_limit)},
success:function() {
curr_offset++;
console.log(repos.length);
}
});
};
each time I call the function "repos_fetch", the data is retrieved from the server and added to the collection "repos".
My problem is that I want to APPEND to the collection, instead of REPLACING. So I put the option "add: true" there.
But below function looks like it's keep replacing the data in collection.
What's even strange is that if I remove the line "curr_offset++;" then the data gets appended!. "curr_offset" just increments, so I get different sets of data.
What's going on here?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Execute InsertQuery command from SqlDataSource in JavaScript I am using ASP.NET
If I want to execute my Insert command from my SqlDataSource in my code behind I would do this.
SqlDataSource1.Insert()
But how would I be able to do this in JavaScript?
<script type='text/javascript' language="javascript">
function valSubmit() {
//Need to call the Insert Command here!
}
</script>
OR
Where in my code behind can I place the Insert() command to make sure only after my valSubmit() function in JavaScript have executed it will then execute the Insert Command?
A: Create a Web Handler that will invoke the Insert method and call this handler using your preferred AJAX method.
A: Create Ajax method Example of Ajax method
$.ajax({
type: POST,
url: url,
data: data,
success: success,
dataType: dataType
});
function success()
{
alert(data saved);
}
URL : a new page for example ajax.aspx.On this page load you can write your method for insertion.
Data : Parameters, These will be accessed using Request.Querystring
and call server methods which are used for insertion or any other operation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can I draw something on window, that does not belongs to me, using opengl? I heard you can hook window handle and use this window as OpenGL canvas. I know how to hook windows, but I can't find how can I draw on this window.
PS. I'm using Qt if it helps.
A: OpenGL contexts are only usable in one thread at a time and are bound to processes. So what that required was creating a OpenGL context of a foreign process' resource.
On Windows using some very quircky hacks this was possible in at least WinXP (I don't know about Vista or 7); this usually includes making large portions of the process memory shared.
On X11/GLX it's a lot easier by creating the context as indirect rendering context (unfortunately OpenGL-3 has not complete indirect GLX specification, for some shady excuses of reasons); indirect contexts can be accessed from multiple processes.
In any case both processes must cooperate to make this work.
A: Qt has some NativeWindow hacks you can play with a bit.
On Windows you can use findWindowEx to get a HWND and interrogate its geometry, then position your own window on top of it.
You really shouldn't be able to interfere with another process's windows arbitrarily -- it's a security hazard.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566205",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Saving advanced state of an Android Listview I know that Android provides a mechanism to allow developers to save and restore states in an Activity via the following methods:
protected void onSaveInstanceState (Bundle outState)
protected void onRestoreInstanceState (Bundle savedInstanceState)
I've seen numerous examples whereby people show how to save simple state (such as the current index in a listview), and many examples where people say that the listview should just be backed by a data model which will allow the list to be restored. However, when things get more complicated and the user interaction more involved, I've been struggling to find out the correct way to save this state.
I have a listview which contains custom controls for each row. When clicked a row will expand with animation to show additional details to the user... within the additional details view, the user is also able to change certain things. Now I know that if my Activity is destroyed (or my Fragment replaced), the current state reflecting the UI changes and the user's interaction with the list is now lost.
My question is how do I got about correctly saving this detailed state of my listview such that the state of each custom component row is also preserved?
Thanks!
Edit: Thanks for the replies below. I understand that SharedPreferences can be used to store key-value state, however, I guess I am more interested in the view states.... for instance Android will automatically save/restore the viewstate of an EditText field (i.e. its contents) in my activity , so how do I go about achieving the same thing with more complex custom components in a listview? Do I really have to save this state all manually myself (i.e. save exactly which listview rows have been expanded, save all the ui changes the user has made/toggled, etc.)?
A: I am not sure but I assume SharedPreferences is what you might be looking for.
A: Make use of SharedPreferences in onPause() method.
where you can store all you activities data when it is moving to background.
When ever you want to restore the data fetch from the Shared Preferences.
A: I don't like to say this, but it seems that this must all be done yourself. The framework does not offer a pre-made method for "save state of view".
Whether you save the state in a Bundle or SharedPreferences, I think the point is that you need to determine state variables that reflect your current list choices, persist them yourself, and onResume() you need to reintroduce that state into your activity.
... quite a manual process, as you say ...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Local class definitions: why does this work Why does the following style of code work:
BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
//do something based on the intent's action
}
}
I would expect it to be:
private class MyBroadcastReceiver extends BroadcastReceiver () {
public void onReceive(Context context, Intent intent) {
//do something based on the intent's action
}
}
MyBroadcastReceiver receiver = new MyBroadcastReceiver();
In the 1st code piece above, how does the compiler know that receiver is of type MyBroadcastReceiver and not BroadcastReceiver? Isn't this ambiguous? Why is this allowed?
If I define:
BroadcastReceiver receiver2 = new BroadcastReceiver();
Now is receiver == reciver2?
EDIT:
BroadcastReceiver
http://developer.android.com/reference/android/content/BroadcastReceiver.html
A: This is an anonymous class declaration. See section 15.9.5 of the JLS for more details:
An anonymous class declaration is automatically derived from a class instance creation expression by the compiler.
The type of the receiver variable actually is just BroadcastReceiver - but the type of the object created is an instance of ContainingClass$1 which extends BroadcastReceiver.
A: It works because you are using an anonymous class
A: You are creating here an unnamed class, which extends BroadcastReciever. This is usual in Java e.g. to create Listeners. As the unnamed class extends BroadcastReciever it can be used by a reference of that type.
A: This is called an anonymous inner class. As this name indicates, such a class has no name.
It will be compiled to a .class file name EnclosingClass$1.class. The class file of the receiver2 variable will be EnclosingClass$2.class.
A: In the first example, the class receiver is NOT an instance of MyBroadcastReceiver; it is an anonymous instance of BroadcastReceiver.
BroadcastReceiver receiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
}
}
MyBroadcastReceiver myReceiver = new MyBroadcastReceiver();
(receiver instanceof MyBroadcastReceiver); // is FALSE
(receiver instanceof BroadcastReceiver); // is TRUE
A:
In the 1st code piece above, how does the compiler know that receiver is of type MyBroadcastReceiver and not BroadcastReceiver?
It does not, you simply created an instance of an anonymous class extending BroadcastReceiver with a specific implementation.
Now is receiver == reciver2?
Clearly no: they are two distinct instances (even though they both extend BroadcastReceiver).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566208",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: When should you use the as keyword in C# When you want to change types most of the time you just want to use the traditional cast.
var value = (string)dictionary[key];
It's good because:
*
*It’s fast
*It’ll complain if something is wrong (instead of giving object is null exceptions)
So what is a good example for the use of as I couldn't really find or think of something that suits it perfectly?
Note: Actually I think sometimes there are cases where the complier prevents the use of a cast where as works (generics related?).
A: Using as will not throw a cast exception, but simply return null if the cast fails.
A: Use as when it's valid for an object not to be of the type that you want, and you want to act differently if it is. For example, in somewhat pseudo-code:
foreach (Control control in foo)
{
// Do something with every control...
ContainerControl container = control as ContainerControl;
if (container != null)
{
ApplyToChildren(container);
}
}
Or optimization in LINQ to Objects (lots of examples like this):
public static int Count<T>(this IEnumerable<T> source)
{
IList list = source as IList;
if (list != null)
{
return list.Count;
}
IList<T> genericList = source as IList<T>;
if (genericList != null)
{
return genericList.Count;
}
// Okay, we'll do things the slow way...
int result = 0;
using (var iterator = source.GetEnumerator())
{
while (iterator.MoveNext())
{
result++;
}
}
return result;
}
So using as is like an is + a cast. It's almost always used with a nullity check afterwards, as per the above examples.
A: Every time when you need to safe cast object without exception use as:
MyType a = (MyType)myObj; // throws an exception if type wrong
MyType a = myObj as MyType; // return null if type wrong
A: The implementation of .Count() in Enumerable uses it to make Count() for collection faster
The implementation is like:
ICollection<TSource> collection = source as ICollection<TSource>;
if (collection != null)
{
return collection.Count;
}
ICollection collection2 = source as ICollection;
if (collection2 != null)
{
return collection2.Count;
}
That tries to cast the source to either ICollection or ICollection both have a Count property.
If that fails Count() iterates the entire source.
So if you are unsure about the type and need the object of the type afterwards (like in the above example) you should use as.
If you only want to test if the object is of a given type use is and if you are sure that the object is of a given type (or derives from/implements that type) then you can cast
A: Ok Nice replies everyone, but lets get a bit practical. In your own code,ie non-vendor code the REAL power of AS keyword doesn't come to the fore.
But when dealing with vendor objects as in WPF/silverlight then the AS keyword is a real bonus.
for example if I have a series of controls on a Canvas and I want to track track thelast selectedControl, but clear the tracking varaible when I click the Canvas i would do this:
private void layoutroot_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
{
//clear the auto selected control
if (this.SelectedControl != null
&& sender is Canvas && e.OriginalSource is Canvas)
{
if ((sender as Canvas).Equals(( e.OriginalSource as Canvas)))
{
this.SelectedControl = null;
}
}
}
Another reason it use AS keyoword is when your Class implements 1 or more Interfaces and you want to explicitly use only one interface:
IMySecond obj = new MyClass as IMySecond
Although not really necessary here, it will assign null to variable obj if MyClass does not implement IMySecond
A: As is used to avoid double casting logic like in:
if (x is MyClass)
{
MyClass y = (MyClass)x;
}
Using
MyClass y = x as MyClass;
if (y == null)
{
}
FYI, IL generated for case #1:
// if (x is MyClass)
IL_0008: isinst MyClass
IL_000d: ldnull
IL_000e: cgt.un
IL_0010: ldc.i4.0
IL_0011: ceq
IL_0013: stloc.2
IL_0014: ldloc.2
IL_0015: brtrue.s IL_0020
IL_0017: nop
// MyClass y = (MyClass)x;
IL_0018: ldloc.0
IL_0019: castclass MyClass
IL_001e: stloc.1
and for case #2:
// MyClass y = x as MyClass;
IL_0008: isinst MyClass
IL_000d: stloc.1
// if (y == null)
IL_000e: ldloc.1
IL_000f: ldnull
IL_0010: ceq
IL_0012: stloc.2
IL_0013: ldloc.2
IL_0014: brtrue.s IL_0018
A: Here is a snippet from http://blog.nerdbank.net/2008/06/when-not-to-use-c-keyword.html
class SomeType {
int someField;
// The numeric suffixes on these methods are only added for reference later
public override bool Equals1(object obj) {
SomeType other = obj as SomeType;
if (other == null) return false;
return someField == other.SomeField;
}
public override bool Equals2(object obj) {
if (obj == null) return false;
// protect against an InvalidCastException
if (!(obj is SomeType)) return false;
SomeType other = (SomeType)obj;
return someField == other.SomeField;
}
}
The Equals1 method above is more efficient (and easier to read) than Equals2, although they get the same job done. While Equals1 compiles to IL that performs the type checking and cast exactly once, Equals2 compiles to do a type comparison first for the "is" operator, and then does a type comparison and cast together as part of the () operator. So using "as" in this case is actually more efficient. The fact that it is easier to read is a bonus.
In conclusion, only use the C# "as" keyword where you are expecting the cast to fail in a non-exceptional case. If you are counting on a cast to succeed and are unprepared to receive any object that would fail, you should use the () cast operator so that an appropriate and helpful exception is thrown.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "29"
}
|
Q: How to populate the pull down menu? I'm trying to populate the pull down menu. so far ive got:
<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage" %>
<HTML>
<HEAD>
<TITLE>NZ Currency Converter</TITLE>
</HEAD>
<BODY>
<p><tr>
<td colspan="2" align="right"> The other currency is:</td>
<td>
<select name="the other currency is:">
<% List<Currency.Models.exchrate> exchrateList = (List <Currency.Models.exchrate>) ViewData["exchrateList"];
foreach (Currency.Models.exchrate st in exchrateList)
{
%>
<option value="<% Response.Write(st.othercurrency);%>">"<% Response.Write(st.fromnzd);%>">"
<% Response.Write (st.tonzd);%>">
</option>
<% } %>
<option value=""></option>
</select>
</td>
</tr>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Currency.Models;
namespace Currency.Controllers
{
[HandleError]
public class HomeController : Controller
{
public ActionResult Index()
{
financeInit();
return View();
}
public void financeInit()
{
financeEntities db = new financeEntities();
ViewData["exchrate"] = db.exchrates.ToList();
ViewData["Convert From NZD"] = "";
ViewData["Convert To NZD"] = "";
ViewData["You wish to convert"] = "";
ViewData["That will produce"] = "";
}
public ActionResult financeCurrencyConvert()
{
return View();
}
}
}
This is my home controller view currently which is linked to the database from which the pull down menu will be populated. what more can i add to this. i am new to asp.net and not sure how web development works so any help will be appreciated. In the pulldown menu instead of countries im getting their conversion rates. can anyone help with how to change this to select as countries
A: The issue is that you are using different view data keysin controller and view ("The Other Currency is:" in controller and "exchrateList" in view). Match them and you should be ok - for example, change this line from controller
ViewData["The Other Currency is:"] = db.exchrates.ToList();
to
ViewData["exchrateList"] = db.exchrates.ToList();
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: HTTP response code after redirect There is a redirect to server for information and once response comes from server, I want to check HTTP code to throw an exception if there is any code starting with 4XX. For that I need to know how can I get only HTTP code from header? Also here redirection to server is involved so I afraid curl will not be useful to me.
So far I have tried this solution but it's very slow and creates script time out in my case. I don't want to increase script time out period and wait longer just to get an HTTP code.
Thanks in advance for any suggestion.
A: Your method with get_headers and requesting the first response line will return the status code of the redirect (if any) and more importantly, it will do a GET request which will transfer the whole file.
You need only a HEAD request and then to parse the headers and return the last status code. Following is a code example that does this, it's using $http_response_header instead of get_headers, but the format of the array is the same:
$url = 'http://example.com/';
$options['http'] = array(
'method' => "HEAD",
'ignore_errors' => 1,
);
$context = stream_context_create($options);
$body = file_get_contents($url, NULL, $context);
$responses = parse_http_response_header($http_response_header);
$code = $responses[0]['status']['code']; // last status code
echo "Status code (after all redirects): $code<br>\n";
$number = count($responses);
$redirects = $number - 1;
echo "Number of responses: $number ($redirects Redirect(s))<br>\n";
if ($redirects)
{
$from = $url;
foreach (array_reverse($responses) as $response)
{
if (!isset($response['fields']['LOCATION']))
break;
$location = $response['fields']['LOCATION'];
$code = $response['status']['code'];
echo " * $from -- $code --> $location<br>\n";
$from = $location;
}
echo "<br>\n";
}
/**
* parse_http_response_header
*
* @param array $headers as in $http_response_header
* @return array status and headers grouped by response, last first
*/
function parse_http_response_header(array $headers)
{
$responses = array();
$buffer = NULL;
foreach ($headers as $header)
{
if ('HTTP/' === substr($header, 0, 5))
{
// add buffer on top of all responses
if ($buffer) array_unshift($responses, $buffer);
$buffer = array();
list($version, $code, $phrase) = explode(' ', $header, 3) + array('', FALSE, '');
$buffer['status'] = array(
'line' => $header,
'version' => $version,
'code' => (int) $code,
'phrase' => $phrase
);
$fields = &$buffer['fields'];
$fields = array();
continue;
}
list($name, $value) = explode(': ', $header, 2) + array('', '');
// header-names are case insensitive
$name = strtoupper($name);
// values of multiple fields with the same name are normalized into
// a comma separated list (HTTP/1.0+1.1)
if (isset($fields[$name]))
{
$value = $fields[$name].','.$value;
}
$fields[$name] = $value;
}
unset($fields); // remove reference
array_unshift($responses, $buffer);
return $responses;
}
For more information see: HEAD first with PHP Streams, at the end it contains example code how you can do the HEAD request with get_headers as well.
Related: How can one check to see if a remote file exists using PHP?
A: Something like:
$ch = curl_init();
$httpcode = curl_getinfo ($ch, CURLINFO_HTTP_CODE );
You should try the HttpEngine Class.
Hope this helps.
--
EDIT
$ch = curl_init();
curl_setopt($ch, CURLOPT_USERAGENT, $your_agent_variable);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_REFERER, $your_referer);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($httpcode ...)
A: The solution you found looks good. If the server is not able to send you the http headers in time your problem is that the other server is broken or under very heavy load.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566225",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: jQuery hide if clicked outside the button I want to show a paragraph by clicking on the button with the jQuery. But when it is visible, then I want to hide it by clicking anywhere else than the button (ie. anywhere outside the button).
For example, here is my code:
<p style="display: none">Hello world</p>
<button>Say Hello</button>
jQuery:
$("button").click(function () {
$("p").show();
});
here is jsfiddle link:
http://jsfiddle.net/k9mUL/
How can I hide it by clicking outside the button? Thanks
A: You could bind a click event handler to the document, as well as the one on the button. In that event handler, hide the p element:
$("button").click(function (e) {
$("p").show();
e.stopPropagation();
});
$(document).click(function() {
$("p").hide();
});
You need to stop the propagation of the click event in the button click event, otherwise it will bubble up to the document and the p element will be hidden again straight away.
Here's a working example.
A: You can take advantage of event bubbling by binding your handler to the click event of the document and using event.target to determine if the user clicked the button or something else in the document:
$(document).click(function(event) {
if ($(event.target).is("button")) {
$("p").show();
} else {
$("p").hide();
}
});
A: Although doing it manually is great, there is a plugin which allows you to add this functionality of it helps you:
http://benalman.com/projects/jquery-outside-events-plugin/
A: You can bind an event handler to the click event on the whole document and check if the targeted element is not a button:
$(document).click(function(e){
if(e.target.nodeName.toLowerCase() != 'button')
$('p').hide();
});
Or here's a more "jquery" way :
$(document).click(function(e){
if(!$(e.target).is('button'))
$('p').hide();
});
Live DEMO.
A: <p style="display: none">Hello world</p>
<button onclick='show(event);'>Say Hello</button>
function show(e){
$("p").show();
e.cancelBubble = true;
document.addEventListener('click',hide,false);
}
function hide(){
$("p").hide();
document.removeEventListener('click',hide,false);
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: Virtual Path Issue Hello Code Experts,
I am uploading some files to a virtual directory. For the virtual directory I am giving the path like
"/Uploads/" + DatabaseName + "/" + REOID + "/" + "ExternalDocument" + "/";
It works fine in my local but not in live server. It is not uploading files in live server.
If I change it to
"~/Uploads/" + DatabaseName + "/" + REOID + "/" + "ExternalDocument" + "/";
Then will it work? If not then how shall I map it to virtual directory?
A: use the Server.MapPath function
http://msdn.microsoft.com/en-us/library/system.web.httpserverutility.mappath.aspx
Server.MapPath("~/Uploads/" + DatabaseName + "/" + REOID + "/" + "ExternalDocument" + "/");
A: Read the documentation on waht the ~ means. You willfind ou tthe second approach is always valid, the first one not. Te first assuems the folder is /Uploads (at the web server root).
A: +1 to @MarkisT. Would suggest you also let the Framework do the combination for you:
http://msdn.microsoft.com/en-us/library/dd782933.aspx
using System.IO;
using System.Web;
var path = Path.Combine("~/Uploads", DataBaseName, REOID, "ExternalDocument");
var fullPath = Server.MapPath(path);
If you are still having issues; would suggest you inspect fullPath on local and server to understand what is happening as relates to virtual and absolute paths. You may also have security issues on the server, especially if you happen to be writing outside the application directory. Of course, would expect exceptions in that case.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566232",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHPExcel: Date formatting difference between 1.7.4 and 1.7.6 I've two different results with the same code between two PHPExcel versions (same server, same code, same data). I've tried two ways to write in the cell, same behaviour.
PHPExcel_Cell::setValueBinder( new PHPExcel_Cell_AdvancedValueBinder() );
$sheet->getStyleByColumnAndRow($col,$i)->getAlignment()->setHorizontal(PHPExcel_Style_Alignment::HORIZONTAL_CENTER);
$sheet->setCellValueByColumnAndRow($col,$i,$myDate->format('Y-m-d'));
//Or this line:
//$sheet->setCellValueByColumnAndRow($col,$i,PHPExcel_Shared_Date::stringToExcel($myDate->format('Y-m-d')));
$sheet->getStyleByColumnAndRow($col,$i)->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_DATE_YYYYMMDDSLASH);
In 1.7.4 --> dd/mm/YYYY that's what i want
In 1.7.6 --> YY/m/d uglyy !!!!
What's wrong with my code ?
Thanks for your help
S.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566236",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to make css a:active work after the click? I am trying to make a menu working as tabs. The tabs themselves are working fine and the menu links are great aswell.. But I'd like to remove the buttom border of the active tab, to make it look like you're on that actual page. I've tried using #id a:active but it seems to work only as long as I press the link. I've had the though about doing it by javascript aswell, but I can't seem to figure out a way to do it. Here's my css for active.
CSS: (please let me know if you'll need more of my css)
#navigation a:active {
color: #000;
background: -webkit-gradient(linear, left top, left bottom, from(#DFE7FA), to(#FFF));
border-bottom-width:0px;
}
Thanks,
/Pyracell
A: Add and remove a class when you select a tab link..
#navigation .active {
color: #000;
background: -webkit-gradient(linear, left top, left bottom, from(#DFE7FA), to(#FFF));
border-bottom-width:0px;
}
and use the script (jQuery version)
$(function(){
$('#navigation a').click(function(){
$('#navigation .active').removeClass('active'); // remove the class from the currently selected
$(this).addClass('active'); // add the class to the newly clicked link
});
});
A: From your demo link in the comments on another answer, JavaScript will not be of any help, it should be done in your PHP code.
Something in the lines of:
<a <?php if (this_tab_is_selected){ ?>class='active' <?php } ?>href='LINK_TO_TAB' >
TAB_NAME
</a>
Mentioning that changing tabs is redirecting to another page could have helped with better responses from the start xD
Depending on your code and how you are creating the tabs, you need to change the this_tab_is_selected to a code that returns true for the selected tab.
P.S. You still need to make the modification mentioned in the other answer in your CSS. (Which is to change #navigation a:active to #navigation a.active)
A: A crude way to do this with JavaScript (jQuery)
$('a[href]').each(function() {
if ($(this).attr('href') == window.location.pathname || $(this).attr('href') == window.location.href)
$(this).addClass('active');
});
A: How are you implementing the tabs; as multiple different HTML pages? The :active pseudo-class does indeed only apply when a link is 'active', which generally means 'being clicked on'. If you're implementing the tabs as multiple HTML pages, you'll probably want to assign a CSS class like "CurrentTab" to the tab representing the page the user is currently on, and apply your border-bottom-width:0px to that class.
A: the practice which is usually followed is to apply a class to your currently selected tab,e.g. class="selected" and then modify your css to target that class
#navigation a.selected
A: This is not how it works. The :active selector matches (as you noticed) a link that is currently getting clicked (= is active/working). What you want, is a selector for the active page. You will need to use a normal css class there, like this:
#navigation a:active, #navigation a.active {
color: #000;
background: -webkit-gradient(linear, left top, left bottom, from(#DFE7FA), to(#FFF));
border-bottom-width:0px;
}
A: Things like this need to be done with an if statement using code such as PHP.
For example if you click a link you get your new page, set a page variable, something like:
$page = "Home";
Then use an if statement to add or remove extra CSS classes/ids to chnage the style e.g.
if ($page == "home")
{
<a href="home.php" class="active">Home</a>
<a href="about.php">About</a>
}
else if ($page == "About")
{
<a href="home.php">Home</a>
<a href="about.php" class="active">About</a>
}
A: I'm a little late to the party, but I have a simple answer using css only. Give each page a unique id, give each menu item a unique id (or class in this case), style your links as you like for when you are not on the page, then style them as you want them if you are on the page. The css matches when you click on the menu item and it loads the page. So whatever page you are on, the menu item appears "active". Below I have it to where the current page menu button text changes color but you can use the visible property to show and hide images or use any css to style it. (Also in this example is css to change things on hover too.) In addition, this method allows you to write separate css for each menu button, so each menu button can do something different than the others if you wish.
#menu {
padding-top: .5em;
text-align: center;
font-family: 'Merriweather Sans';
font-size: 1.25em;
letter-spacing: 0;
font-weight: 300;
color: #003300;
}
#menu a {
text-decoration: none;
color: #003300;
}
#menu a:visited {
color: #003300;
}
#menu a:hover {
font-style: italic;
}
#home a.home,
#about a.about,
#edc a.edc,
#presentations a.presentations,
#store a.store,
#contact a.contact {
font-weight: 800;
color: #660000;
}
#home a.home:hover,
#about a.about:hover,
#edc a.edc:hover,
#presentations a.presentations:hover,
#store a.store:hover,
#contact a.contact:hover
{
font-style: normal;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566238",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: How to Annotate Index on a MappedSuperclass I have a mapped superclass with two already indexed properties. now i want to create a group index over both properties. until now it worked with:
@MappedSuperclass
Class A {
@Index(name="pa")
int a;
@Index(name="pb")
int b;
}
According to the hibernate documentation i could annotate my new index with @Table (hibernate annotation). but i dont know what to set for the required appliesTo parameter.
has anybody tried this successfully before?
A: From Hibernate Documentation:
@Table(appliesTo="tableName", indexes = { @Index(name="index1",
columnNames={"column1", "column2"} ) } ) creates the defined indexes
on the columns of table tableName. This can be applied on the primary
table or any secondary table.
Update:
For the @MappedSuperclass you could try to use @Tables annotation
@Tables(value={@Table(appliesTo="table1", indexes={@Index(name="index1", columnNames={"column1", "column2"})}),
@Table(appliesTo="table2", indexes={@Index(name="index1", columnNames={"column1", "column2"})})})
But that seems rather tedious.
Note that, @Index annotation has columnNames property, which allows you to specify more than one column. However, I'm not sure whether you should duplicate index definition for each field.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566246",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Divide files depending on X and put into individual folder How do I create a script in a command prompt (or shell script in a bash) to divide files depending on a number, say X, and put into individual folder.
Example: I have 10 files and the number X is 4 (I can set it inside the script). So, the system will create 3 folders (1st folder contain 4 files, 2nd folder contain 4 files and the last folder will contain the remaining 2 files) after running the script.
Regarding about the divide of the files. It can be either go by the date or the filename.
Example: Suppose the 10 files above is a.txt, aa.txt, b.txt, cd.txt, ef.txt, g.txt, h.txt, iii.txt, j.txt and zzz.txt. After running the script, it will create the 3 folders such that the 1st folder contain a.txt, aa.txt, b.txt, cd.txt, the 2nd folder contains ef.txt, g.txt, h.txt, iii.txt and the last folder will contain the remaining files - j.txt and zzz.txt
A: Based on your description, an awk one liner could achieve your goal.
check the example below, you can change "4" in xargs -n parameter with your X:
kent$ l
total 0
-rw-r--r-- 1 kent kent 0 2011-09-27 11:04 01.txt
-rw-r--r-- 1 kent kent 0 2011-09-27 11:04 02.txt
-rw-r--r-- 1 kent kent 0 2011-09-27 11:04 03.txt
-rw-r--r-- 1 kent kent 0 2011-09-27 11:04 04.txt
-rw-r--r-- 1 kent kent 0 2011-09-27 11:04 05.txt
-rw-r--r-- 1 kent kent 0 2011-09-27 11:04 06.txt
-rw-r--r-- 1 kent kent 0 2011-09-27 11:04 07.txt
-rw-r--r-- 1 kent kent 0 2011-09-27 11:04 08.txt
-rw-r--r-- 1 kent kent 0 2011-09-27 11:04 09.txt
-rw-r--r-- 1 kent kent 0 2011-09-27 11:04 10.txt
kent$ ls|xargs -n4|awk ' {i++;system("mkdir dir"i);system("mv "$0" -t dir"i)}'
kent$ tree
.
|-- dir1
| |-- 01.txt
| |-- 02.txt
| |-- 03.txt
| `-- 04.txt
|-- dir2
| |-- 05.txt
| |-- 06.txt
| |-- 07.txt
| `-- 08.txt
`-- dir3
|-- 09.txt
`-- 10.txt
A: #!/usr/bin/env bash
dir="${1-.}"
x="${2-4}"
let n=0
let sub=0
while IFS= read -r file ; do
if [ $(bc <<< "$n % $x") -eq 0 ] ; then
let sub+=1
mkdir -p "subdir$sub"
n=0
fi
mv "$file" "subdir$sub"
let n+=1
done < <(find "$dir" -maxdepth 1 -type f)
Works even when files have spaces and other special characters in their names.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566253",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: set 'secure' flag to JSESSION id cookie I want to set 'secure' flag to JSESSIONID cookie . Is there a configuration in tomcat 6 for this ?
I tried by setting 'secure="true"' in 'Connector' (8080) element of server.xml , but it creates problems ....thats Connection is getting reset .
Note that in my application , the JSESSIONID is getting created in 'http' mode ( index page ) , when the user logins , it will switch into 'https' mode.
A: If you are using tomcat 6 you can do the following workaround
String sessionid = request.getSession().getId();
response.setHeader("SET-COOKIE", "JSESSIONID=" + sessionid + "; secure ; HttpOnly");
see https://www.owasp.org/index.php/HttpOnly for more information
A: use the attribute useHttpOnly="true". In Tomcat9 the default value is true.
A: For nginx proxy it could be solved easy in nginx config:
if ($scheme = http) {
return 301 https://$http_host$request_uri;
}
proxy_cookie_path / "/; secure";
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566264",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to get val from fileds inside table inside div with JQuery Can somebody help me how to collect data from input fields from tbl_number in one array array_tbl[number] and object_number in other arrays_object[number] with JQuery when HTML looks like
<div id="devices" style="width:95%;">
<div id="device_1" style="background-color:#858585;">
<table id="tbl_device_1">
<tbody>
<tr>
<th>Slave</th>
<th>Instance</th>
<th>Object Name</th>
<th>Model Name</th>
<th>Delete</th>
<th>Add Object</th>
</tr>
<tr>
<td>
<input id="slave_address_1" class="in" type="text"/>
</td>
<td>
<input id="instance_1" class="in" type="text"/>
</td>
<td>
<input id="object_name_1" class="in" type="text"/>
</td>
<td>
<input id="model_name_1" class="in" type="text"/>
</td>
<td>
<input class="btn_del" type="button" onclick="$('#device_1').remove();" title="Delete"/>
</td>
<td>
<input class="btn_add" type="button" onclick="add_object_row(1);" title="Add new object" style="float:none;"/>
</td>
</tr>
</tbody>
</table>
<br>
<div id="device_objects_1" style="width:100%;">
<table id="object_1" style="margin-left:30px;">
<tbody>
<tr>
<th>Type</th>
<th>Instance</th>
<th>Object Name</th>
<th>Val Type</th>
<th>Position</th>
<th>Units</th>
<th>Quot</th>
<th>Shift</th>
<th>Delete</th>
</tr>
<tr>
<td>
<input id="type_1" class="in_short" type="text"/>
</td>
<td>
<input id="instance_1" class="in_short" type="text"/>
</td>
<td>
<input id="object_name_1" class="in_short" type="text"/>
</td>
<td>
<input id="val_type_1" class="in_short" type="text"/>
</td>
<td>
<input id="position_1" class="in_short" type="text"/>
</td>
<td>
<input id="units_1" class="in_short" type="text"/>
</td>
<td>
<input id="quot_1" class="in_short" type="text"/>
</td>
<td>
<input id="shift_1" class="in_short" type="text"/>
</td>
<td>
<input class="btn_del" type="button" onclick="$('#object_1').remove();"/>
</td>
</tr>
</tbody>
</table>
<table id="object_1" style="margin-left:30px;">
<tbody>
<tr>
<th>Type</th>
<th>Instance</th>
<th>Object Name</th>
<th>Val Type</th>
<th>Position</th>
<th>Units</th>
<th>Quot</th>
<th>Shift</th>
<th>Delete</th>
</tr>
<tr>
<td>
<input id="type_2" class="in_short" type="text"/>
</td>
<td>
<input id="instance_2" class="in_short" type="text"/>
</td>
<td>
<input id="object_name_2" class="in_short" type="text"/>
</td>
<td>
<input id="val_type_2" class="in_short" type="text"/>
</td>
<td>
<input id="position_2" class="in_short" type="text"/>
</td>
<td>
<input id="units_2" class="in_short" type="text"/>
</td>
<td>
<input id="quot_2" class="in_short" type="text"/>
</td>
<td>
<input id="shift_2" class="in_short" type="text"/>
</td>
<td>
<input class="btn_del" type="button" onclick="$('#object_1').remove();"/>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div id="device_6" style="background-color:#C2C2C2;">
<table id="tbl_device_6">
<tbody>
<tr>
<th>Slave</th>
<th>Instance</th>
<th>Object Name</th>
<th>Model Name</th>
<th>Delete</th>
<th>Add Object</th>
</tr>
<tr>
<td>
<input id="slave_address_6" class="in" type="text"/>
</td>
<td>
<input id="instance_6" class="in" type="text"/>
</td>
<td>
<input id="object_name_6" class="in" type="text"/>
</td>
<td>
<input id="model_name_6" class="in" type="text"/>
</td>
<td>
<input class="btn_del" type="button" onclick="$('#device_6').remove();" title="Delete"/>
</td>
<td>
<input class="btn_add" type="button" onclick="add_object_row(6);" title="Add new object" style="float:none;"/>
</td>
</tr>
</tbody>
</table>
<br>
<div id="device_objects_6" style="width:100%;">
<table id="object_6" style="margin-left:30px;">
<tbody>
<tr>
<th>Type</th>
<th>Instance</th>
<th>Object Name</th>
<th>Val Type</th>
<th>Position</th>
<th>Units</th>
<th>Quot</th>
<th>Shift</th>
<th>Delete</th>
</tr>
<tr>
<td>
<input id="type_3" class="in_short" type="text"/>
</td>
<td>
<input id="instance_3" class="in_short" type="text"/>
</td>
<td>
<input id="object_name_3" class="in_short" type="text"/>
</td>
<td>
<input id="val_type_3" class="in_short" type="text"/>
</td>
<td>
<input id="position_3" class="in_short" type="text"/>
</td>
<td>
<input id="units_3" class="in_short" type="text"/>
</td>
<td>
<input id="quot_3" class="in_short" type="text"/>
</td>
<td>
<input id="shift_3" class="in_short" type="text">
</td>
<td>
<input class="btn_del" type="button" onclick="$('#object_6').remove();"/>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
A: With this code u can get values of inputs that has class 'in' to in array_tbl array
var array_tbl = []
$('.in').each(function(){
array_tbl.push($(this).val())
})
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566267",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to put line break in excel sheet cell I've so many rows in database table and i want it to be exported in excel sheet.
My each row represent an individual sale, this sale may contain one or more product and if there is more than one product i'm showing it like this
above image represent my single row that contain more than one product for a sale.
when i convert the whole recode into excel both product code no are shown as a joined string, But i want to put the line break in excel sheet cell. how can i put the line break in excel sheet programmaticaly.
A: You can put line break using \n in excel sheet. if you want to switch to another cell in same row then you can achieve it by ','...
something like this
$data = $row['fname']." ".$row['lname'].",";
$data .= $row['programEnrollments'][0]['startSessionName'].",\n";
A: If you're exporting XML code to generate your Excel file, you would need to use PageBreaks
A: Vikas,
Am I right, that you want to know how to use the replace function with Chr(10)?
Something like:
Application.Calculation = xlCalculationManual
Dim SpecialChar
SpecialChar = Chr(10)
Cells.Replace What:=SpecialChar, Replacement:=" ", SearchOrder:=xlByColumns, MatchCase:=True
Application.Calculation = xlCalculationAutomatic
Regards,
Robert Ilbrink
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566268",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Using var for type declaration instead of explicitly setting interface type I'm not sure if I'm overthinking this but in the past, I've done something like this when declaring a class:
IMyService myService = new MyService();
Jumping into myService will take you to the IMyService interface.
However, doing the following will (obviously) take you to MyService.
var myService = new MyService();
Which is considered the 'correct' usage, or is this another example of "What's your favourite ice cream flavor?"?
I've looked at the most relevant question but it doesn't really answer my scenario.
A: There is also this option ...
var myService = new MyService() as IMyService;
This will make var myVar = IMyService type ... you can then in other code do something like ...
if(myVar is MyService)
{
//instance specific stuff
}
A: Well, it depends. Do all the public members of your MyService class come (exclusively) from the implementation of the IMyService interface? Or there are some extra public members (perhaps from the implementation of another interface)? If so, the second "flavor" will allow you seeing these extra members, while the first one will not.
On the other hand, if you are using interfaces, I would say that the "correct" usage is obtaining the type instances from a dependency injection engine or from some kind of factory class or method, but I guess that's outside the scope of this question.
A: What type do you want myService to be? Do you want it to be an IMyService reference or a MyService reference? Once you make that decision, the rest follows.
In other words, only you can answer the question.
A: It depends on what you mean by correct usage. In the example with an interface you are creating an object of MyService class and storing it into the "pointer" of IMyService class. So your object ius actually an instance of MyService, but your myService var treats it as IMyService interface. So you will not be able to call any methods/access any properties of MyService that are not in IMyService.
With var sample, you are just telling the complier to compute the type of the myService variable from the right side of the declaration. So, in this case it's absolutely identical to MyService myService, that means that you can access all public methods and properties of MyService class via myService variable.
A: I suppose the real question is why you define myService as an interface. It doesn't have much use unless you want to be able to assign other IMyService's to it. In that case you have to define it as an interface.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566271",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Inner join help in mysql SELECT MsgID, Name FROM tbl_message INNER JOIN tbl_user on tbl_message.UserID = tbl_user.UserID WHERE OrgID ='1' order by MsgID
I have a message table
msgid msg userid Orgid
24 Hi 2 1
25 hsa 4 1
User table
userid Name Orgid
2 cas 1
4 asd 1
I want to get the name from user table. I am doing inner join to get it but I am getting error. what is wrong with the query. Error is OrgID is ambiguous
A: It would help if you told us what the error is. Looking at your query, two errors I can see are:
*
*There's a stray comma after SELECT MsgID which should be removed.
*The WHERE OrganisationID ='1' part of the statement seems to reference a column OrganisationID which doesn't exist. Maybe change it to Orgid?
A: You can use the given query:
SELECT message.msg, message.msgid, message.userid,
message.orgid, user.username, user.orgid
FROM user INNER JOIN message
ON user.userid = message.userid
WHERE message.orgid='1'
order by message.msgid
I hope this will help you out.
A: SELECT MsgID FROM tbl_message INNER JOIN tbl_user on tbl_message.UserID = tbl_user.UserID WHERE OrgID ='1' order by MsgID
A: The below code will work, in your code Orgid in where condition is ambigious
SELECT
msgid
FROM
tbl_message
INNER JOIN tbl_user ON tbl_message.UserID = tbl_user.UserID
WHERE
tbl_message.Orgid = 1
AND tbl_user.Orgid = 1
ORDER BY msgid
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566272",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Save File to a remote Url first of all sorry for my english , not my main lang.
I need to export some data to a remote folder from android.
I have a file on android "file.xml" and i need to export it to a folder (under iis)
"http://192.168.x.xx/folder/fileuploaded.txt"
It seems most of the examples out there are using an upload script in php, but i need to do it only from android. Doing the opposite way (from remote url to android app) is easy with Url.openStream(), but i cannot find a working example to put back the file on the server.
Maybe im missing something, this is my first android (and java btw) app.
anyone could point me in the right direction?
Thanks!
A: Diego, what you are trying to achieve is not possible only from Android. You cannot put a file on the server using HTTP unless there is a receiving application running.
You can only post your binary data to the server (url) but to write it locally and make it available on the http again for download, can only be done if you have a server app. It could be created using any language PHP, JSP, ASP etc.
A: You cannot just upload files to server of your wish unless there is something on the server side that allows file uploads. That is usually a ASP/Perl/PHP script.
If you don't want to use such a script, then one way to do this is to run ftp on your server and upload files using that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566278",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: SQL Server: hour and minute average In SQL Server, I have a start time column on a table such as:
2011-09-18 08:06:36.000
2011-09-19 05:42:16.000
2011-09-20 08:02:26.000
2011-09-21 08:37:24.000
2011-09-22 08:22:20.000
2011-09-23 11:58:27.000
2011-09-24 09:00:48.000
2011-09-25 06:51:34.000
2011-09-26 06:09:05.000
2011-09-27 08:25:26.000
...
My question is, how can I get the average hour and minute? I want to know that what is the average start time for this job. (for example 07:22)
I tried something like this but didn't work:
select CAST(AVG(CAST(DATEPART(HH, START_TIME)AS float)) AS datetime) FROM
Thanks.
A: declare @T table(StartTime datetime)
insert into @T values
('2011-09-18 08:06:36.000'),
('2011-09-19 05:42:16.000'),
('2011-09-20 08:02:26.000'),
('2011-09-21 08:37:24.000'),
('2011-09-22 08:22:20.000'),
('2011-09-23 11:58:27.000'),
('2011-09-24 09:00:48.000'),
('2011-09-25 06:51:34.000'),
('2011-09-26 06:09:05.000'),
('2011-09-27 08:25:26.000')
;with C(Sec) as
(
select dateadd(second, avg(datediff(second, dateadd(day, datediff(day, 0, StartTime), 0), StartTime)), 0)
from @T
)
select convert(char(5), dateadd(minute, case when datepart(second, C.Sec) >= 30 then 1 else 0 end, C.Sec), 108)
from C
-----
08:08
A: Try this :
select CAST((SUM(DATEPART(HH, START_TIME) * 60 + DATEPART(MI, START_TIME))/COUNT(*))/60 AS VARCHAR(10)) + ':' + CAST((SUM(DATEPART(HH, START_TIME) * 60 + DATEPART(MI, START_TIME))/COUNT(*))%60 AS VARCHAR(10))
FROM.....
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566284",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: display subsets of vtkPoints using different glyphs I am trying to display some timeseries data in 3D using colormapped values using VTK.
I have a single array of 3D positions for two different kinds of objects, say cones and spheres. These positions are interspersed. I also have a 2D array with timeseries data for these objects. n-th entry in position array correponds to n-th row in timeseries array. (all these are numpy arrays).
Now I want an animated display (using python-vtk) of the cones and the spheres with their colors varying according to the entries in the timeseries array. Currently I made it work by splitting each of the arrays into two - one for cones and one for spheres. But ideally I would like to just pipe cone entries of the position array through a coneGlyph and sphere entries through a sphere glyph and set the timeseries values for all the positions directly. What is the way to do that, if possible at all?
A: I bypassed the issue by storing the indices of the two kinds of objects (i.e., cone_indices and sphere_indices). I also create to vtkPoints objects with the cone positions and the sphere positions. These are used to create the vtkPolyData for the respective classes. In the update method of the timer class, I use these index-arrays to pick up the data for that time point for each type and assign the scalar values to the point data.
conePoints.GetPointData().SetScalars(coneData)
spherePoints.GetPointData().SetScalars(sphereData)
numpy's array lookup using an index-array is fast enough.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566287",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: extjs standardSubmit and grid inside a form problem I'm having some weird issue with extjs. I have a form and a grid, each works great separately but when I put the grid inside the form, everything starts to fall to pieces.
My point by doig so would be to be able to submit ids from rows of the grid and at the same time, stuff from the form.
To do so, I put the standardSubmit to false and added a javascript method to the onSubmit attriobute of my form.
However, when I submit the form this way, I get a weird error :
Uncaught SynthaxError: Unexpected token <
But the form values are submitted and visible in the request's header. Of course, when I put the standard submit to true, the error goes away but the values from the grid are not submitted anymore...
A: This SyntaxError usually relates to a loaded JavaScript resource. These are common mistakes that can trigger this error message:
<script type="text/javascript">
<script type="text/javascript">
[...]
</script>
</script>
<script type="text/javascript">
var s = I forgot the opening quotes so this <html> tag will break the script';
</script>
<script type="text/javascript"
var s = 'Here we forgot to close the opening <script> tag! Boom!';
</script>
It could also be triggered by the server setting the content type to 'application/javascript' for a non-JS resource (which then again includes this tags).
I also remember reading that this happened to someone using a minified version of a JavaScript library, but no details on the exact reason were given (other than that the problem was solved by using the non-minified version.
You can also wrap your JS resources in a CDATA tag for debugging purposes which should get rid of the SyntaxError and probably bring up a standard JS error message for the invalid script.
<script><![CDATA[
/* Code here */
]]></script>
Once you identify the resource that triggers the exception it should be possible to spot the problem by doing a through study of the source with your CSI sunglasses on.
Note: my assumption is that it can*not* be triggered by data that is sent to the server, but only data that is returned from the server. This is because the error refers to the parsing process on the client. But I'm not 100% sure on this one.
If this doesn't help you should really post the involved code and/or explain what you do exactly when you 'added a javascript method to the onSubmit attribute of [your] form'.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566296",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error when Joining table I am getting the error, Incorrect syntax near the keyword 'WHERE'
All i want to do is use some columns from another table
SELECT unitCode, studentID, s.studentFName
FROM Student As S Right outer Join
(SELECT unitCode, studentID,
SUM(CASE WHEN subStatus = 'Yes' THEN 1 ELSE 0 END) AS CountYes,
SUM(CASE WHEN subStatus = 'No' THEN 1 ELSE 0 END) AS CountNo
FROM Assignment
GROUP BY unitCode, studentID)
WHERE (CountNo > 0) AND (CountYes = 0) AND s.studentID = assignment.studentID
A: Your join is missing its ON clause and the subselect is missing the alias:
SELECT
unitCode, studentID, s.studentFName
FROM
Student As S
Right outer Join
(
SELECT
unitCode, studentID,
SUM(CASE WHEN subStatus = 'Yes' THEN 1 ELSE 0 END) AS CountYes,
SUM(CASE WHEN subStatus = 'No' THEN 1 ELSE 0 END) AS CountNo
FROM
Assignment
GROUP BY unitCode, studentID
) as assignment
on s.studentID = assignment.studentID
WHERE
(CountNo > 0) AND (CountYes = 0)
;
A: Subselects must have an alias in SQL Server.
Change this:
OUTER JOIN (SELECT ...)
to this:
OUTER JOIN (SELECT ...) T1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566300",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: Start a specific part of an application only one time after installation On my app I've got a Database which i have to fill one time with some entries. I have packed this step in my splashscreen. Now I got the problem every time i open up my application it puts again all entries to my database.
I'm looking for a way to let this happen only on the really first time the app gets opend. But i don't find out, how i can realize this.
I'm happy over every input and Idea!
Have a nice day
safari
Notes
I had an idea to realize that. I make a boolean in my SplashScreen, which takes a look at the database table if there is nothin, it inputs all the entries and makes a mark in a table that its filled like yes.
Afterwards if i open the app again it takes a look at the database if theres a yes or what ever i definied, it doesn't put again all entries in my database.
Sorry for that crappy definition of what my idea is, my english isnt the best.
I'm searching for an easier way than this.
A: why not have a startup activity that checks if the app is launched for the first time ( and stores the value in the app preferences ) and either forwards to the database setup activity or to the main activity....
Here's a sample on how to read and write to the preferences:
Define preference key:
public static final String KEY_APP_IS_INITIALIZED = "APP_INITIALIZED";
read boolean value from preferences:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context)
boolean appIsInitialized = prefs.getBoolean(KEY_APP_IS_INITIALIZED, false);
store boolean value to preferences:
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context)
Editor editor = prefs.edit();
editor.putBoolean(KEY_APP_IS_INITIALIZED, true);
editor.commit();
Launching the activities:
Intent intent = new Intent(startup_activity,
db_initialized ?
MainActivity.class :
DbInitActivity.class);
startup_activity.startActivity(intent);
A: You could use SharedPreferences to store a boolean value which indicates if the database is already filled.
You can store the data using this code:
SharedPreferences pref = getPreferences(MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
editor.putBoolean(key, value);
editor.commit();
and then when you start the application you just read your value using:
SharedPreferences pref = getPreferences(MODE_PRIVATE);
pref.getBoolean(value, false);
A: // Check if DB is set up on start
SharedPreferences settings = getSharedPreferences("yourappidentifiername",MODE_PRIVATE);
String DbSetUp = settings.getString("dbsetup", "no");
// DbSetUp is "no" or "yes"
// Set that DB is set up
SharedPreferences settings = getSharedPreferences("yourappidentifiername",MODE_PRIVATE);
SharedPreferences.Editor editor = settings.edit();
editor.putString("dbsetup", "yes");
editor.commit();
A: Not an optimal solution, but you could check for one of your entries, if they don't exist, add them to your DB, otherwise ignore them.
A: Try this....
Have one bool value in shared preferences.
Check that variable is set or not on each start of the application.
if not set then set it and perform db operation.
if set don't do db operation just go to next steps.
A: I've got an idea, reading other answers.
Use a version for the database to write in the sharedpreference, so next time you'll need to update the database, just delete the old one and refill the new one with you data.
public void populateResDB(int version){
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int resDbVersion = prefs.getInt("ResDBVersion", 1);
if(resDbVersion<version){
//Populate database here
//Delete table/db
//Populate the table/database with new or updated data
//Update ResDBVersion for the next time
Editor editor = prefs.edit();
editor.putInt("ResDBVersion", version);
editor.commit();
}else{
//installed db has the same version as the one we want to install
//so, do nothing.
}
}
I'm trying it now, not yet tested.
In the onCreate of the splash activity use:
populateResDB(1); //1 is for the first time, increase it manually
A: You can use method onCreate in your database helper - it's used only, when new database is created, so I think that is what you're looking for.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566324",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to connect to a Sybase Database using Android? I want to use data, and put data, in a sybase database using android.
How can I access it?
A: http://iablog.sybase.com/mobiledatabase/2011/05/database-programming-on-android-with-ultralite/
I think this has some nice information on how to do it. Hope it helps!
Assuming you've got the JAR file (as the tutorial says) you can do this.
import java.util.Random;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.ianywhere.ultralitejni12.*;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try{
// Define the database properties using a Configuration object
ConfigFileAndroid config = DatabaseManager.createConfigurationFileAndroid("hello.udb", this);
// Connect, or if the database does not exist, create it and connect
try{
_conn = DatabaseManager.connect(config);
} catch ( ULjException e) {
_conn = DatabaseManager.createDatabase(config); �
}
// Create a table T1 in the database if it does not exist
StringBuffer sb = new StringBuffer();
sb.append("CREATE TABLE IF NOT EXISTS T1 (C1 integer primary key default autoincrement, C2 integer )");
PreparedStatement ps = _conn.prepareStatement(sb.toString());
ps.execute();
ps.close();
// Insert a row into T1
sb = new StringBuffer("INSERT INTO T1 (C2) ON EXISTING SKIP VALUES ( ? )");
ps = _conn.prepareStatement(sb.toString());
ps.set(1, new Random().nextInt());
ps.execute();
ps.close();
_conn.commit();
// Select the values from C2 and show them in the user interface
sb = new StringBuffer("SELECT C2 FROM T1");
ps = _conn.prepareStatement(sb.toString());
ResultSet rs = ps.executeQuery();
StringBuffer c2 = new StringBuffer();
while(rs.next()){
c2.append(String.valueOf(rs.getInt(1)));
c2.append(",");
}
TextView tv = (TextView)findViewById(R.id.textview1);
tv.setText(c2.toString());
} catch ( ULjException e) {
Log.e("HelloUltraLite", e.toString());
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566332",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Implement ELSE expression from SQL data, is it possible? Suppose there're 2 tables with data like below:
-- Table #Detail
TelNO
----------
001xxxxx
020xxxxx
021xxxxx
800xxxxx
400xxxxx
28011111
82188888
22223333
...
...
-- Table #FeeRate
Expression Price Description
---------- ------- --------------------------------------------------
001% 10.00 International call
0[^0]% 5.00 National call
800% .00 Free call
400% .80 800 like, but caller need pay for local part
ELSE,How? .20 Others/Local call
I want to select data from the 2 tables JOINed on dbo.FUNCTION_Match (TelNO, Expression) condition. (dbo.FUNCTION_Match is a crude function i wroted to match TelNO and Expression. In this sample, you can treat it as TelNO LIKE Expression).
So the SQL & query result is
SELECT * FROM #Detail d
LEFT JOIN #FeeRate f ON d.TelNO LIKE f.Expression
TelNO Expression Price Description
---------- ---------- ------- --------------------------------------------------
001xxxxx 001% 10.00 International call
020xxxxx 0[^0]% 5.00 National call
021xxxxx 0[^0]% 5.00 National call
800xxxxx 800% .00 Free call
400xxxxx 400% .80 800 like, but caller need pay for local part
28011111 NULL NULL NULL
82188888 NULL NULL NULL
22223333 NULL NULL NULL
The problem is clear, those local calls in #Detail can't matched Others FeeRate.
My crude FUNCTION_Match function has handled multi-expressions like TelNO NOT LIKE '0%' AND TelNO NOT LIKE [84]00% OR TelNO LIKE '0755%' to match Others FeeRate, but it's hard to write a correct multi-expression to express ELSE when there're many records in #FeeRate table.
So, is there a way to implement ELSE expression from data ?
SQLs to create sample data
CREATE TABLE #Detail (TelNO VARCHAR(10) DEFAULT '')
CREATE TABLE #FeeRate (Expression VARCHAR(20) DEFAULT '', Price NUMERIC(10,2) DEFAULT 0, Description VARCHAR(50) DEFAULT '')
INSERT INTO #Detail VALUES ('001xxxxx')
INSERT INTO #Detail VALUES ('020xxxxx')
INSERT INTO #Detail VALUES ('021xxxxx')
INSERT INTO #Detail VALUES ('800xxxxx')
INSERT INTO #Detail VALUES ('400xxxxx')
INSERT INTO #Detail VALUES ('28011111')
INSERT INTO #Detail VALUES ('82188888')
INSERT INTO #Detail VALUES ('22223333')
INSERT INTO #FeeRate VALUES ('001%', 10.0, 'International call')
INSERT INTO #FeeRate VALUES ('0[^0]%', 5.0, 'National call')
INSERT INTO #FeeRate VALUES ('800%', 0.0, 'Free call')
INSERT INTO #FeeRate VALUES ('400%', 0.8, '800 like, but caller need pay for local part')
INSERT INTO #FeeRate VALUES ('ELSE,How?', 0.2, 'Others/Local call')
SELECT * FROM #Detail
SELECT * FROM #FeeRate
SELECT
*
FROM
#Detail d
LEFT JOIN #FeeRate f ON d.TelNO LIKE f.Expression
DROP TABLE #Detail
DROP TABLE #FeeRate
A: Add an extra column to your FeeRate table, called Priority. Assign higher priorities to the matches that should occur "earlier". Do two joins to the fee rate table, the second being a left join, and looking for a higher priority match. If the left join works, reject the result row:
CREATE TABLE #FeeRate (Expression VARCHAR(20) DEFAULT '', Price NUMERIC(10,2) DEFAULT 0, Description VARCHAR(50) DEFAULT '',Priority int)
INSERT INTO #FeeRate VALUES ('001%', 10.0, 'International call',5)
INSERT INTO #FeeRate VALUES ('0[^0]%', 5.0, 'National call',4)
INSERT INTO #FeeRate VALUES ('800%', 0.0, 'Free call',3)
INSERT INTO #FeeRate VALUES ('400%', 0.8, '800 like, but caller need pay for local part',2)
INSERT INTO #FeeRate VALUES ('%', 0.2, 'Others/Local call',1)
SELECT * FROM #Detail d
inner JOIN #FeeRate f ON d.TelNO LIKE f.Expression
left join #FeeRate f_anti on d.TelNo LIKE f_anti.Expression and f_anti.Priority > f.Priority
where
f_anti.Price is null
This probably allows you to simplify some of your other expressions also.
A: If there is only one "other" category, store its values in variables and substitute them in when there is no match using ISNULL:
DECLARE @expression VARCHAR(20), @price NUMERIC (10,2), @description VARCHAR(50)
SELECT @expression = Expression, @price = Price, @description = [Description]
FROM #FeeRate
WHERE Expression = 'ELSE,How?'
SELECT d.TelNO, ISNULL(f.Expression, @expression) AS Expression,
ISNULL(f.Price, @price) AS Price,
ISNULL(f.[Description], @description) AS [Description]
FROM
#Detail d
LEFT JOIN #FeeRate f ON d.TelNO LIKE f.Expression
A: I don't know for sure what data you are having in #Detail table, but for the above data you can do something like this:
SELECT * FROM
#Detail d
LEFT JOIN #FeeRate f ON
(CASE
WHEN d.TelNO LIKE '%xxxxx' THEN TelNO
ELSE 'ELSE,How?'
END) LIKE f.Expression
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566338",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: NSPredicate for max(arrayOfNSDates) I got problem with NSPredicate.
I got some engine where the predicates are constructed from a definition coming from a web service.
I use somethning like that:
[NSPredicate predicateWithFormat:@"max({1,2,3})==3"]
it's great, but I need max function for NSDate objects.
Here http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSExpression_Class/Reference/NSExpression.html#//apple_ref/doc/uid/TP30001190 is wrote that max() function can get only array containings objects representing numbers.
Is there any solution to use this function for that (override some method, create some category for NSPredicate)
Thanks in advance.
A: OK, this is possible, but it's weird. We'll have to build the format string programmatically. Alternatively, we could built it all by creating the individual NSExpression objects, but that'd be a lot more code (albeit likely safer, but whatever).
NSDate *maxDate = ...;
NSArray *arrayOfDates = ...; // an NSArray of NSDate objects
NSMutableArray *dateFormats = [NSMutableArray array];
for (NSDate *date in arrayOfDates) {
NSString *format = [NSString stringWithFormat:@"%f", [date timeIntervalSinceReferenceDate]];
[dateFormats addObject:format];
}
NSString *dateFormatString = [dateFormats componentsJoinedByString:@","];
NSString *format = [NSString stringWithFormat:@"CAST(max({%@}) = %%@, 'NSDate')", dateFormatString];
// format now looks like CAST(max({xxxx.xxxx, nnnn.nnnn, aaaa.aaaa, ....}), 'NSDate') = %@
NSPredicate *datePredicate = [NSPredicate predicateWithFormat:format, maxDate];
The trick here is to use the date's absolute time interval since the reference date as the arguments to the max() function, and then turn the result of that back into a date by using CAST(). More info on how to use the CAST() function with dates can be found in this blog post.
A: This solutions is realy good, but don't solve my problem.
I got something like this:
NSPredicate* predicate = [NSPredicate predicateWithFormat: condition];
[predicate evaluateWithObject:nil substitutionVariables: currentForm];
And condition can be:
max($widgetWhichReturnDate.result.result,$widgetWhichReturnDate.result)
or
max($widgetWhichReturnInt.result,$widgetWhichReturnInt1.result)
what widget is used here depends from webservice.
So I don't like to use different functions for Date and int (or in the future maybe float, double etc)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566339",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: On top datagridview I have 4 datagridviews.
based on user's selection I'll bring on of them to front.
I have a button that use top datagridview for calculating something.
How can I recognize which datagridview is on top?
A: Use .Visible = true; or .Visible = false; Property to either hide or show your current grid, thus you can identify which one is on top by checking the .Visible
foreach(Control c in this.Controls)
{
if (c is DataGridView && c.Visible)
{
//Do your logic here
}
}
A: take a global variable. when you move first datagrid then set value of global variable to 'one'(or any other so you can identify that this is first datagrid) and for second datagrid 'two' like for other datagrids also. While calculation based on the variable value you can do appropriate actions
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566340",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Make Search and Archives match homepage I have my homepage http://www.faberunashop.com set up as a directory. When you click on the post image, it takes you over to the artists site. Here is the code that I used to make this happen by adding it to the functions.php:
function print_post_title() {
global $post;
$thePostID = $post->ID;
$post_id = get_post($thePostID);
$title = $post_id->post_title;
$perm = get_permalink($post_id);
$post_keys = array(); $post_val = array();
$post_keys = get_post_custom_keys($thePostID);
if (!empty($post_keys)) {
foreach ($post_keys as $pkey) {
if ($pkey=='url1' || $pkey=='title_url' || $pkey=='url_title') {
$post_val = get_post_custom_values($pkey);
}
}
if (empty($post_val)) {
$link = $perm;
} else {
$link = $post_val[0];
}
} else {
$link = $perm;
}
echo '<h2><a href="'.$link.'" rel="bookmark" title="'.$title.'">'.$title.'</a></h2>';
}
Now I want to do the same to my search and archive page. What do I adjust to make them behave the same?
A: I suppose that you use WordPress.
In that case you can change the layout and the behavior of your search results by creating a file with name search.php into your theme for your search results, and another file for archives that called archives.php.
For more information about Template Hierarchy for WordPress you can find here http://codex.wordpress.org/Template_Hierarchy
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566341",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: TortoiseHg 'No space left on device' error while pushing We are using TortoiseHg as our Mercurial client UI. Today we ran into an issue while trying to push from one particular workstation. It was receiving the following error:
abort: No space left on device
[command returned code 255 ..........]
This error occurs while TortoiseHg/Mercurial is bundling files in preparation to pushing to the repository. I did some testing and noticed that the workstations (C:) drive was gradually being filled up as the file were being bundled. The (C:) drive went from ~900MB to ~100MB and then the error message was received. So this is obviously the cause.
My question is this:
*
*Does anyone know which default directory is used to store the temp files created while TortoiseHg/Mercurial bundles files in prep for a push? This seems to be independent of the drive TortoiseHg is installed to. I re-installed to a data drive with plenty of space and still used (C:) to store whatever temp files it was using.
*Is there a way to configure TortoiseHg/Mercurial to use a temp directory of your choice?
Thanks in advance for any help!
A: Mercurial is python and python has good platform specific defaults for temporary file locations. They're pretty easily overridden if you want something other than the defaults, which on Windows are probably c:\temp.
http://docs.python.org/library/tempfile.html#tempfile.tempdir says it's:
*
*The directory named by the TMPDIR environment variable.
*The directory named by the TEMP environment variable.
*The directory named by the TMP environment variable.
*A platform-specific location:
*
*On RiscOS, the directory named by the Wimp$ScrapDir environment variable.
*On Windows, the directories C:\TEMP, C:\TMP, \TEMP, and \TMP, in that order.
*On all other platforms, the directories /tmp, /var/tmp, and /usr/tmp, in that order.
*As a last resort, the current working directory.
So if you've got software using Mercurial on a client computer set the environment variable to some place you know has space.
A: Mercurial always stores internal files inside the ".hg" folder in the local repository folder.
Maybe TortoiseHg has a additional temp folder... don't know. Anyway you should try to push the files using the Mercurital command line client:
hg push
More information about the command line client you can find here Mercurial: The Definitive Guide
Another temporary solution might be the move these files via a file system simlink to another drive with more space left.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566343",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: analyze program performance I have a program and I have encountered some performance issues.
I want to be able to track how long it takes for every single function in my code to run.
please recommend me a tool that can do as stated.
EDIT:
are there any free/open source tools?
A: Have a look at DotTrace, JetBrains are very good.
A: If you have VS 2010 you can use it's profiling tools to accomplish exactly what you want
A: I have a positive experience with SlimTune Profiler. It's lightweight, free and pretty powerful.
A: Three options.
1) As Joe says, Jetbrains DotTrace. I use this. It's nice and simple.
2) As M0sa says, Visual Studio has profiling tools, but only in Ultimate and premium editions.
3) Redgate do Ants Profiler. Apparently it's much better these days. I rejected it years ago because it was slow and a memory hog. Probably worth looking at.
There are also some tools available for free for specific technologies. If you download the Windows 7 SDK that includes a suite of performance tools include the WPF performance tools. FYI they aren't all just for Windows 7.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566351",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: AppDelegate never being called on iphone/ipad I am developing an app that runs on both ipad/iphone, so for ipad
I am using a view controller in mainWindow_ipad.xib and then I am loading a new view using navigation vc, but I cant access my appDelegate method. The app directly starts and loads the newView which I am loading
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { }
How can I ensure this method is called? I am loading mainWindow_ipad.xib from info.plist
Update
this is my .m file
@implementation Ihope_test_sqlAppDelegate_iPad
@dynamic aNav;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
NSLog(@"IPAD");// but i cant find this log output
}
this is my .h file
#import "Ihope_test_sqlAppDelegate.h"
@class RootView;
@interface Ihope_test_sqlAppDelegate_iPad : Ihope_test_sqlAppDelegate
{
IBOutlet UINavigationController *aNav;
}
//@property (nonatomic, retain) UITextField *usernameField;
//@property (nonatomic, retain) UITextField *passwordField;
@property (nonatomic, retain) IBOutlet UINavigationController *aNav;
-(IBAction)removeKeyboard;
@end
A: Check that the class of the app delegate in mainWindow_ipad.xib is of the right class. You need to make sure that the MainWindow nib file for iPad has an App Delegate that is of the Ihope_test_sqlAppDelegate_iPad class rather than Ihope_test_sqlAppDelegate.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566353",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: RefreshEventName for filtering on ria services for visual studio 2010 In ria services for silverlight 3 there was a functionality through RefreshEventName in order to control when a filter should be applied to the domain service query. (usually set to TextChanged)
In the new implementation of ria (visual studio 2010) the only way to set the filters of a query is by using a filterDescriptor along with binding like the following example:
<riaControls:DomainDataSource x:Name="myData" LoadSize="50" QueryName="GetPartnerCategoriesQuery" AutoLoad="True">
<riaControls:DomainDataSource.DomainContext>
<ds:DataAccessContext />
</riaControls:DomainDataSource.DomainContext>
<riaControls:DomainDataSource.FilterDescriptors>
<riaControls:FilterDescriptor PropertyPath="Descr" Operator="Contains" Value="{Binding Text,ElementName=txtFilter}"
IsCaseSensitive="False" IgnoredValue="" />
</riaControls:DomainDataSource.FilterDescriptors>
</riaControls:DomainDataSource>
Is there a way to control on when the filter should be applied?
The default setting is magically set to TextChanged.
I am looking for a way to set the filters on LostFocus event, or even better using a button.
A: Thought of a way to implement a "press button to search" functionality.
Instead of binding the filterDescriptors to elements (textboxes etc) i bind them to properties on codebehind.
When the user clicks the search button i just copy the values of the controls to the properties.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566356",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Servicemix - OSGi classloading issues with embedded dependencies I'm developing project with multiple OSGi bundles, deployed on ServiceMix (FuseESB compilation, v. 4.3.1). The issue is, one of this bundles is connecting to EJB on WebLogic, therefore it embeddes weblogic.jar.
The solution is working, however a trick was required. The bundle exports Spring service via OSGi. This service is imported in another bundle, which is entry point to the system. When from this bundle the service was called, the weblogic classes were invisible. The working trick is to wrap Spring service in following aspect, which temporarly switches classloader:
public Object profileInventory(ProceedingJoinPoint pjp) throws Throwable {
Object output = null;
ClassLoader clOld = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(pjp.getTarget().getClass().getClassLoader());
output = pjp.proceed();
} finally {
Thread.currentThread().setContextClassLoader(clOld);
}
return output;
}
As I have understood, the service is called with classloader from entry bundle, not with the classloader from bundle that embedds weblogic, and for this classloader embedded dependency classes are not visible. In similar case, exported Spring service can use private imports and private packages from its bundle, but with embedded jars it is not so.
My question is: is the embedding jars something so specific, that this embedded classes will be visible only when the call originates from embedding bundle (or with classloader swich trick), or there is something more to specify when embedding bundle, something I have forgot to do?
I'm using maven-bundle-plugin
<plugin>
<groupId>org.apache.felix</groupId>
<artifactId>maven-bundle-plugin</artifactId>
<configuration>
<instructions>
<Bundle-Name>${pom.artifactId}</Bundle-Name>
<Bundle-SymbolicName>${pom.groupId}.${pom.artifactId}</Bundle-SymbolicName>
<Embed-Dependency>
weblogic;scope=*,
</Embed-Dependency>
A: I have encountered a similar problem when using Spring remoting before. Spring likes to dynamically load classes using the thread context classloader, which doesn't always fare well in OSGi.
The burden to work correctly doesn't belong in the caller though, it belongs in the offending bundle. I don't have the code on hand (it was a couple of years ago), but you need to simply provide the classloader to the Spring remoting classes (I am assuming you are using Spring remoting) to handle the classloading properly.
For example, if the bundle uses SimpleRemoteStatelesSessionProxyFactory, it should be calling the setBeanClassLoader() method.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566357",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: SVN-difference between lock on working copy of file and lock on repository file What is the difference if I lock the file in the working copy that I have downloaded and the same file in the repository. The syntax is :
svn lock TARGET
So target can be URL for the file in repository and file in the working copy.
What is the difference in both ways?
A: Locking a file through the svn lock command will always lock it in the repository.
If you use the 'file in your working copy' syntax (e.g. svn lock readme.txt), then you can only commit that file from that particular working copy.
If you use the 'URL in repository' syntax (svn lock http://myrepo/svn/myproject/readme.txt), changes to that file can not be committed from any working copy until the lock is removed.
For more information, see the svn book: http://svnbook.red-bean.com/en/1.7/svn.advanced.locking.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566364",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Efficiently Computing Text Widths I need to compute the width of a column with many rows (column AutoSize feature). Using Canvas.TextWidth is far too slow.
Current solution: My current solution uses a text measurer class that builds a lookup table for a fixed alphabet once and then computes the width of a given string very fast by adding up character widths retrieved from the lookup table. For characters not contained in the lookup table, the average character width is used (also computed once).
Problem: This works well for European languages but not for Asian languages.
Question: What's the best way to tackle this problem? How can such an AutoSize feature be realized without the relatively slow Canvas functions and without depending on a specific alphabet?
Thanks for any help.
A: You said you want to get the maximum text width for a column. Can't you, say, take only the 4 or 5 longest strings and get their widths? That way you won't have to find the width for all items and can save quite some time.
Or you use your cache to find the rough length of the strings and then refine that by getting the actual width for the top 4 or 5 items you found.
I don't think it matters a lot whether you use Canvas.TextWidth or GetTextExtentPoint32. Just use one of these to get the exact widths, after you used one of the methods above to guesstimate the longest/widest strings.
To those who think this doesn't work
If the poster of the original question thinks it could work, I have no reason to think it won't. He knows best what kind of strings can be in the columns he has.
But that is not my main argument. He already wrote that he does a preliminary textwidth by adding the predetermined individual widths of the characters. That does not take into account any kerning. Well, kerning can only make a string narrower, so it still makes sense to check only the top 4 or 5 items for the exact width. The biggest problem that can occur is that the column could be a few pixels too wide, no more. But it will be a lot faster than using TextWidth or GetTextExtentPoint32 or similar functions on each entry (assuming more than 5 entries), and that is what the original poster wanted. I suggest that those who don't believe me simply try it out.
As for using the pure string length: even that is probably good enough. Yes, 'WWW' is probably wider than '!!!!!', but the original poster will probably know best wat kind of string material he has, and if it is feasible. '!!!!!' or 'WWW' are not the usual entries one expects. Especially if you consider that not only one single string is checked, but the longest 4 or 5 strings (or whatever number turns out to be optimal). It is very unlikely that the widest string is not among them. But the original poster can tell if that is possible or feasible. He seems to think it is.
So stop the downvoting and try it out for yourself.
A: I'm afraid you have to use Canvas.TextWidth, or your implementation will be imprecise. The width of text depends on the font kerning, where different character sequences may have different widths (not just the total of individual character widths).
A: Me, I cut out the middle-man and use the Windows API directly. Specifically, I use GetTextExtentPoint32 with the .Handle of the Canvas. There's nothing you can do to be faster, other than caching results in some way, and frankly you'll just add overhead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566365",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: How do I convince the JVM to inline an interface method? I have an class hierarchy rooted in an interface and implemented with an abstract base class. It something looks like this:
interface Shape {
boolean checkFlag();
}
abstract class AbstractShape implements Shape {
private boolean flag = false;
protected AbstractShape() { /* compute flag value */ }
public final boolean checkFlag() { return flag; }
}
interface HasSides extends Shape {
int numberOfSides();
}
interface HasFiniteArea extends Shape {
double area();
}
class Square extends AbstractShape implements HasSides, HasFiniteArea {
}
class Circle extends AbstractShape implements HasFiniteArea {
}
/** etc **/
When I sample the running code with VisualVM, it appears that AbstractShape.checkFlag() is never inlined and consumes 14% of total program running time, which is obscene for a method this simple, even for a method called so frequently.
I have marked the method final on the base class, and (currently) all classes implementing the "Shape" interface extend AbstractShape.
Am i interpreting the VisualVM sample results correctly? Is there any way to convince the JVM to inline this method or would I need to tear out the interfaces and just use an abstract base class? (I would prefer not to because the hierarchy includes interfaces like HasFiniteArea and HasSides which mean the hierachy does not have a perfect tree form)
EDIT: to be clear, this is a method that in any universe should be inlined. It is called more than 420 million times during a 2 minute execution and, because it is not inlined and remains a virtual call, it accounts for 14% of runtime. The question I'm asking is what is preventing the JVM from inlining this method and how do i fix it?
A: Here is quote from the Wikipedia
A common misconception is that declaring a class or method final
improves efficiency by allowing the compiler to directly insert the
method inline wherever it is called. This is not completely true; the
compiler is unable to do this because the classes are loaded at
runtime and might not be the same version as the ones that were just
compiled. Further, the runtime environment and JIT compiler have the
information about exactly which classes have been loaded, and are able
to make better decisions about when to inline, whether or not the
method is final.
See also this article.
A: The default compiler threshold is 10000. -XX:CompilerThreshold= This means a method or a loop (for the server JVM) has to be called at least 10000 times before it is compiled to native code.
After it has been compiled it can be inlined, however the call stack does show this. It is smart enough to know the inlined code came from another method and you never see a truncated call stack.
profilers try sample code and assign time. It doesn't always do a great job and you get methods which are obvious not time consumers being assigned CPU time. VisualVM is a free profiler and it is implementing in Java. If you use a profiler like YourKit you can get more accurate results as it uses native code e.g. doesn't create garbage.
A: After extensive experimentation, I could not get the Sun JDK 6 to inline this method when called on the interface.
Fortunately, there were a limited number of call sites involved, and changing
public void paint(Shape shape) {
if(shape.checkFlag()) { /* do stuff */ }
}
to
public void paint(Shape shape) {
if(((AbstractShape)shape).checkFlag()) { /* .. */ }
}
is enough of a hint to get the JVM to inline the method. Running time of the calculation in question dropped 13% compared to the original runtime of 6 minutes.
A: From the literature I've read on old versions of JVM's by declaring methods final it would determine it to transform that method inline.
Now you don't have to specify that method to be final to optimize the code.
You should let the JVM optimize the code, and make the method final only if you explicitly don't want that method overridden. The JVM probably doesn't make your method inline because its own optimization is faster, considering the rest of the application's code.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566368",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Newbie: Errors in an iPhone app I'm really newbie in iOS and I have to handle a complicated situation. I was given an iPhone app developed by someone and I have to make it work. The guy who developed it has told me that it worked, but sometimes crashed in an iPhone. I've never developed using iOS and I don't really know how this app works.
Well, when I open the app with Xcode, the first problem that I detect is some errors with the references. The app uses the project CorePlot-CocoaTouch.xcodeproj. I've added again this project and solved the references (I've followed some other posts like this one: http://www.jaysonjc.com/programming/pie-chart-drawing-in-iphone-using-core-plot-library.html).
I want to test it with the simulator (I don't have an iPhone yet). I have a doubt here...should I use iOS Device, or iOS Simulator as Base SDK? Firstly I chose iOS Simulator, but it appeared a problem with Cocoa.framework (it turned into red).
Anyway, using iOS Device as Base SDK, I build the project and it says "Build failed (59 errors, 3 warnings)". I check out the errors, and most of them are "Expected specifier-qualifier-list before ..."
Can anyone help me? This is more or less the situation, but I can provide more specific details if they're needed.
I'm sorry if I'm talking about something really basic, but I've been trying to solve it for 2 weeks and I give up. I've tried to talk to the guy, but he's not really helpful..
Thanks for the replies!
By the way, I didn't say it and I don't know if it's relevant or what it means. The guy has a directory called "Libraries" where it's stored the CorePlot. The files there are the same than if you download the CorePlot project from other source. The only exception is a folder called "SDKBuild", which contains files like "build.sh", "iphoneos-SDKSettings.plist" or "iphonesimulator-SDKSettings.plist". I'm really newbie, so it's probably obvious, but I have no idea...
A: just try to add CocoaTouch framework to your project.
and for base SDK use "latest iOS".
A: Right click on the project name in 'group & files' set on the left of xcode. Choose add -> Existing Frameworks.
Find Cocoa.framwork and click add. Do this to all red colored framework.
Choose IOS Simulator as base SDK.
Try run it..
A: If you want to run the app on simulator, you have to build with iOS simulator. The base SDK basically sets the OS version (this will be the same regardless of whether you are running the app on simulator or device). You should be chaining the build settings to device only if the device is connected and if you have installed the appropriate provisioning profiles.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566370",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Where should log4j.properties be located when using Maven Exec Plugin? I am trying to use log4j in a project I am executing with the exec-maven-plugin. I have tried placing the file in the following locations:
$PROJECT_HOME
$PROJECT_HOME/src/main/resources
$PROJECT_HOME/target
$PROJECT_HOME/target/classes
For all locations of the file, I am getting the following message when executing the code:
log4j:WARN No appenders could be found for logger (mypacakge.MyClass).
log4j:WARN Please initialize the log4j system properly.
Where should the log4j.properties file be located?
exec-maven-plugin config:
...
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.2</version>
<configuration>
<mainClass>mypackage.Main</mainClass>
</configuration>
</plugin>
...
A: You have two choices:
*
*Put the property file under
./src/main/resources/log4j.xml
*
*You can specify it from the command line:
$ mvn compile exec:java -Dexec.classpathScope=compile -Dexec.mainClass=com.lei.java.sample.Test -Dlog4j.configuration=file:./log4j.xml
A: I'm not sure this is the right way (because I don't know this plugin), but you may use the configuration of the plugin to specify to the classpath of the VM the right location of your file :
<configuration>
<executable>maven</executable>
<!-- optional -->
<workingDirectory>/tmp</workingDirectory>
<arguments>
<argument>-classpath</argument>
<argument>/path/to/dirthatcontainslog4J</argument>
...
</arguments>
</configuration>
What is the purpose of using such a plugin ?
If this is in order to test your app, you should probably use maven-dependency-plugin : http://www.sonatype.com/books/mvnex-book/reference/customizing-sect-custom-packaged.html
You can find more info here :
maven jar-with-dependencies log4j
How can I create an executable JAR with dependencies using Maven?
Regards
A: Actually, log4j has provided command line option support for locating configuration file manually. However it is used for java command itself, and you could use it in Maven building through -Dexec.args option to pass java options directly:
$ mvn -Dexec.args="-Dlog4j.configurationFile='./log4j2.xml' -classpath /previously/configured/path" org.codehaus.mojo:exec-maven-plugin:1.2.1:exec
Besides, arguments in exec.args could also be written persistently into Mojo's <arguments> section, as said in document:
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>exec-maven-plugin</artifactId>
<version>1.6.0</version>
<executions>
...
</executions>
<configuration>
<executable>maven</executable>
<arguments>
<argument>-Dlog4j.configurationFile="./log4j2.xml"</argument>
...
</arguments>
</configuration>
</plugin>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566374",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to enter text in uppercase? I need enter text only at uppercase. How can I do it in vaadin with TextField?
I need that text is really uppercase not only visualy using styles....
A: An easy way to achieve this is to set the style and change the string to uppercase by yourself.
Here's the VAADIN code:
TextField donut = new TextField();
donut.setStyleName("upMeBro");
this.addComponent(donut);
Set the css file like this:
.v-textfield-upMeBro {
text-transform: uppercase;
}
After a event is fired (User typed in text, Button is clicked, etc.) you can easily modify the string to uppercase with native java:
System.out.println(donut.getValue().toString().toUpperCase());
A: The easiest way to solve your problem is wroten by "user810595". But if your do not want to use custom styles in your application you can use this code:
final TextField field = new TextField();
field.setImmediate(true);
field.addListener(new TextChangeListener() {
@Override
public void textChange(TextChangeEvent event) {
String text = event.getText();
field.setValue(text.toUpperCase());
//TODO: do some actions if needed
}
});
A: Well this is my try:
code
public class UpperTextField extends TextField {
public UpperTextField() {
addStyleName("upper-case");
}
@Override
protected String getInternalValue() {
return super.getInternalValue() != null ? super.getInternalValue().toUpperCase() : super.getInternalValue();
}
}
css
.upper-case{
text-transform: uppercase;
}
A: Use a converter. Just like you would convert a field from String to Int using the StringToIntConverter, you could try using the StringToUpperCaseStringConverter and then bind it.
A: in event keyreleased you write
private void jTxtNoRincKeyReleased(java.awt.event.KeyEvent evt)
{
// TODO add your handling code here:
jTxtNoRinc.setText(jTxtNoRinc.getText().toUpperCase());
}
jTxtNoRinc : Component's Name
it's simple
A: I would say ..
<input id="yourid" style="**text-transform: uppercase**" type="text" />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566380",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: rails 3 habtm filtering with multiple entries i have a product model and a product category model. and theres a habtm between those.
i have categories like 'men' and 'jeans' and i would like to filter these. to do a filter on men is no problem but i need to filter multiple parameters (men and jeans). i tried some variations but i'm stuck on this.
this is what i have so far..
Product.joins(:product_categories).where(['product_categories.id = 5 and product_categories.id = 6'])
thanks for your time!
A: How about writting it like this and passing array of ids you're looking to filter by?
Product.joins(:product_categories).where(['product_categories.id in (?)', _product_categories_ids ])
A: this is the solution which selects men AND jeans and not men OR jeans:
@products = Product.scoped
@product_category_ids.each.with_index do |product_category_id, index|
@products = @products.joins("INNER JOIN product_categories_products pcp#{index} ON pcp#{index}.product_id = products.id AND pcp#{index}.product_category_id = #{product_category_id}")
end
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566383",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Readonly public property redeclared as readwrite in private interface.. understanding a bit more I've read the Property redeclaration chapter in The Objective-C Programming Language document and I'd like if some of you can clarify me the following property redeclaration:
// MyObject.h public header file
@interface MyObject : NSObject {
NSString *language;
}
@property (readonly, copy) NSString *language;
@end
// MyObject.m private implementation file
@interface MyObject ()
@property (readwrite, copy) NSString *language;
@end
@implementation MyObject
@synthesize language;
@end
I just want to understand if the above @property and @synthesize keywords produce the following code:
// MyObject.h public header file
@interface MyObject : NSObject {
NSString *language;
}
-(NSString *)language;
@end
// MyObject.m private implementation file
@interface MyObject ()
-(void)setLanguage: (NSString *) aString;
@end
@implementation MyObject
-(NSString *)language {
return language;
}
-(void)setLanguage: (NSString *) aString {
[language release];
language = [aString copy];
}
@end
So, what happens is that the compiler sees the first @property declaration and adds a getter method in the public interface... than, when it comes to the implementation file it finds another @property declaration for the same property but with readwrite attribute within the private interface and adds only a setter method since the getter has been already added to the public interface.. then, the @synthesize keyword is found and both implementations are added to the private implementation section.. the copy attribute of the first @property declaration would not be necessary, since the setter is not needed there, but we must specify it to be consistent with the second property redeclaration. Are my thoughts right?
A: Yes, your understanding is correct.
Also note that there are no strictly private methods in Objective-C. An external caller can still call setLanguage:. The compiler will output a warning but the message would get through at runtime.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566384",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: why my uialeartview alway change position when rotage My uialeartview code.
when it show in Landscape or Portrait it ok but when
change Portrait to Landscape or Landscape to Portrait
it will always move up not in center of window like before
how can i make it it center of window when rotage.
UIAlertView *over;
over=[[UIAlertView alloc]initWithTitle:@"Game over"
message:[NSString stringWithFormat:@"Your score : %d\n\n\n",score]
delegate:self
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[over show];
UITextField *nameinputfiled=[[UITextField alloc]initWithFrame:CGRectMake(11, 80, over.frame.size.width-50, 31)];
nameinputfiled.backgroundColor=[UIColor whiteColor];
[over addSubview:nameinputfiled];
[over release];
A: You don't have to add the UIAlertView as a subView, just use [over show] and don't forget to release it afterwards.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566388",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error when executing SQLCommand using C# i'm pretty new to ADO.NET using C# (Visual Studio 2010). Using LinqToSql isn't an option because underlying database is a Compact Edition 3.5 (unfortunealty).
with the code displayed underneath I get an error: "There was an error parsing the query. [ Token line number = 2,Token line offset = 38,Token in error = AgentName ]"
Can someone tell me what i'm doing wrong?
using (SqlCeConnection oConn = new SqlCeConnection(connectionstring))
{
string strSql = @"select
a.name as 'AgentName',
t.description as 'JobType',
s.description as 'Status',
count(j.statusid) as 'Count'
from
jobs as j
inner join agents as a on j.agentid = a.id
inner join statusdictionary as s on j.statusid = s.id
inner join jobtypedictionary as t on j.jobtypeid = t.id
where
convert(datetime,starttime,0) between @FirstDate and @LastDate
AND j.JobTypeID = @JobTypeID AND j.AgentID = @AgentID
group by
s.description,
t.description,
a.name order by a.name,
t.description";
SqlCeCommand oCmd = new SqlCeCommand(strSql, oConn);
SqlCeParameter fdparam = new SqlCeParameter();
fdparam.ParameterName = "@FirstDate";
fdparam.Value = firstdate;
oCmd.Parameters.Add(fdparam);
SqlCeParameter ldparam = new SqlCeParameter();
ldparam.ParameterName = "@LastDate";
ldparam.Value = lastdate ;
oCmd.Parameters.Add(ldparam);
SqlCeParameter JIDparam = new SqlCeParameter();
JIDparam.ParameterName = "@JobTypeID";
JIDparam.Value = jobtypeid;
oCmd.Parameters.Add(JIDparam);
SqlCeParameter AIDparam = new SqlCeParameter();
AIDparam.ParameterName = "@AgentID";
AIDparam.Value = jobtypeid;
oCmd.Parameters.Add(AIDparam);
oConn.Open();
SqlCeDataReader oReader = oCmd.ExecuteReader();
A: i think you need to lose the quotes around 'AgentName'.
A: Change single quotes '' to brackets []
a.name as [AgentName],
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566390",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: are there any samples on how to use chat api with facebook c# sdk Can I use the Facebook Chat API with the Facebook C# SDK? If so, are there any samples for using the Chat API?
A: Facebook C# SDK doesn't support the Facebook chat API.
Facebook chat is based on the XMPP protocol, so you might want to search for XMPP libraries written in C# instead.
You can find a list of XMPP libraries at http://xmpp.org/xmpp-software/libraries/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566397",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Index xml output of a rest web service into a solr server How can i index a solr server with the content of webservice.
my webservice output looks like this
now i want to index the solr serverwith the content under xml as shown above
how can i index thiss into apache solr.
A: You will need to loosely follow the steps below to index your data.
*
*Configure your Index Schema for the fields you want indexed. Based on the example above, you would want fields for classname, packagename and url. See SolrSchema for more details.
*Add the documents to your index. Please see one of the following for details on how you can do this.
*
*Adding documents in XML format
*DataImportHandler - Usage with XML/HTTP Datasource
A: Make a script in your favorite scripting language (Python for me). I did something similar with databases and hope a similar solution will go well fro you.
With Python:
*
*urllib2 can fetch the body of your webpage, given the URL.
*Use an XML parser like etree to recursively descend down the tree, and convert it into an XML/ JSON hierarchy of your choosing (as you prefer)
*Upload it to Solr (Solr allows uploads in XML, JSON, CSV etc).
And run this script periodically like a cron-job.
You will need two pieces of code: one to query your RESTful service and acquire the body of the response; the other to upload a formatted document to Solr.
This piece of code uploads a Python object request_obj to the given request_url and a solr's response is returned as a Python object. A native Python object (composed of dictionaries (associative arrays), lists, strings, numbers) translates to JSON easily (with 1-2 caveats).
Use this only as reference. I guarantee no suitablity for your purpose.
Dont forget to use /update/json?wt=python which is available from Solr 3.3 onwards. You need MultipartPostHandler library.
def solr_interface(self,request_url,request_obj):
request=json.dumps(request_obj,indent=4,encoding="cp1252")
opener = urllib2.build_opener(MultipartPostHandler.MultipartPostHandler)
urllib2.install_opener(opener)
req = urllib2.Request(request_url, request)
req.add_header("Content-Type", "application/json")
text_response = urllib2.urlopen(req).read().strip()
return ast.literal_eval(text_response)
As for parsing (and composing) XML in Python, use these excellent tutorials http://www.learningpython.com/2008/05/07/elegant-xml-parsing-using-the-elementtree-module/ and http://effbot.org/zone/element.htm
This is a commandline sample.
from xml.etree import ElementTree as ET
elem =ET.fromstring("<doc><p>This is a block</p><p>This is another block</p></doc>")
for subelement in elem:
... print subelement.text
...
This is a block
This is another block
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566398",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Asp.net website custom logins i have made a simple web application which uses a table from a database to show the data also for the logins i used asp.net membership provider. which made the aspnet.mdf database. Now i don't want to use 2 databases for this. I just want a single database which also contains the users and roles. Can any one give me an advice on this?
A: How to Configure ASP.Net Membership Providers to Use Our Own Database?
If, on the other hand, you wish to use your own database structure, you will have to create a custom Membership Provider. It's quite a long process, but not very complicated.
Here's a good explanation: about Creating a custom membership provider
A: You don’t want to create two databases. You can use ASP.NET SQL Server Registration Tool (Aspnet_regsql.exe) to create membership tables to your existing database.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566399",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Linking HTML table with MySQL table I have a table that displays data from a MySQL table. I have an extra column that adds a checkbox for each entry.
Is it possible to link that column row with the other data in the columns containing the MySQL data?
The checkbox entries will then be saved to a new mysql table upon pressing the 'Save' button.
Here is a picture to show you what I mean:
Code:
<?php
$connection = mysql_connect('localhost','admin','root');
if( isset($_POST['submit']) )
{
if( isset( $_POST['cb_change'] ) && is_array( $_POST['cb_change'] ))
{
foreach( $_POST['cb_change'] as $emp_number => $permission)
{
$sql = "UPDATE `rights` SET Permission='".mysql_real_escape_string($permission)."' WHERE emp_number='".mysql_real_escape_string($emp_number)."'";
echo __LINE__.": sql: {$sql}\n";
mysql_query( $sql );
}
}
}
?>
<p style="text-align: center;">
<span style="font-size:36px;"><strong><span style="font-family: trebuchet ms,helvetica,sans-serif;"><span style="color: rgb(0, 128, 128);">File Database - Administration Panel</span></span></strong></span></p>
<p style="text-align: center;">
</p>
<head>
<style type="text/css">
table, td, th
{
border:1px solid #666;
font-style:Calibri;
}
th
{
background-color:#666;
color:white;
font-style:Calibri;
}
</style>
</head>
<form method="post" action="admin.php">
<?php
if (!$connection)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db('users', $connection);
//mysql_query('INSERT into rights(Emp_num, ID, Name, Surname) SELECT emp_number, employee_id, emp_firstname, emp_lastname FROM hs_hr_employee');
$result = mysql_query("SELECT emp_number, employee_id, emp_firstname, emp_lastname, Permissions FROM rights");
mysql_query("INSERT INTO rights (emp_number, employee_id, emp_firstname, emp_lastname)
SELECT emp_number, employee_id, emp_firstname, emp_lastname
FROM hs_hr_employee
ON DUPLICATE KEY UPDATE employee_id = VALUES(employee_id), emp_number = VALUES(emp_number)
");
$duplicates = mysql_query("SELECT emp_number, employee_id, emp_firstname, emp_lastname, count(*) FROM rights GROUP BY emp_number, employee_id, emp_firstname, emp_lastname having count(*) > 1");
$count = mysql_num_rows($duplicates);
if ($count > 0) {
while ($row = mysql_fetch_assoc($duplicates)) {
$field = $row["emp_number"];
$limit = $row["count(*)"] - 1;
mysql_query("DELETE FROM rights WHERE emp_number='$field' LIMIT $limit");
}
mysql_free_result($duplicates);
}
echo "<center>";
echo "<table >
<tr>
<th>Employee Number</th>
<th>ID</th>
<th>Name</th>
<th>Surname</th>
<th>Permissions</th>
<th>Change</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['emp_number'] . "</td>";
echo "<td>" . $row['employee_id'] . "</td>";
echo "<td>" . $row['emp_firstname'] . "</td>";
echo "<td>" . $row['emp_lastname'] . "</td>";
echo "<td>" . $row['Permissions'] . "</td>";
echo "<td> <select name='cb_change[]'><option value='all'>All</option> <option value='remote'>Remote Gaming</option> <option value='landbased'>Landbased Gaming</option> <option value='general'>General Gaming</option> </select> </td>";
echo "</tr>" ;
}
#echo "<td>" . $row['Change'] . "</td>";
echo "</table>";
echo "</center>";
#$_POST['cb_permissions'];
mysql_close($connection);
?>
<p style="text-align: center;">
</p>
<p style="text-align: center;">
</p>
<p style="text-align: right;">
<input name="Save_Btn" type="button" value="Save" />
</p>
</form>
Any help would be kindly appreciated.
A: Assuming you mean another column after the select list column titled 'change'.
Add another table cell after the change colum with this...
echo "<td> <input type="checkbox" name='fieldName[]' value="<?php echo $row['emp_number']; ?>" > </td>";
After you've posted the form the $_POST['fieldName'] array will have the ids for the rows that have been clicked.
Try and make sure the $row['emp_number'] is from your tables primary key to make sure the value is unique.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566401",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to round to the next multiple in JavaScript? I'm looking for a JavaScript function which will round to the next multiple:
function arrondiSuperieur($nombre, $arrondi) {
return ceil($nombre / $arrondi) * $arrondi;
}
echo arrondiSuperieur(6, 5); //display 10
echo arrondiSuperieur(16, 7); //display 21
Have you an idea?
A: Translated PHP to JS:
function arrondiSuperieur(nombre, arrondi) {
return Math.ceil(nombre / arrondi) * arrondi;
}
alert(arrondiSuperieur(6, 5)); //display 10
alert(arrondiSuperieur(16, 7)); //display 21
alert shows a dialog with the result. You can also use document.write if the script is directly run on load within the <body> tags.
A: I think you want you function to do this:
function arrondiSuperieur($nombre, $arrondi) {
return floor($nombre / $arrondi) * $arrondi + $arrondi;
}
This will round up to the closest number that is divisible by the second parameter in the function.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566404",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to wrap accordion pairs with outer container? I have the following problem with the accordion. I have pairs of elements with an outer container "accordion" but I need to wrap each pair with another container. As I understood I can't wrap them before because the accordion won't work.
So I need to wrap them after domready with an additional snippet...
I got this:
<div id="accordion">
<h2 class="head">Headline</h2>
<div class="content">Some content...</div>
<h2 class="head">Headline</h2>
<div class="content">Some content...</div>
....more pairs
</div>
I need this:
<div id="accordion">
<div class="outer">
<h2 class="head">Headline</h2>
<div class="content">Some content...</div>
</div>
<div class="outer">
<h2 class="head">Headline</h2>
<div class="content">Some content...</div>
</div>
...more pairs
</div>
I thought this will do the job:
$('.head').before('<div class="outer">');
$('.content').after('</div>');
...but it inserts already closed divs before each headline.
A: You can only insert whole elements using methods like before() and after().
One way to achieve what you want would be to call wrapAll() on each <h2>/<div> pair, using something like nextUntil() to match the pairs:
$("#accordion h2").each(function() {
$(this).nextUntil("h2").andSelf().wrapAll("<div class='outer'></div>");
});
A: Try this
$('.head:first,.content:first').wrapAll('<div class="outer">');
$('.head:last,.content:last').wrapAll('<div class="outer">');
JSFiddle Example
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566407",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Mapping a UserType column of oracle in Hibernate I have a user defined datatype that can contain a list of numbers. How can I map it in Hibernate.
While using the reverse engineer feature of hibernate, I get a Serializable datatype corresponding to this field.
I desire to have some concrete Class for the same.
I explored about org.hibernate.usertype.UserType interface but not sure how to use it in my case.
A: You can create a many to many relation for instance:
@Entity
public class Foo {
@ManyToMany(cascade = CascadeType.ALL, fetch=FetchType.EAGER)
@JoinTable(
name = "foo_numbers",
joinColumns = { @JoinColumn(name = "fooid") },
inverseJoinColumns = { @JoinColumn(name = "numberid") }
)
private List<Number> params;
}
Of course, you don't need to override all the names in the @JoinTable statement.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566410",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to see which commits in one branch aren't in the other? I have two branches devel and next. In devel I have a more or less huge amount of commits. Some of the commits are cherry picked in next. Also I added some commits to next which are merged to devel.
Now I would like to see what is missing in next, so I can test the changes in detail before bringing them to next. My question is now, how can I see which commits are in devel but not in next?
A: You might could try doing git log subsets:
git log --oneline devel ^next
A: How about
git log next..devel
Result is similar to Byran's answer (different order of commits) but both of our answers will produce commits that are different between the branches, rather just showing what's in one branch and not in the other.
A: The little-used command git cherry (docs) shows you the commits which haven't yet been cherry-picked.
In short:
git cherry <feature-branch> [base-branch]
# Checkout the base branch
git checkout main
# Diff against the target branch
git cherry -v next
# Diff against the target branch, without switching
git cherry -v next main
Example output:
+ 492508acab7b454eee8b805f8ba906056eede0ff feat: make bazzable
- 5ceb5a9077ddb9e78b1e8f24bfc70e674c627949 hotfix: off-by-one
+ b4459544c000f4d51d1ec23f279d9cdb19c1d32b feat: add bar
+ b6ce3b78e938644a293b2dd2a15b2fecb1b54cd9 feat: add foo
+ means the commit is only in next, but not in main
- means the commit is in both branches
Remove the -v if you want the commits without the subject line:
+ 492508acab7b454eee8b805f8ba906056eede0ff
- 5ceb5a9077ddb9e78b1e8f24bfc70e674c627949
+ b4459544c000f4d51d1ec23f279d9cdb19c1d32b
+ b6ce3b78e938644a293b2dd2a15b2fecb1b54cd9
A: Also, you can use this to get a nice list of actual different commits not shared between the branches:
git log --left-right --graph --cherry-pick --oneline main...next
Example output:
> 492508ac (HEAD -> next) feat: make bazzable
> 5ceb5a90 hotfix: off-by-one
> b4459544 feat: add bar
> b6ce3b78 (origin/add-foo, add-foo) feat: add foo
The operative word is --cherry-pick
--cherry-pick
Omit any commit that introduces the same change as another commit on the "other side" when the set of commits are limited with symmetric difference. For example, if you have two branches, A and B, a usual way to list all commits on only one side of them is with --left-right, like the example above in the description of that option. It however shows the commits that were cherry-picked from the other branch (for example, "3rd on b" may be cherry-picked from branch A). With this option, such pairs of commits are excluded from the output.
Update As mentioned in a comment, recent versions of git added --cherry-mark:
--cherry-mark
Like --cherry-pick (see below) but mark equivalent commits with = rather than omitting them, and inequivalent ones with +.
A: To get the list of commits that were not integrated into the release branch (next) you may use:
git rev-list --reverse --pretty="TO_TEST %h (<%ae>) %s" --cherry-pick --right-only origin/release_branch...origin/development_branch | grep "^TO_TEST " > NotIntegratedYet.txt
Check git-rev-list for more info.
A: @Mark Longair nailed it in his answer here, but I'd like to add some additional insight.
Related, and answering the question of how to break up a large Pull Request (PR), especially when squashing your commits is impractical due to one or more merges of master into your feature_branch
My situation:
I made a big feature_branch with 30 commits and opened a Pull Request (PR) on GitHub to merge it into master. Branch master changed a ton underneath me, and received 200 commits my feature_branch didn't have. To resolve conflicts I did git checkout feature_branch and git merge master to merge master's changes into my feature_branch. I chose to merge rather than rebase onto latest master so I would have to resolve conflicts only one single time instead of potentially 30 times (once for each of my commits). I didn't want to squash my 30 commits into 1 first and then rebase onto the latest master because that might wipe away GitHub review comment history in the PR. So, I merged master into my feature branch and resolved conflicts 1 single time. All was well. My PR, however, was too big for my colleagues to review. I needed to split it up. I went to squash my 30 commits and OH NO! WHERE ARE THEY? THEY ARE ALL INTERMINGLED WITH master's 200 recent commits now because I merged master into my feature_branch! WHAT DO I DO?
git cherry usage in case you want to try to git cherry-pick individual commits:
git cherry to the rescue (sort of)!
To see all the commits that are in feature_branch but NOT in master I can do:
git checkout feature_branch
git cherry master
OR, I can check commits from ANY branch withOUT ensuring I'm on feature_branch first by doing git cherry [upstream_branch] [feature_branch], like this. Again, this checks to see which commits ARE in feature_branch but are NOT in upstream_branch (master in this case):
git cherry master feature_branch
Adding -v also shows the commit message subject lines:
git cherry -v master
Piping to "word count" "-lines" (wc -l) counts how many commits there are:
git cherry master | wc -l
You can compare this count against the commit number shown in your GithHub PR to feel better about knowing git cherry really is working. You can also compare the git hashes one by one and see they match between git cherry and GitHub. Note that git cherry will NOT count any merge commits where you merged master into feature_branch, but GitHub WILL. So if you see a small discrepancy in the count, search the GitHub PR commit page for the word "merge" and you'll probably see that's the culprit which is not showing up in git cherry. Ex: a commit titled "Merge branch 'master' into feature_branch" will show up in the GitHub PR but not when you run git cherry master feature_branch. This is fine and expected.
So, now I have a means of finding out which diffs I may want to cherry-pick onto a fresh feature branch to split up this diff: I can use git cherry master feature_branch locally, or look at the commits in the GitHub PR.
How squashing could help--if only we could squash:
An alternative, however, to split up my big diff is to squash all 30 of my commits into one, patch that onto a new feature branch, soft reset the patch commit, then use git gui to add pieces file by file, chunk by chunk, or line by line. Once I get one sub-feature, I can commit what I've added then check out a new branch, add some more, commit, check out a new branch, etc, until I have my big feature broken out into several sub-features. The problem is that my 30 commits are intermingled with the other 200 commits from other people due to my git merge master into my feature_branch, so rebasing is therefore impractical, as I'd have to sift through 230 commits to re-order and squash my 30 commits.
How to use a patch file as a much easier replacement for squashing:
A work-around is to simply obtain a patch file containing a "squash-equivalent" of all 30 of my commits, patch it onto a new fork of master (a new sub-feature-branch), and work from there, as follows:
git checkout feature_branch
# ensure I have the latest changes from master merged into feature_branch
git merge master
# Obtain a patch file, which is the equivalent of a squash of my 30 commits into 1 commit:
git diff master..feature_branch > ~/mypatch.patch
git checkout master
# Create a new, sub-feature branch
git checkout -b feature_branch2
# Patch the 30 commit patch file onto it:
git apply ~/mypatch.patch
Now I have my 30-commit patch all applied locally, but unstaged and uncommitted.
Now use git gui to add files, chunks, and/or lines and break up your big PR or "diff":
Note that if you don't have git gui, you can easily install it in Ubuntu with sudo apt install git-gui.
I can now run git gui and start adding files, chunks, and/or lines (by right-clicking in the git GUI program), and break up the 30 commit feature branch into sub branches as described just above, repeatedly adding, committing, then forking a new feature branch and repeating this cycle until all changes have been added to a sub-feature-branch and my 30-commit feature is successfully broken up into 3 or 4 sub-features. I can open up a separate PR for each of these sub-features now, and they will be easier for my team to review.
References:
*
*Create patch or diff file from git repository and apply it to another different git repository
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566416",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "208"
}
|
Q: sql exception while updating data While updating data, I get the following exception:
Dynamic SQL generation for the UpdateCommand is not supported against a SelectCommand that does not return any key column information.
Can anyone help me please?
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
cn = new SqlConnection(cs);
da = new SqlDataAdapter("select*from Clinic_info", cn);
SqlCommandBuilder cmd = new SqlCommandBuilder(da);
ds = new DataSet();
da.Fill(ds, "Clinic_info");
//ds.Tables["Clinic_info"].Constraints.Add("CL_ID_pk", ds.Tables["Clinic_info"].Columns["CL_ID"], true);
try
{
DataRow row;
row = ds.Tables["Clinic_info"].Rows.Find(Session["msg"].ToString());
row.BeginEdit();
row["CL_Name"] = cl_name.Text;
row["CL_Desc"] = cl_descri.Text;
A: Make sure sql table has primary key.
A: Make sure you've got select * from Clinic_info in the code instead of select*from Clinic_info.
And, as Coder has told you, check the table has a primary key. This is the reason behind the exception.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566418",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Error "Unable to find the requested .Net Framework Data Provider. It may not be installed" I am using Visual Studio 2008 and oracle database 10g.
I trying to connect to the backend like this:
Subwindow "Server explorer". Push button "Connect to database" and make next chain
Data Connection->Choose Data Source->Oracle Database->oracle Data provider for .Net->Continue->Data Source name : oraclexe->Userneme: hr password: hr -> Test connection (answer "Test connected succeeded ")->push button OK and:
"Unable to find the requested .Net Framework Data Provider. It May not be installed"
I have made changes to machine.config
<add name="Oracle Data Provider for .NET"
invariant="Oracle.DataAccess.Client" description="Oracle Data Provider for .NET"
type="Oracle.DataAccess.Client.OracleClientFactory,
Oracle.DataAccess, Version=2.111.6.20, Culture=neutral, PublicKeyToken=89b483f429c47342" />
But then to same error persists. What to do?
A: Oracle data providers are specific for an architecture. If you download a 64-bit driver you need to build your application as 64bit (or AnyCPU if the target OS is 64bit).
The problem is that Visual Studio is 32-bit, so you also need a 32bit driver installed.
A: A couple of suggestions:
*
*Don't use the EF beta. If you do, use the 32-bit version. The driver does not work as advertised as of October 2010, the install was misconfigured for 64 bit applications and odac dll's were placed in the wrong system folder, aside from other issues.
*Stick with ado.net and do some simple queries before tackling the project, if you are using someone else's project or downloaded it from somewhere.
*Visual studio project files keep suggested locations for assemblies in the project file, look for those and remove the "hint" path if this is someone else's project.
*Download and install the client files:
http://www.oracle.com/technology/software/tech/windows/odpnet/index.html since you did not specify that you have the client files installed.
In summary, you are probably using one version of the driver for the design tool and another for the underlying connections. I know this sounds weird but I've run into it several times already. The only way forward is to take it apart. If you start with an ADO.NET base connection test you'll find the problem.
Below is a simple connection to get started.
Thanks,
Aldo
using System;
using System.Data.Common;
using Oracle.DataAccess.Client;
namespace EntityFrameworkForOracle
{
internal class Test1Connection
{
internal void InternalTestRead()
{
using (var con = Database.GetLocalConnection())
{
con.Open();
var cmd = Database.GetCommand(con);
const string sql = @"select *
from TESTTABLE";
cmd.CommandText = sql;
var reader = cmd.ExecuteReader();
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}", reader[0], reader[1]);
}
reader.Close();
con.Close();
con.Dispose();
cmd.Dispose();
}
}
}
public static class Database
{
private const string ProviderName = "Oracle.DataAccess.Client";
private const string LocalConnectionString = "User Id=system;Password=XXX;Data Source=localhost:XXXX/XXXX;enlist=true;pooling=true";
private static readonly DbProviderFactory Factory = DbProviderFactories.GetFactory(ProviderName);
public static DbCommand GetCommand(DbConnection con)
{
var cmd = Factory.CreateCommand();
if (cmd != null)
{
cmd.Connection = con;
return cmd;
}
return null;
}
public static DbCommand GetCommand(string cmdText, DbConnection con)
{
var cmd = GetCommand(con);
cmd.CommandText = cmdText;
return cmd;
}
public static DbConnection GetLocalConnection()
{
var con = Factory.CreateConnection();
if (con != null)
{
con.ConnectionString = LocalConnectionString;
return con;
}
return null;
}
public static void CloseConnection(OracleConnection connection)
{
connection.Close();
connection.Dispose();
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566419",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Select All tables / not? I have the following master & child tables (All of them require ADD/EDIT/DELETE)
tblSchool
tblStudent
tblClass
tblTests
|
> tblSchoolClass
> tblClassStudent
> tblStudentTest
So, while specifying a new ADO.net Data Entity model, Do i need to select ALL the tables or group and select them (creating 2 or more models in the process) ?
(Disclaimer : ASP.net MVC newbie)
A: As Ladislav as answered, select all your tables and put them in a single model. If you have the relationships (primary and foreign keys) setup correctly in the database, these will be created in your entity model as well.
Creating two models would serve no purpose other than to make your life more difficult. I have used separate models only when I am dealing with multiple databases. In your case, it sounds like you only have one database.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566420",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: setTimeout Jquery help how can i settimeOut of 1 sec, for the following animation to take place, i tried using SetTimeout, but it didnt work, heres the code
$(document).ready(function(){
$('.caption_logo .flying-text').css({opacity:0});
$('.caption_logo .active-text').animate({opacity:1, marginLeft: "-350px"}, 500);
var intval = setInterval(changeText, 300);
function changeText(){
var $activeText = $(".caption_logo .active-text");
var $nextText = $activeText.next();
if($activeText.next().length == 0) clearInterval(intval);
$nextText.css({opacity: 0}).addClass('active-text').animate({opacity:1, marginLeft: "-350px"}, 500, function(){
$activeText.removeClass('active-text');
});
}
});
A: Can you try with setTimeout function like below:
$(document).ready(function(){
$('.caption_logo .flying-text').css({opacity:0});
$('.caption_logo .active-text').animate({opacity:1, marginLeft: "-350px"}, 500);
setTimeout(changeText, 300);
function changeText(){
var $activeText = $(".caption_logo .active-text");
var $nextText = $activeText.next();
if($activeText.next().length > 0) setTimeout(changeText, 300);
$nextText.css({opacity: 0}).addClass('active-text').animate(
{
opacity:1,
marginLeft: "-350px"
},
500,
function(){
$activeText.removeClass('active-text');
}
);
}
});
Hope it work for you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566424",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WebP library for C# It seems like there is no code samples for WebP in C#. Is there any? I don't need to display WebP images directly but saving & transferring as WebP would be nice.
A: WebP-wrapper
Wrapper for libwebp in C#. The most complete wapper in pure managed C#.
Exposes Simple Decoding API, Simple Encoding API, Advanced Encoding API (with compresion statistics), Get library version and WebPGetFeatures (info of any WebP file). In the future I´ll update for expose Advanced Decoding API.
The wrapper is in safe managed code in one class. No need for external dll except libwebp_x86.dll and libwebp_x64.dll (included v6.1). The wrapper work in 32, 64 bit or ANY (auto swith to the apropiate library).
The code is full comented and include simple example for using the wrapper.
A: Take a look at http://webp.codeplex.com/. There is a library that allows you to easily encode into WebP format. Check out this question for more information:
Convert Bitmap to WebP Image?
The library allows you to save into WebP format like so:
using (Image image = Image.FromFile("image.jpg"))
{
Bitmap bitmap = new Bitmap(image);
WebPFormat.SaveToFile("image.webp", bitmap);
}
A: there is a project in github
Wrapper for libwebp in C#. The most complete wrapper in pure managed C#.
Exposes Simple Decoding API and Encoding API, Advanced Decoding and
Encoding API (with stadistis of compresion), Get version library and
WebPGetFeatures (info of any WebP file). Exposed get PSNR, SSIM or
LSIM distortion metrics.
The wrapper is in safe managed code in one class. No need external dll
except libwebp_x86.dll and libwebp_x64.dll (included v6.1). The
wrapper work in 32, 64 bit or ANY (auto swith to the apropiate
library).
The code is full comented and include simple example for using the
wrapper.
see project page: https://github.com/JosePineiro/WebP-wrapper
A: There is https://github.com/mc-kay/libwebp-sharp wrapper project. But it doesn't seem to be implemented.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566426",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: ie7 css; position relative problem? Please have a look at the following url: http://server.patrikelfstrom.se/johan/fysiosteo/
I want the image to be on the right side of the content, so i made the container position: relative and the image position: absolute. Works great, except in IE7. So I would like to know how to fix it. Is it an IE bug, or did I miss something?
Thanks
A: It works fine in IE9...why don't you set the image as a background of the content block and position that background right (background-position property).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566434",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: OpenCV - How to defined a variable of type CvvImage in Opencv 2.3? I'm writing a program to capture image frames from a camera and to dispay them on the MFC picture control window. My program is using MFC in OpenCV 2.3 and Visual studio 2010.
but I am not able to use the function CvvImage.
It says it is undefined. This function comes under the highgui.h header file. When I check the header file and compared it with Opencv 1.0 I saw that this function is not defined here.
When I use this program on opencv 1.0 and visual studio 2008 it works fine. and executes.
but using visual studio 2010 and opencv 2.3 it is not defined.
please help use the CvvImage or tell me the equivalent used in opencv 2.3.
I do no want to use IplImage. because then I am not able to place my image frame on the MFC picture control window.
Thank you
A: WEll after many days thinking i finally got the answer.
What we need to do it to add a class CvvImage.cpp and the header file CvvImage.h to the open cv directory.
and in the main program we need to define #include "CvvImage.h"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566439",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to use Integer in freemarker template? Yesterday, when I attempted to get a variable value from action,
if I set the variable's which defined in ftl value up to below ten , the result always got empty.
<input type="hidden" name="orderId" id=orderId" value="9" />
public class OrderVo {
private Long id;
public Long getId() { return this.id; }
public void setId(Long id) { this.id = id; }
}
System.out.println("=============================" +vo.getOrderId());
the result was ""
Thank you at first,but it doesn't work.
I got it the day before yesterday!
Because for the release of the tomcat.
You may come across problem in the tomcat 6.x,but not 5.x.
A: Please see the following section in the freemarker manual.
http://freemarker.sourceforge.net/docs/ref_builtins_number.html
Cheers.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566442",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Load Database - how to show progress in progressBar? I'm trying to use a ProgressBar, which shows the progress of loading a database, which is in the local assets folder. I don't know if it's even possible this way, because I'm using code which was before for downloading a file from the internet.
I think that I would have to get the size of the database, but I have no idea how to do this. The conection.getContentLength() doesn't seem to work. May the conection doesn't contain the address assets/kneipen2.sqlite ?
This is in the onCreate():
new LoadFilesTask().execute("assets/kneipen2.sqlite");
And this is the AsyncTask inner class:
private class LoadFilesTask extends AsyncTask<String, Integer, Integer> {
@Override
protected Integer doInBackground(String... urls) {
//oeffneDatenbank();
int count;
try {
myDbHelper = new DataBaseHelper(Start.this);
try {
myDbHelper.createDataBase();
}
catch (IOException ioe) {
throw new Error("Unable to create database");
}
try {
myDbHelper.openDataBase();
} catch (SQLException sqle) {
throw sqle;
}
URL url = new URL(urls[0]);
//Ignore this! Only used to show that operations can take a long time to complete...
URLConnection conection = url.openConnection();
conection.connect();
int lenghtOfFile = conection.getContentLength();
// downlod File
InputStream input = new BufferedInputStream(url.openStream());
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
// publishing the progress....
publishProgress((int)(total*100/lenghtOfFile));
}
input.close();
} catch (Exception e) {}
return null;
}
So, there isn't shown a progress, but at the end the database is loaded correctly. Please help me.
A: ProgressDialog MyDialog = ProgressDialog.show( YourCurrentClass.this, "Please wait!" , "Loading..", true);
This might be of help
A: You can use it in two ways :
Either
preExecute() and postExecute() method of AsyncTask where in preExecute() just show thr progressDialog and in postExecute() dismiss the same.
or
Use Handler to show progress dialog and dismiss the same...
Hope u get what i say...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566445",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Can ClickOnce deployment technique be used in combination with Systems Management Server (SMS)? Can ClickOnce deployment technique be used in combination with Systems Management Server (SMS)?
What I have seen so far is that we have to publish an application on Web Server, FTP or network to be eligible for clickonce deployment. But our organization has policy of distributing applications through SMS only. Are there any ways to achieve this?
A: No, ClickOnce can not be used in combination with SMS.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566459",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: NHibernate map to inconsistent Data I am using NHibernate to map a DataModel. Unfotunatley the DataBase contains some inconsistent data due to lack of keys/constraints. Currently I am stuck with an m:n mapping where some keys on the map Table reference missing data.
Here is some sample Data:
Table: Foo
id Value
0 A
1 B
2 C
Table: Bar
id Value
10 X
20 Y
30 Z
Table: Map
foo_id bar_id amount
0 10 2
0 11 4
1 12 5
2 20 8
I want to fetch all the Foo, that also have a Bar. In (T)SQL i would just use a join. I've tired a couple of mappings (like references + nullable, etc), but since the mapping table contains a key, NHiernate seems to expect an entity.
Any suggestions?
A: You could use the not-found="ignore" attribute (NotFound.Ignore() in Fluent).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566460",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Sql Job running for 30 minutes then report successful We have a job that runs every night and rebuild the indexes on a customer database, however after installing the job, it runs successfully every night according to the history and finishes in around 30 minutes every night, however we found that the indexes that it should fix, are not actually fixed and still fragmented above the allowed level.
Is there anything that would stop a job from running more then 30 minutes? It currently doesn't have an end date on it.
A: The end date is about when a schedule (for determining when to start the job) should cease to be valid. There is a Shutdown Timeout setting in Sql Server Agent Properties, but that defaults to 15 seconds, and is about completing shutdown, rather than total execution time.
So...
Have you run the script manually?
How long does it take to complete?
Does it complete successfully according to your standards?
Related:
*
*SQL Agent: Set a Max Execution Time
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566461",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Two threads communicating I have a richTextBoxLog which is public and static.
After I declare it, I start a new thread which initializes new variable named proba. richTextBoxLog should get the value from proba.
The problem is, proba needs time to be initialized, and I want richTextBoxLog to initialize while proba is initializing.
I want to write something like:
richTextBoxLogFile.richTextBoxLog.Text += proba;
But, when I write it in the method which is called by the previously mentioned thread, I get an exception: "Cross-thread operation not valid: Control 'richTextBoxLog' accessed from a thread other than the thread it was created on."
Can I write something like this: stop the thread, then initialize richTextBoxLog, then start the thread again, then stop it, and the same continues while initializing richTextBoxLog ends.
Edit: I try to use this:
context.Post(new SendOrPostCallback(newMethod), (object)proba);
where context is the context of the main thread and newMethod initializes the value of richTextBoxLog. However, this call is in the method which is started by the new thread, in a while loop:
while (-1 != (ch = _reader.Read()))
{
Console.Write((char)ch);
proba += ((char)ch).ToString();
context.Post(new SendOrPostCallback(newMethod), (object)proba);
}
_complete.Set();
}
The problem I have now is that I want newMethod to be called every time when I enter in the while loop. But, what's happening is: the while loop finishes and after that newMethod is entered about thousand times.
A: You need to invoke the method with proba:
System.Windows.Threading.Dispatcher.CurrentDispatcher.Invoke(
new Action(() =>
{
//do stuff with proba
}
));
//edit:
wait, this is a little more complicated. The dispatcher is an object which can simply said execute methods from other threads. This means you need to create a dispatcher in the thread with proba and use that dispatcher in your other thread to execute the method like above.
A: I'd look into using the BackgroundWorker - it takes a lot of the pain out of operations like this.
http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx
Otherwise you need to use Control.Invoke to sync up the threads again - http://msdn.microsoft.com/en-us/library/system.windows.forms.control.invoke.aspx (you shouldn't, and often can't, access the UI from anything other than the UI thread)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566463",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: WCF + EF 4.1 Eager Loading and Serialization Problem The simple case where my OperationContract implementation is like:
public List<Directory> GetDirectories(bool includeFiles)
{
if (includeFiles)
{
return this.db.Directories.Include(e => e.Files).ToList();
}
else
{
return this.db.Directories.ToList();
}
}
where GetDirectories(false); works perfectly ok and GetDirectories(true); throws a CommunicationObjectFaultedException with message:
The communication object, System.ServiceModel.Channels.ServiceChannel,
cannot be used for communication because it is in the Faulted state.
Obviously my File entities have reference to Directory entities, and the Directory entities have a list of files. First I thought this would be the typical cyclic reference trap but I get no signs of it in the exception message. Any ideas on this problem?
A: It will be cyclic reference trap (here is something about this topic) and reason for your CommunicationObjectFaultedException will be something like:
using (var client = new ServiceClient())
{
data = client.GetDirectories(true);
}
The reason is that unhandled exception has faulted the channel and using is trying to call Close on that faulted channel - it is invalid transition in channel state machine (and one big WCF strangeness) resulting it the exception you mentioned. There are many ways to avoid it but the basis is:
ServiceClient client = null;
try
{
client = new ServiceClient();
data = client.GetDirectories(true);
}
finally
{
if (client != null)
{
if (client.State == CommunicationState.Faulted)
{
client.Abort();
}
else
{
client.Close();
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566466",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Is there a way to add and detach an event handler without loosing scope? Working with asynchronous classes, often I find that I am always having to store state in fields so that I have access to them in the completed method. Ideally, I'd like to avoid having to store state in fields as this means I need to worry about multiple calls being made and their affect on the field data.
I wrote this block of code which could work, although Resharper gives me an 'access to modified disclosure' warning.
public void Test(Action<Result> result)
{
var myClass = new MyClass();
EventHandler eventHandler = null;
eventHandler = (s, e) =>
{
var mc = (MyClass) s;
mc.Completed -= eventHandler;
result(mc.Result);
};
myClass.Completed += eventHandler;
myClass.Run();
}
Is there a problem with this block of code and if not, is there a better way to do this without creating fields to store data and ensure that some level of scope still exists?
A: Your usage of an anonymous delegate in this context is absolutely fine. For a discussion on the specific ReSharper warning, see the following question which discusses it in detail:
Access to Modified Closure
I use the pattern you have illustrated quite often in WPF / Silverlight / WP7 application when you want to execute some code just once when the UI is first loaded or rendered.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566472",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C# 3D wpf gradient colour depending Z C#
I want to t ouse the LinearGradientBrush with absolute cordinates so the pixel colour
of each objects reflactes the height but I do not understand how to use the LinearGradientBrush.
But how is this applied to "only" the Z value of each object.
In my example I want the colour to shade from blue to read from cordinates -100 to 100
LinearGradientBrush myG= new LinearGradientBrush();
myG.MappingMode = BrushMappingMode.Absolute;
myG.StartPoint = new Point(0, -100);
myG.EndPoint = new Point(0, 100);
myG.GradientStops.Add(new GradientStop(Colors.Blue, 0));
myG.GradientStops.Add(new GradientStop(Colors.Red, 1));
Material material = new DiffuseMaterial(myG);
Regards Stefan
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7566474",
"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.