text stringlengths 8 267k | meta dict |
|---|---|
Q: parsing text file in objective C i am trying to parse a text file saved in doc dir below show is the code for it
NSArray *filePaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES);
NSString *docDirPath=[filePaths objectAtIndex:0];
NSString *filePath=[docDirPath stringByAppendingPathComponent:@"SKU.txt"];
NSError *error;
NSString *fileContents=[NSString stringWithContentsOfFile:filePath];
NSLog(@"fileContents---%@",fileContents);
if(!fileContents)
NSLog(@"error in reading file----%@",error);
NSArray *values=[fileContents componentsSeparatedByString:@"\n"];
NSLog(@"values-----%@",values);
NSMutableArray *parsedValues=[[NSMutableArray alloc]init];
for(int i=0;i<[values count];i++){
NSString *lineStr=[values objectAtIndex:i];
NSLog(@"linestr---%@",lineStr);
NSMutableDictionary *valuesDic=[[NSMutableDictionary alloc]init];
NSArray *seperatedValues=[[NSArray alloc]init];
seperatedValues=[lineStr componentsSeparatedByString:@","];
NSLog(@"seperatedvalues---%@",seperatedValues);
[valuesDic setObject:seperatedValues forKey:[seperatedValues objectAtIndex:0]];
NSLog(@"valuesDic---%@",valuesDic);
[parsedValues addObject:valuesDic];
[seperatedValues release];
[valuesDic release];
}
NSLog(@"parsedValues----%@",parsedValues);
NSMutableDictionary *result;
result=[parsedValues objectAtIndex:1];
NSLog(@"res----%@",[result objectForKey:@"WALM-FT"]);
The problem what i am facing is when i try to print lineStr ie the data of the text file it is printing as a single string so i could not able to get the contents in line by line way please help me solve this issue.
A: Instead use:
- (NSArray *)componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
it covers several different newline characters.
Example:
NSArray *values = [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
for (NSString *lineStr in values) {
// Parsing code here
}
ALso seperatedValues is over released. First one is created with alloc init, then on the next line it is replaced by the method componentsSeparatedByString. So the first one od lost without being released, that is a leak. Later the seperatedValues created by componentsSeparatedByString is released but it is already auto released by componentsSeparatedByString to that is an over release;
Solve all the retain/release/autorelease problem with ARC (Automatic Reference Counting).
Here is a version that uses convenience methods and omits over release:
NSArray *values = [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
for (NSString *lineStr in values) {
NSArray *seperatedValues = [lineStr componentsSeparatedByString:@","];
NSString *key = [seperatedValues objectAtIndex:0];
NSDictionary *valuesDic = [NSDictionary dictionaryWithObject:seperatedValues forKey:key];
[parsedValues addObject:valuesDic];
}
NSLog(@"parsedValues---%@",parsedValues);
A: Are you sure the line separator used in your text file is \n and not \r (or \r\n)?
The problem may come from this, explaining why you don't manage to split the files into different lines.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527657",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to trigger jQuery from GMaps infowindow I want to trigger jQuery from a GMap info window. I have these code for my GMap:
var theContent = "<form action='#' method='post' onSubmit='return false;'><input type='text' name='firstname' />";
theContent += "<input type='submit' value='Save' /></form>";
var infowindow = new google.maps.InfoWindow({
content: theContent
});
infowindow.open( map, marker);
and these code for jQuery:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function() {
$('form').bind('submit',function() {
var str = $('form').serialize();
$.ajax({
type: "POST",
url: "save.php",
data: str,
success: function(msg){
alert('Saved!');
}
});
return false; //so the page won't refresh
});
});
</script>
The problem is, my input to the infowindow textbox isn't saving, that's why I think jQuery isn't triggered inside GMap infowindow/bubble.
When I tried the form outside GMap, it works fine.
Thanks for any help!
A: Right now, the jQuery code is binding to the form on document ready, but not necessarily when the info window is open. Therefore, it's possible you are binding to the form when the infowindow is not even part of the DOM, which is not possible. You need to either:
*
*Call $('form').bind(...) RIGHT AFTER infowindow.open(...) OR
*Change $('form').bind(...) to $('form').live(...). This will target all present and future forms on the page.
A: When is the InfoWindow being created, i.e. when is that top script being executed? There's not enough information to tell here, but a likely reason could be because you're trying to use jQuery to bind to the form submit before that form has been created.
Try binding to the form once you've created the InfoWindow.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527660",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: get_class_var on child class I have the following setup:
abstract class AParentLy{
private $a;
private $b;
function foo(){
foreach(get_class_vars(get_called_class()) as $name => $value){
echo "$name holds $value";
}
}
}
class ChildClass extends AParentLy{
protected $c='c';
protected $d='d';
}
$object = new ChildClass();
$object->foo();
What I want it to output is:
c holds c
d holds d
What it does output is:
c holds c
d holds d
a holds
b holds
The get_called_class() method correctly outputs "ChildClass"
I'm fairly new to class inheritance in PHP and from what I can gather the problem lies somewhere in the so scope. But I can't figure out how to make it work.
(The somewhat questionable solution would be to just go ahead and add a great big if($name!='a' && $name!='b' ...~ into the mix. But I'm sure there must be another, more sane and stable way to do this)
A: Change the visibility of Child's properties to PROTECTED.
When properties are private, its not visibles.
More info at:
http://php.net/manual/en/language.oop5.visibility.php
A: class Parent1 {
//private $a;
//private $b;
function foo(){
foreach(get_object_vars($this) as $name => $value){
echo "$name holds $value";
}
}
}
class Child1 extends Parent1 {
protected $c='c';
protected $d='d';
}
Parent is a reserved name.
in class Parent1 you can see $a and $b so removed.
changed $c/$c to protected.
the other solution would be:
class Parent1 {
private $a;
private $b;
}
class Child1 extends Parent1 {
private $c='c';
private $d='d';
function foo(){
foreach(get_object_vars($this) as $name => $value){
echo "$name holds $value<br>";
}
}
}
putting foo in Child
EDIT
Sorry to wake an old post. I think i have a preferable solution (actually 2 solutions) for this:
The first one is to use a middle class that will create a barrier between the parent and the child:
abstract class Parent1 {
private $a;
private $b;
abstract function foo();
}
class ParentClone1 {
function foo(){
foreach(get_object_vars($this) as $name => $value){
echo "$name holds $value<br />";
}
}
}
class Child1 extends ParentClone1 {
protected $c='c';
protected $d='d';
}
$c = new Child1();
$c->foo();
// c holds c
// d holds d
The other solution is to use visibility:
If you call get_class_vars()/get_object_vars() from inside a class, it sees all the variables (including private/protected). If you run it from outside it will only see public:
function get_object_vars_global($class){
return get_object_vars($class);
}
abstract class Parent1 {
private $a;
private $b;
function foo(){
foreach(get_object_vars_global($this) as $name => $value){
echo "$name holds $value<br />";
}
}
}
class Child1 extends Parent1 {
public $c='c';
public $d='d';
}
$c = new Child1();
$c->foo();
since this will result in putting class fields as public, I'd go with the first solution.
A: Had another go at the whole experiment this question was a part of.
The eventual solution (just in case anyone stumbles over this and has the same problem) I came to was to create the following method within the parent class:
function get_properties(){
foreach(get_class_vars(get_called_class()) as $name => $value){
if(!in_array($name,array_keys(get_class_vars('Parent')))){
$r[$name]=$this->$name;
}
}
return $r;
}
with this you get every parameter (and their value) of the child class without any of the parent class. You'll have to change the function a bit if you ever change the class name, but at least for me this was a workable solution.
A: First some basic mistakes:
*
*Don't use a $ in a function name (here: $foo), this will result into a syntax error.
*You shouldn't name a class Parent, because it is a reserved word.
Calling this would result into an error like Fatal error: Cannot use 'Parent' as class name as it is reserved
There is a good example how it works in the php manual, and there can be found this important sentence, which answers your question:
Class members declared public can be accessed everywhere. Members
declared protected can be accessed only within the class itself and by
inherited and parent classes. Members declared as private may only be
accessed by the class that defines the member.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527662",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: WebView is not getting display in the AlerDialog I am trying to display 'WebView' in 'AlertDialog'.
For that I referred one of the question posted here: Displaying WebView in AlertDialog
It successfully opens the dialog window. But I dont know some how its not showing the web content.
This is my 'print_webview' file, which I am inflating in AlertDialog window:
'<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/root">
<WebView
android:id="@+id/dialog_webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
</LinearLayout>'
This is my Java file:
'public class CloudPrintTest extends Activity {
static final int GOOGLE_CLOUD_PRINT_DIALOG = 1; //dialog ID for google cloud print
/** Called when the activity is first created. */
Button printButton;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
printButton = (Button)findViewById(R.id.button1);
printButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
//startActivity(new Intent(CloudPrintTest.this,PrintDialog.class));
showDialog(GOOGLE_CLOUD_PRINT_DIALOG);
}
});
}
@Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
switch(id){
case GOOGLE_CLOUD_PRINT_DIALOG:
//LayoutInflater layoutInflator = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//final View dialogLayout = layoutInflator.inflate(R.layout.print_webview, null);
LayoutInflater inflater = LayoutInflater.from(CloudPrintTest.this);
View alertDialogView = inflater.inflate(R.layout.print_webview, null);
WebView myWebView = (WebView)alertDialogView.findViewById(R.id.dialog_webview);
myWebView.getSettings().setJavaScriptEnabled(true);
myWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
myWebView.setWebViewClient(new PrintTestWebViewClient());
myWebView.loadUrl("http://www.google.com/");
AlertDialog.Builder builder = new AlertDialog.Builder(CloudPrintTest.this);
builder.setView(alertDialogView);
builder.setTitle("Google Cloud Print");
builder.setCancelable(true);
AlertDialog printDialog = builder.create();
return printDialog;
}
return null;
}
private class PrintTestWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
}'
I have tried all the possible ways, but didnt get the result.
Please help.
Regards
A: What i would suggest is you creating an activity.
And when you register it in your manifest. Give it the Dialog look with
<activity android:theme="@android:style/Theme.Dialog">
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527665",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Android - Problem with the Serializable interface I have been using the Serializable interface to pass an object from one activity to another. I am using putExtra on the sender side and getSerializable on the receiver side. Everything works fine but I have received (for the first time) the following error report:
java.lang.RuntimeException: Parcelable encountered IOException reading
a Serializable object
I don't understand why this exception has been generated since I am using getSerializable and not getParcelable.
I know that I should implement the Parcelable interface instead because it has been designed specifically for Android (and that's what I will end up doing) but I want to understand why I am getting this error.
Thanks!
A: Parcelable is mentioned in this error because an Intent you send from one Activity to another has a Bundle inside and this Bundle is Parcelable. When you call Intent.putExtra() this extra is added to the inner Bundle. When Intent is passed between activities its Bundle is converted to and from a byte array and so is your Serializable object.
But I don't know why this error occurs. Maybe it's because of some bug in writeObject()/readObject() implementation.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527670",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: What is the most effective way to move items within a vector? I've seen some special cases where std::rotate could be used or a combination with one of the search algorithms but generally: when one has a vector of N items and wants to code function like:
void move( int from, int count, int to, std::vector<int>& numbers );
I've been thinking about creation of a new vector + std::copy or combination of insert/erase but I can't say I ended up with some nice and elegant solution.
A: Depending on the size of the vector and the ranges involved, this might be less expensive than performing copy/erase/insert.
template <typename T>
void move_range(size_t start, size_t length, size_t dst, std::vector<T> & v)
{
typename std::vector<T>::iterator first, middle, last;
if (start < dst)
{
first = v.begin() + start;
middle = first + length;
last = v.begin() + dst;
}
else
{
first = v.begin() + dst;
middle = v.begin() + start;
last = middle + length;
}
std::rotate(first, middle, last);
}
(This assumes the ranges are valid and they don't overlap.)
A: Pre-C++11 (although the following remains valid) you can get more efficient "moves" for contained types which specialise/overload std::swap. To take advantage of this, you would need to do something like
std::vector<Foo> new_vec;
Foo tmp;
for (/* each Foo&f in old_vec, first section */) {
swap (f, tmp);
new_vec .push_back (tmp);
}
for (/* each Foo&f in old_vec, second section */) {
swap (f, tmp);
new_vec .push_back (tmp);
}
for (/* each Foo&f in old_vec, third section */) {
swap (f, tmp);
new_vec .push_back (tmp);
}
swap (new_vec, old_vec);
The above may also give good results for C++11 if Foo has a move-operator but hasn't specialised swap.
Linked lists or some clever sequence type might work out better if Foo doesn't have move semantics or an otherwise-optimised swap
Note also that if the above is in a function
std::vector<Foo> move (std::vector<Foo> old_vec, ...)`
then you might be able to perform the whole operation without copying anything, even in C++98 but for this to work you will need to pass by value and not by reference, which goes against the conventional prefer-pass-by-reference wisdom.
A: It's always important to profile before jumping to any conclusions. The contiguity of vector's data memory may offer significant caching benefits that node-based containers don't. So, perhaps you could give the direct approach a try:
void move_range(size_t start, size_t length, size_t dst, std::vector<T> & v)
{
const size_t final_dst = dst > start ? dst - length : dst;
std::vector<T> tmp(v.begin() + start, v.begin() + start + length);
v.erase(v.begin() + start, v.begin() + start + length);
v.insert(v.begin() + final_dst, tmp.begin(), tmp.end());
}
In C++11, you'd wrap the iterators in the first and third line into std::make_move_iterator.
(The requirement is that dst not lie within [start, start + length), or otherwise the problem is not well-defined.)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527674",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: Machine-readable (WebIDL) reference for JavaScript / HTML5? I'm looking for a machine-readable reference of JavaScript classes (members, methods, parameters...), especially related to the HTML5 standard (canvas, storage, etc.).
All I have found so far is the specs on the W3C site, which include a part of the specification, f.i. http://dev.w3.org/html5/2dcontext/ has in it the Web IDL for CanvasRenderingContext2D, and other pages have other portions.
But I must be blind as I couldn't find some global index/summary with all the valid IDLs sorted and classified by version/drafts/etc.
Anyone know where it can be found?
A: HTML5 is still changing, so any official reference bar the spec is almost inevitably going to be out of date.
Your best bet is to suck the data straight out of the spec. Parse the file and then extract all the pre elements with class idl. That's your machine readable list. Guaranteed official and up-to-date.
A: Asked Ian Hickson (editor of the spec at the time of this answer), here is an edited summary of his reply:
There is not a single document that contains all the IDL fragments, no.
[so the HTML spec documents constitute the reference for WebIDL]
FWIW, I recommend using this source:
http://whatwg.org/c
It's more canonical than the W3C copies.
A blind extraction [of the <pre class="idl"> elements] should mostly work. It'll need a little massaging, but
not much. Make sure to exclude the class="idl extract" blocks.
I actually do do a blind extraction as part of the spec generation
process, to verify that the IDL syntax is correct (or rather, that all the
mistakes are intentional... I occasionally use syntax that isn't specced
in the WebIDL spec yet).
A: Not sure if it is WebIDL, but the WebKit Source has lots .idl files mixed in with the .cpp and .h files. You can browse the source online. Start at WebCore and dig into some of the subdirectories.
A: Are you looking for this?
http://code.haskell.org/yc2js/W3C/
A: The WebIDLs used by Mozilla can be found at http://mxr.mozilla.org/mozilla-central/source/dom/webidl/
A: See below link:
Dependent Specifications:
http://www.w3.org/wiki/Web_IDL#Dependent_Specifications
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527681",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "16"
} |
Q: WebClient Retry Is it possible to retry a webclient request? On the odd occasion my application will throw an error when attempting to connect to an xml web service but if I retry, it works OK. I'd like it to retry 2 times before throwing an error unless someone has a better solution :)
private void ApplicationBarLogin_Click(object sender, EventArgs e)
{
settings.UsernameSetting = Username.Text;
if (RememberPassword.IsChecked == true)
{
settings.PasswordSetting = Password.Password;
settings.RememberPasswordSetting = true;
}
else
{
settings.RememberPasswordSetting = false;
}
WebClient internode = new WebClient();
internode.Credentials = new NetworkCredential(settings.UsernameSetting, settings.PasswordSetting);
internode.DownloadStringCompleted += new DownloadStringCompletedEventHandler(internode_DownloadStringCompleted);
internode.DownloadStringAsync(new Uri("https://customer-webtools-api.internode.on.net/api/v1.5/"));
}
public void internode_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
MessageBox.Show(e.Error.Message);
}
else
{
MessageBox.Show("Authentication successfull.");
}
}
A: If you get a failure, you could re-issue the request. By keeping count of the number of times you re-issue the request you can determine when to show the user an error. Here is a quick modification to your code to demonstrate what I mean.
private void ApplicationBarLogin_Click(object sender, EventArgs e)
{
settings.UsernameSetting = Username.Text;
if (RememberPassword.IsChecked == true)
{
settings.PasswordSetting = Password.Password;
settings.RememberPasswordSetting = true;
}
else
{
settings.RememberPasswordSetting = false;
}
WebClient internode = new WebClient();
internode.Credentials = new NetworkCredential(settings.UsernameSetting, settings.PasswordSetting);
internode.DownloadStringCompleted += new DownloadStringCompletedEventHandler(internode_DownloadStringCompleted);
internode.DownloadStringAsync(new Uri("https://customer-webtools-api.internode.on.net/api/v1.5/"));
}
private int _retryCount = 0;
public void internode_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{
_retryCount++;
if (_retryCount < 3)
{
WebClient internode = (WebClient)sender;
internode.DownloadStringAsync(new Uri("https://customer-webtools-api.internode.on.net/api/v1.5/"));
}
else
{
_retryCount = 0;
MessageBox.Show(e.Error.Message);
}
}
else
{
_retryCount = 0;
MessageBox.Show("Authentication successfull.");
}
}
A: WebClient doesn't have any built in retry functionality.
You should look to build the retry logic yourself before, probably, informing the user of the problem.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527682",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Cached data not expiring in Sinatra/memcached app I have a Sinatra app on Heroku and I fetch data from many 3rd party APIs and store it in memcache, to speed up load time.
But the data is not updating: the data that is loaded in the first time after enabling the plugin stays in the memcache all the time and it does not expire.
Here are parts of my code:
set :cache, Dalli:client.new
configure do
set :cache_default_expiry, 300
end
def get_apidata()
apidata = settings.cache.get('apidata')
if apidatadata.nil?
# getting data from API
settings.cache.set('apidata',apidata)
Where is problem in my code, why isn't cached data expiring?
A: From my tests set :cache_default_expiry does not work. What you can do instead is this:
set :cache, Dalli::Client.new(ENV['MEMCACHE_SERVERS'],
:username => ENV['MEMCACHE_USERNAME'],
:password => ENV['MEMCACHE_PASSWORD'],
:expires_in => 300)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527685",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: UIProgressbar update method Hello i'm trying to write a method that update a UIProgressbar !
The problem is that when both of values arrive fine to the method (NSLog display values)
the division operation generate a bad_access when i run the application !!
I tried many messages from both value like intValue/inValue ...
Help me to solve this issue and how can I print values of NSNumber
-(void)UpdateProgressbar:(NSNumber *)currentOperationNumer TotalOperationNumber:(NSNumber*)n
{
NSLog(@" operation : %i",currentOperationNumer);
NSLog(@" total : %i",n);
if (currentOperationNumer<=n)
{
[downloadBar setProgress:(currentOperationNumer/n )];
NSLog(@"progress !");
}
else
{
[self.view removeFromSuperview];
}
}
A: try [currentOperationNumber intValue] in place of currentOperationNumber (or floatValue if setProgress expects a float). So....
int myProgress = [currentOperationNumber intValue] / [n intValue];
[downloadBar setProgress:myProgress];
Actually, isn't it a float value it expects in there?
A: NSNumber is an object wrapper for various primitive types, with what you are doing you are trying to divide a pointer by a pointer..
maybe try chaining the code to..
[downloadBar setProgress:([currentOperationNumer intValue] / [n intValue])];
A: You can print value by using following code
-(void)UpdateProgressbar:(NSNumber *)currentOperationNumer TotalOperationNumber:(NSNumber*)n
{
NSLog(@" operation : %@",currentOperationNumer);
NSLog(@" total : %@",n);
if (currentOperationNumer<=n)
{
[downloadBar setProgress:(currentOperationNumer/n )];
NSLog(@"progress !");
}
else
{
[self.view removeFromSuperview];
}
}
A: The best way to debug EXC_BAD_ACCESS:
*
*If you are not using XCode 4, then upgrade.
*In XCode 4, press CMD-I to run Instruments.
*Select the Zombies profile. (Background: EXC_BAD_ACCESS means you are sending a message to a deallocated object. Zombies turns on the zombie feature, so that objects with a retain count of 0 are not deallocated, but kept as a zombie. The NSZombie class raises an exception whenever a message is sent to it - thus it can be trapped, and identified the point of origin.)
*Run your app via Instruments. When it crashes, Instruments will be brought to the foreground with a pop-up callout that indicates the memory that was freed but accessed.
*You can click the little arrow in the lower right corner, this will give you that memory's alloc/retain/release history, and the code that performs the action. Click on the source column, it will take you to that line in the code.
A: make it sure downloadBar.progress is a float and it's from 0.0 to 1.0 inclusive.
Please, try this:
float current = 0.0f;
float count = 100.0f;
while (stuff..) {
downloadBar.progress = current / count;
}
it should work without problems.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527694",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Start Alarm on Android without having the application running My idea is to set an alarm for a specific date in my application, but I want to be able to have the alarm ringing at the set date, even if my application isn't running at all.
How can I achieve this?
Thanks in advance!
A: I'd start a service when the device is booted - that service should take care about the alarming when the time has come.
To make your service be started at boot time you need the following things in your AndroidManifest.xml
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
in the <manifest> tag
<receiver android:name="com.yourpackage.AlarmingBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
in your <application> tag
Additionally you need your AlarmingBroadcastReceiver, should look something like that to start the service:
public class AlarmingBroadcastreceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent startServiceIntent = new Intent(context, AlarmingService.class);
context.startService(startServiceIntent);
}
}
whereas AlarmingService.class is the class name of your service that finally takes care about the alarming stuff
A: You will need to create a onBoot BroadCast Receiver so when the device is started your application will get control to set up alarms.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527700",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What data does Bing maps send and receive from the Microsoft servers? I have a Bing Maps control in a silverlight application.
The application is to be deployed on a company network which has a very tight security policy and so they need to know what data is going to be sent/recieved over the connection to the Microsoft servers.
Can anyone point me in the right direction with regards to data connections etc. I understand that the control sends a licence and recieves map tiles but I don't know how.
A: The only data that gets sent from the Bing Maps control to Bing's servers is your application key, which is used to log a transaction recording the start of your session. This is done by a call to the service at http://dev.virtualearth.net/webservices/v1/LoggingService/LoggingService.svc. The service sends back an authentication result code and a session id which is assigned for the rest of the session.
In terms of data received from Bing's servers to the Map Control - if you use one of the built-in map styles (aerial/road etc.), then the tile images are requested from one of the tile servers in the edge caching network, which have URLs as follows:
http://ecn.t0.tiles.virtualearth.net
http://ecn.t1.tiles.virtualearth.net
http://ecn.t2.tiles.virtualearth.net
http://ecn.t3.tiles.virtualearth.net
That's it. If you load a tile layer from a local tile source then no content gets transferred from Bing. Nothing ever gets sent to Microsoft relating to any shapes or other data plotted on the map.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527703",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: List to appear on clicking event I want to have a child list appear on clicking a point of the parent list (similar to how clicking can minimize and maximize the content table in Wikipedia articles), how can I achieve it?
I've learned basic HTML years ago, and can't remember how to do this even if I did learn it. Thanks for the help.
A: Withou any scripting (JavaScript or jQuery) you can't do this.
Here is example with jQuery:
js
$('#nav > li').click(function() {
$(this).find('ul').toggle();
});
html:
<ul id="nav">
<li>Menu item</li>
<li>Menu item</li>
<li>Menu item</li>
<li>Menu item</li>
<li>Menu item
<ul class="sub-menu">
<li>Menu item</li>
<li>Menu item</li>
<li>Menu item</li>
</ul>
</li>
</ul>
Code: http://jsfiddle.net/4mgqK/2/
A: Do you mean a treeview? If so, something like jsTree might be fit for your purposes.
If you just need to show or hide a block of HTML (contained in a div element, for example) then jQuery toggle might be what you need.
A: You can use javascript to accomplish this. If you use jQuery, it's very easy to do this, but you'll have to add jQuery to your page. More information about basic jQuery can be found here:
http://docs.jquery.com/How_jQuery_Works
If you import jQuery, you can do it this way:
$("#parentElementId").click(function()
// if your parentElement has been clicked, excecute this function
{
$("#childElementId").show(); // if it has been hidden before with css(display:none)
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527708",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How do I redirect all Sub folders and directories to the main root excluding files? Basically I have a CDN setup.
/public_html/
index.html
/files/
image/
video/
video2/video2
I want to redirect ALL sub folders and directories to the main folder - except file extensions, so if someone loads a file, I want that to load, just so people cant view directories. (I dont want to see a 404 or forbidden message, just want the directory to go to the main page)
It would save me from uploading index.php redirects. Can this be done with .htaccess?
A: # don't show any files in the folder
IndexIgnore *
ErrorDocument 403 /
ErrorDocument 404 /
RewriteEngine On
# disabled user to access directly to the files folder.
RewriteRule ^files(\/?)$ - [F]
# images
RewriteRule ^image/(.*)\.(jpg|png|jpeg|gif)$ /files/$1.$2 [L]
# video
RewriteRule ^video/(.*)\.(flv|avi|mov)$ /files/$1.$2 [L]
#etc...
If you have sub folders, the (.*) will automatically use it. Example:
http://www.domain.com/image/i.png => /files/i.png
http://www.domain.com/image/sub1/sub2/i.png => /files/sub1/sub2/i.png
Here some links that will help you:
http://www.javascriptkit.com/howto/htaccess.shtml
http://www.htaccess-guide.com/
http://net.tutsplus.com/tutorials/other/the-ultimate-guide-to-htaccess-files/
http://www.bloghash.com/2006/11/beginners-guide-to-htaccess-file-with-examples/
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527709",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Q: How to change webview color at time of loading URL? In my app,
I open a url in webview,
But it takes some time to open a url in webview,
Within that time webview shows white background,
I want to change that background.
I try with
webView.backgroundColor=[UIColor blackColor];
It"s not work for me
So,How can i do that?
A: - (void)webViewDidFinishLoad:(UIWebView *)webView
{
webView.backgroundColor=[UIColor whiteColor];
}
- (void)webViewDidStartLoad:(UIWebView *)webView
{
webView.backgroundColor=[UIColor blackColor];
}
A: while create
[webView setBackgroundColor:[UIColor clearColor]];
[webView setBackgroundColor:[UIColor purpleColor]];
[webView setOpaque:NO];
- (void)webViewDidFinishLoad:(UIWebView *)webView{
[webView setOpaque:YES];
[webView setBackgroundColor:[UIColor whiteColor]];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527710",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: DevExpress: How to change the backcolor of a SearchLookUpEdit control I want to change the BackColor of the PopUp control that is shown if you select the DropDown button in an SearchLookUpEdit but I can't find an appropriate property to do this.
Btw. I use a defaultLookAndFeel object with Style set to "UltraFlat" so I can't define it within the skin.
A: With a little help from devexpress support: http://www.devexpress.com/Support/Center/p/Q345598.aspx
Private Sub SearchLookUpEdit1_Popup(sender As System.Object, _
e As System.EventArgs) Handles SearchLookUpEdit1.Popup
Dim popupControl As Control = CType(sender, IPopupControl).PopupWindow
popupControl.BackColor = Color.LightBlue
Dim lc As LayoutControl = CType(popupControl.Controls(2).Controls(0), LayoutControl)
Dim lcgroup As LayoutControlGroup = CType(lc.Items(0), LayoutControlGroup)
lcgroup.AppearanceGroup.BackColor = Color.LightBlue
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527712",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Hibernate criteria results I think this is a very simple question. but unfortunately I cannot find a solution.
I have a mysql database table called "Invoice" having "inv_No","inv_netvalue","inv_date" inv_No is the primary key. I want to get a Invoice object according to a given inv_No. I used a critaria. But this result nothing. list.size() is 0.
Invoice invoice = new Invoice();
invoice.setInvNo(Integer.parseInt(invoiceNo));
Session session = HSession.getSession();
Criteria crit = session.createCriteria(Invoice.class);
crit.add(Example.create(invoice));
List list=crit.list();
but when I used this "FROM Invoice invoice WHERE invoice.invNo='" + invoiceNo + "'" it returns which I expected.
Any one help me please.Let me know where I am wrong..
A: It's not clear to me why you've got the second createCriteria call. Have you tried this?
Criteria crit = session.createCriteria(Invoice.class);
crit.add(Example.create(invoice));
That follows some of the examples in the docs, for example.
EDIT: Another option is not to use "query by example" but just:
Criteria crit = session.createCriteria(Invoice.class);
crit.add.(Restrictions.eq("invNo", Integer.parseInt(invoiceNo)));
A: Criteria criteria = session.createCriteria(Invoice.class);
criteria.add.(Restrictions.eq("invNo", Integer.parseInt(invoiceNo)));
is the best way to get the results.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527715",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to use Scroll on JPanel? (Swing) I'm actually having no problem when dealing with the JScrollPane with JTextArea...
But here... I have a JPanel. And I wanted to use Scroll on it.
Take a look on my JPanel here Image Preview.
I wonder how to do it in netbeans. I think I should do a bit of customized coding.
So, I tried to do like this;
1) Right Click on jPanel2, Customize Code.
2) Using This modified code;
Initialization Code:
jPanel2 = new javax.swing.JPanel();
scrb = new javax.swing.JScrollPane(jPanel2);
// Code of sub-components - not shown here
// Layout setup code - not shown here
scrb.setPreferredSize(jPanel2.getPreferredSize());
jPanel1.add(jPanel2, "card2");
Variable Declaration Code:
private javax.swing.JPanel jPanel2;
private javax.swing.JScrollPane scrb;
Then re-run my Project again....
but,... sigh. THe Scroll didn't came up into the running app.
Is there anything I forget over here?
I tried to manipulate the Size of the jPanel2, but hence not work....
The Scroll didn't appeared.
A: The problem is in this line:
jPanel1.add(jPanel2, "card2");
Instead of this write this:
jPanel1.add(scrb, "card2");
What you are doing is adding jPnael2 to a scrollpant but then instead of adding that scrollpane to jPanel1 you add jPanel2 to jPanel1 so scrollPane doesn't even come to picture.
A: Try adding the scrb to jpanel1.
Here's a nice tutorial in scroll panes;
http://download.oracle.com/javase/tutorial/uiswing/components/scrollpane.html
A: In addition to the other suggestions to add the scrollpane to the panel, I'm not sure if it will work because of the following line of code:
scrb.setPreferredSize(jPanel2.getPreferredSize());
Scrollbars only appear when the preferred size of the component added to the the scrollpane is greater than the size of the scrollpane. So if you layout manager respects the preferred size of the components this condition will never be true.
A: If you are using NetBeans IDE, it is better to use GUI designer to create scroll pane. Use the below steps to implement a scroll pane:
1. In Netbeans GUI editor, select all panels which requires scroll pane using CTRL+left click
2. Right click on the highlighted panels, select the option 'Enclose in' -> Scroll Pane. This will add a scroll pane for the selected panels.
3. If there are other elements than Panel(say JTree), select all the elements ->Enclose in ->Panel. Then enlose the new parent panel to scroll pane
4. Make sure that 'Auto Resizing' is turned on for the selected parent panel(Right click on panel -> Auto resizing -> Tick both Horizontal and vertical)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527716",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Any way to get JSON data of a Google Doc SpreadSheet using jquery without make the doc public? I am trying to get data from a Google Doc Spreadsheet, using javascript and jQuery, in order to do some math with the numbers.
With the next code I got it, for public spreadsheets:
function getdata( key, wid, f )
{
return $.getJSON(
'//spreadsheets.google.com/feeds/cells/' +
key + '/' + wid + '/public/basic?alt=json-in-script&callback=?',
function( data ){
/* the content of this function is not important to the question */
var entryidRC = /.*\/R(\d*)C(\d*)/;
var retdata = {};
retdata.mat = {};
for( var l in data.feed.entry )
{
var entry = data.feed.entry[ l ];
var id = entry.id.$t;
var m = entryidRC.exec( id );
var R,C;
if( m != null )
{
R = new Number( m[ 1 ] );
C = new Number( m[ 2 ] );
}
var row = retdata.mat[ R ];
if( typeof( row ) == 'undefined' )
retdata.mat[ R ] = {};
retdata.mat[ R ][ C ] = entry.content;
}
if( typeof( f ) != 'undefined' )
f( retdata )
else
console.log( retdata );
}
);
}
When tried for private ones, I got the data in XML (using the URL:
'//spreadsheets.google.com/feeds/cells/'+ key + '/' + wid + '/private/basic' ). This test checks also for the availability, the firewall, the permission setup and the login state of the current user.
But adding the last part: ?alt=json-in-script&callback=f to get the data in JSON, throws an Not found, Error 404. (Also got if only alt=json is added).
Summary of situation:
public private
XML yes yes
JSON yes Question
The use of JSON against google is described in http://code.google.com/intl/es/apis/gdata/docs/json.html
The use of google spreadsheet api is described in
http://code.google.com/intl/es/apis/spreadsheets/data/3.0/reference.html#WorksheetFeed
Any way to get JSON data of a GDoc SpreadSheet using javascript without make the doc publicly available?
Thanks in advance
A: "Note: Retrieving a feed without authentication is only supported for published spreadsheets."
Shame, because this would be a very useful feature. As it is, I'm pleased to learn that this is possible at least from published docs.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527720",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
} |
Q: RMI stub for JMX in tomcat I am creating an RMI stub for JMX similar to the instructions in this blog post, and it opens a listening port as expected. When I try to connect to the port with JMX I get the following error:
java.io.IOException: Failed to retrieve RMIServer stub: javax.naming.NameNotFoundException: jmxrmi
at javax.management.remote.rmi.RMIConnector.connect(RMIConnector.java:340)
at javax.management.remote.JMXConnectorFactory.connect(JMXConnectorFactory.java:248)
at ....
Caused by: javax.naming.NameNotFoundException: jmxrmi
at com.sun.jndi.rmi.registry.RegistryContext.lookup(RegistryContext.java:99)
at com.sun.jndi.toolkit.url.GenericURLContext.lookup(GenericURLContext.java:185)
at javax.naming.InitialContext.lookup(InitialContext.java:392)
at javax.management.remote.rmi.RMIConnector.findRMIServerJNDI(RMIConnector.java:1888)
at javax.management.remote.rmi.RMIConnector.findRMIServer(RMIConnector.java:1858)
at javax.management.remote.rmi.RMIConnector.connect(RMIConnector.java:257)
... 2 more
Is there any way for me to debug the RMI server and see why that name can't be found?
Thanks
A: Looks like you left out a ':'. You should have service:jmx:rmi ...
A: The name of the connector is the last part of the URL (in the blog post it's "connector"). Change that to "jmxrmi".
A: Turns out that one of the configuration options was pointing to a file that didn't exist. JMX fell over silently :(
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527726",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to manipulate objects after adding them to a view This is a very elemental question about object-orientated programming- so sorry in advance if this is obvious.
I have a view and add several objects to this view (as subviews). I do this programatically. Every object get's an individual ID so that I can later tell objects apart (in this case it is the int position). This is my code:
for (int i=0; i < [directories count]; i++) {
NSLog(@"%i", i);
Notebook *aBook = [[Notebook alloc] initWithName:aName withPosition:i];
[self.view addSubview:aBook];
[aBook release];
[aName release];
}
After this, a have a view with several objects attached to it. My question is how I can get to these objects now. What if I wanted to find out the name or any other variable saved in this object? E.g. how would I get the nameOfBook if I knew what the stackPosition is? Here is the header of my object notebook:
#import <Foundation/Foundation.h>
@interface Notebook : UIView
{
NSString *nameOfBook;
int stackPosition;
int bookWidth;
int bookHeight;
int xPosition;
int yPosition;
}
@property (nonatomic, retain) NSString *nameOfBook;
@property int stackPosition;
@property int bookWidth, bookHeight, xPosition, yPosition;
-(id)initWithName:(NSString *)name withPosition:(int)position;
-(void)putOnScreen;
@end
A: You can create an array or dictionary of your Notebook objects and add each one into there. Then you can reference them later on by getting the array / dictionary object.
So create instance var for your array....
NSMutableArray *myBooks;
And then add your objects into the array in your loop....
[myBooks addObject:aBook];
And when you want to retrieve it later (using 0 based index)....
Notebook *theBook = [myBooks objectAtindex:myIndexNumberHere];
A: Create a method in your view controller.
-(UIView*)getNotevookForName:(NSString*)name{
for (UIView *v in self.view.subviews)
if ([v isKindOfClass:Notebook.class] && [[(Notebook*)v nameOfBook] isEqualToString:name])
return v;
return nil;
}
This approach won't too efficient if you have a lot of Notebook views
A: Since you add them as a subview, they are probably descendants of UIView. Why not use tag property like so:
int kBookTagIndex = 10;
for (int i=0; i < [directories count]; i++) {
NSLog(@"%i", i);
Notebook *aBook = [[Notebook alloc] initWithName:aName withPosition:i];
[aBook setTag:i+kBookTagIndex];
[self.view addSubview:aBook];
[aBook release];
[aName release];
}
and retrieve it later on:
int stackIndex = 4;
Notebook *aBook = [self.view viewForTag:stackIndex+kBookTagIndex];
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527728",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: refresh jquery mobile text inputs I have been working with JQM for a couple of weeks and after studying various examples and reading the docs, I cannot seem to find a way to refresh text inputs in a success callback. Is this possible with v1.0b2. I can refresh(reset) other elements just not text inputs. Any help would be appreciated. Thanks
A: Example:
*
*http://jsfiddle.net/phillpafford/f6Prp/6/
JS
$('#reset').click(function() {
$('.resetMe').val('');
$("input[name='checkbox-1']").attr("checked",false).checkboxradio("refresh");
$("input[name='radio-choice-1']").attr("checked",false).checkboxradio("refresh");
});
HTML
<div data-role="page" id="home">
<div data-role="content">
<div data-role="fieldcontain">
<label for="name">Text Input:</label>
<input type="text" name="name" id="name" value="" class="resetMe" />
</div>
<div data-role="fieldcontain">
<label for="textarea">Textarea:</label>
<textarea cols="40" rows="8" name="textarea" id="textarea" class="resetMe"></textarea>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>Agree to the terms:</legend>
<input type="checkbox" name="checkbox-1" id="checkbox-1" />
<label for="checkbox-1">I agree</label>
</fieldset>
</div>
<div data-role="fieldcontain">
<fieldset data-role="controlgroup">
<legend>Choose a pet:</legend>
<input type="radio" name="radio-choice-1" id="radio-choice-1" value="choice-1" />
<label for="radio-choice-1">Cat</label>
<input type="radio" name="radio-choice-1" id="radio-choice-2" value="choice-2" />
<label for="radio-choice-2">Dog</label>
<input type="radio" name="radio-choice-1" id="radio-choice-3" value="choice-3" />
<label for="radio-choice-3">Hamster</label>
<input type="radio" name="radio-choice-1" id="radio-choice-4" value="choice-4" />
<label for="radio-choice-4">Lizard</label>
</fieldset>
</div>
<a href="#" data-role="button" id="reset">Reset button</a>
</div>
</div>
A: I am dynamically creating some text inputs in my code (based on button clicks). Because they are being created after the page is rendered, they were all showing the standard UI (instead of jquery mobile css look and feel.) I found out that I have to "refresh" them after creating them (similar to how you refresh a button or other element.)
After creating the inputs, I add the line:
$('#myInputName').textinput();
to refresh
A: Why not just add a class to the text inputs and then set the values on those elements like so:
$(".my_class").val("");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527731",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How do I do inline Razor code within some HTML? What I want to do:
<div class='duck@if (this.Model.quacker) { -noisy }'>quack</div>
ie. either
<div class='duck'>quack</div>
or
<div class='duck-noisy'>quack</div>
However I can't quite get the syntax right. I tried @:-noisy but that generates errors such as
Make sure you have a matching "}" character for all the "{" characters
within this block
I tried also @:-noisy@ but the same error. What should I do?
A: The <text> element will transition to HTML again. Like this:
<div class='duck@if (this.Model.quacker) { <text>-noisy</text> }'>quack</div>
A: do this as follows :
@{
var poo = string.Format("{0}{1}", "duck", (this.Model.quacker) ? "-noisy" : "");
}
<div class='@poo'>quack</div>
UPDATE
The below one is generating the best solution :
<div class='@("duck")@if(this.Model.quacker){<text>-noisy</text>}'>quack</div>
A: should be like this
<div @if(this.Model.quacker)
{
@:class='duck-noisy'
}else{
@:class='duck'
}>quack</div>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527733",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Add total column to cross tab pivot query How do I add a total column to this query?
SELECT YearOfAccount, [Completed] AS Closed, [Open] AS Opened
FROM
(SELECT YearOfAccount, Status, CaseCode
FROM Records ) myRecords
PIVOT
(
COUNT(CaseCode)
FOR [Status] IN
( [Completed], [Open])
) AS pvt
Currently I am getting back the results I want but I want to include a total column on the far right for all records that are completed or Open.
A: Add
, [Completed] + [Open] AS Total
to the SELECT list
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527735",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to implement the clear Button Functionality for Edittext that are same as calculator? I am going to Implement the Calculator type application in my application.
I have successfully implement the all functionality.
Buit stuck with the lastSingle character clear button that is available as "C" on any other calculator.
So i need code to implement it.
So if any one have it then please help me.
Thanks.
A: public void clear(){
String text = (yourEditText.getText().toString);
if(!(text.equals("")))
yourEditText.setText(text.subString(0,text.length-2));
}
a better one could be
Editable editableText = yourEditText.getEditableText();
int length = editableText.length();
if (length > 0) {
editableText.delete(length - 1, length);
}
A: Here is a demo code for, how to create calculator in Android, this also have the clear function key implemented in it, study it to use it
LInk http://www.java2s.com/Open-Source/Android/App/nookdevs/com/nookdevs/calculator/Calculator.java.htm
A: Hi this is what I have done
It will help you in all the ways i.e. location deletion and non location deletion of elements from edit text
private void handleBackspace() {
String txt = _txtGiven.getText().toString();
String value = "";
int i = _txtGiven.getSelectionStart();
for (int j = 0; j < txt.length(); j++) {
char c = txt.charAt(j);
if (!((i - 1) == j)) {
value += c;
}
}
if (txt.length() == 1 && i == 1) {
_txtGiven.setText("");
}
if (value.length() > 0) {
_txtGiven.setText(value);
if (!(i == 0)) {
_txtGiven.setSelection(i - 1);
}
}
}
where _txtGiven is your edit text
Use this code and let me know if you face any problem
enjoy
A: When you press the 'C' button on the windows calculator you get : '0.'.
Two options :
EditText et = findViewById(R.id.editText1);
or
EditText et = new EditText(this);
then
et.setText("0.");
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527741",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Dynamic resource injection in EJB3? I know how to do resource injection to get JMS queue in EJB, just like the following sample, it's easy to get QUEUE1. But if I have lots of queue, and I don't want to change code when there is a new queue "QUEUE4".
Is it possible to get the resource dynamically or any suggestion for it?
@Stateless
public class OrderBean implements Order {
@Resource(name = "A.QCF", mappedName = "A.QCF")
private ConnectionFactory connectionFactory;
@Resource(name = "QUEUE1")
private Queue QUEUE1;
@Resource(name = "QUEUE2")
private Queue QUEUE2;
@Resource(name = "QUEUE3")
private Queue QUEUE3;
public String sendData(String abc) {
// ...
}
}
Update:
Thanks for Gonzalo and bkail, the following is my solution:
EJB code: "QueueName" is a parameter from client.
InitialContext initialContext = new InitialContext();
Queue dynamicQueue = (Queue)initialContext.lookup("java:comp/env/" + QueueName);
ejb-jar.xml:
<enterprise-beans>
<session>
<<resource-env-ref>>
<resource-env-ref-name>Queue1</resource-env-ref-name>
<resource-env-ref-type>javax.jms.Queue</resource-env-ref-type>
</<resource-env-ref>>
<<resource-env-ref>>
<resource-env-ref-name>Queue2</resource-env-ref-name>
<resource-env-ref-type>javax.jms.Queue</resource-env-ref-type>
</<resource-env-ref>>
</session>
</enterprise-beans>
When I have a new queue, I just need to change ejb-jar.xml and restart server.
A: I am afraid you'd have to do a explicit JNDI lookup so that you can dynamically set the resource you want to inject. Something like:
Queue dynamicQueue = (Queue)initialContext.lookup(dynamicQueueName);
where dynamicQueueName is the variable you set depending on whatever criteria you are using to figure out the queue name.
A: If I understand correctly, you want to dynamically declare a resource-env-ref for a Queue (which is basically what the @Resource is doing). That doesn't make sense:
Jetty: adding <resource-env-ref> programmatically
A: READERS, there must be a more elegant answer than mine.
A static parametrisable initialisation, for instance from a resource bundle (.properties) file, can be done.
See Andy Gibson. (Resource bundles are cached by the way, but you can flush the cache.)
I think you might mean having one object sending to a one out of a dynamic set of queues.
Personnally I would inject my own Queue Provider bean, self programmed.
Look at Reconfigure your application at runtime with reloadable property files.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527742",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Windows phone 7 scrollviewer problem I am not able to scroll through the page in wp7 . eventhough i have added scrollview it still doesnt work.
<phone:PhoneApplicationPage
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="860"
x:Class="sastadeal.PhonePage1"
FontFamily="{StaticResource PhoneFontFamilyNormal}"
FontSize="{StaticResource PhoneFontSizeNormal}"
Foreground="{StaticResource PhoneForegroundBrush}"
Orientation="Portrait"
shell:SystemTray.IsVisible="True" Height="1768">
<!--LayoutRoot is the root grid where all page content is placed-->
<Grid x:Name="LayoutRoot" Background="Transparent" Height="1768">
<ScrollViewer>
<!--TitlePanel contains the name of the application and page title-->
<!--TitlePanel contains the name of the application and page title-->
<Grid x:Name="ContentPanel" Margin="24,8,0,-8" Background="#FF61B1DE" Height="1768" >
<Image Height="76" Margin="8,8,0,0" Source="logo.png" Stretch="Fill" VerticalAlignment="Top"/>
<TextBlock HorizontalAlignment="Left" Margin="35,124,0,0" TextWrapping="Wrap" Text="Account Purpose" VerticalAlignment="Top" Foreground="Black"/>
<ListBox x:Name="lb" Height="70" Margin="36,161,185,0" VerticalAlignment="Top" FontSize="24" Background="#FF00BEEF">
<ListBoxItem x:Name="lb_vendor" Content="Launch & Grab Deals"/>
<ListBoxItem x:Name="lb_customer" Content="Grab Deals"/>
</ListBox>
<TextBlock HorizontalAlignment="Left" Margin="32,252,0,0" TextWrapping="Wrap" Text="Enter You Vendor Code" Foreground="Black" VerticalAlignment="Top" Name="Vendorcode_tb"/>
<TextBox x:Name="vendorcode_text" HorizontalAlignment="Left" Margin="21,283,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="334" />
<TextBlock HorizontalAlignment="Left" Margin="35,363,0,0" TextWrapping="Wrap" Text="e-Mail ID-" Foreground="Black" VerticalAlignment="Top"/>
<TextBox HorizontalAlignment="Left" Margin="21,390,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="334"/>
<TextBlock HorizontalAlignment="Left" Margin="32,466,0,0" TextWrapping="Wrap" Text="Enter Password - " Foreground="Black" VerticalAlignment="Top"/>
<TextBox x:Name="pwd" HorizontalAlignment="Left" Margin="21,497,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="335"/>
<TextBox x:Name="pwdr" HorizontalAlignment="Left" Margin="21,596,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="335"/>
<TextBlock HorizontalAlignment="Left" Margin="32,569,0,0" TextWrapping="Wrap" Text="Re-enter password" Foreground="Black" VerticalAlignment="Top"/>
<TextBlock HorizontalAlignment="Left" Margin="35,669,0,0" TextWrapping="Wrap" Text="Contact Number -" VerticalAlignment="Top" Foreground="Black"/>
<TextBox x:Name="Cno_txt" HorizontalAlignment="Left" Margin="21,700,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="335" InputScope="Number"/>
<TextBlock HorizontalAlignment="Left" Margin="36,776,0,0" TextWrapping="Wrap" Text="Mobile Number- " Foreground="Black" VerticalAlignment="Top"/>
<TextBox x:Name="mno_text" HorizontalAlignment="Left" Margin="21,807,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="335"/>
<TextBlock HorizontalAlignment="Left" Margin="30,898,0,0" TextWrapping="Wrap" Text="Address 1" Foreground="Black" VerticalAlignment="Top"/>
<TextBox HorizontalAlignment="Left" Margin="36,950,0,0" TextWrapping="Wrap" Text="" x:Name="add1_text" Width="335" InputScope="PostalAddress" Height="72" VerticalAlignment="Top"/>
<TextBlock HorizontalAlignment="Left" Margin="36,1026,0,0" TextWrapping="Wrap" Text="Address 2" Foreground="Black" VerticalAlignment="Top"/>
<TextBox HorizontalAlignment="Left" Margin="36,1057,0,0" TextWrapping="Wrap" Text="" VerticalAlignment="Top" Width="335"/>
</Grid>
</ScrollViewer>
</Grid>
The Screen automatically goes back to its previous location and the scroll is not complete. It just moves down and than back again like an elastic
A: Your Grid, that is the only child of the ScrollViewer, has a fixed height of 1768. That determines the maximum area that can be scrolled up/down by the ScrollViewer.
Your ScrollViewer stretches to fit its parent by default. That parent is another Grid that also has a fixed height of 1768.
Therefore the ScrollViewer has a fixed height of 1768 as well, so there is nothing to scroll. The amount available to scroll is the difference between the ScrollViewer height and the content height. In this case the difference is 0.
Remove the fixed height of the outer Grid. I doubt your Windows Phone has a 1768 high screen :)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527744",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
} |
Q: How to redirect request from a filter to desired servlet with post DataParameter? I am using following code to redirect a request from filter to servlet and jsp by using following snippet of code :-
String redirectedServlet = "servletLcation"+"?parameter=abc";
response.sendRedirect(redirectedServlet.trim());
Here parameter is passing as get method. I want to pass this parameter as a post method.
Is any way to do this ? My finding is as of now there is no way to send any parameter to any servlet by using response.sendRedirect() . response.sendRedirect() only support get method to pass parameter from one servlet to another servlet.
Thanks,
A: That's correct - you can't send redirect with POST.
If you need it, you can use forwarding (server-side redirect), which will preserve the http method request.getRequestDispatcher("/targetUri").forward(req, resp)
But use redirection in filters carefully - normally you do that if you want to restrict some access.
A: To pass a parameter from one servlet to another servlet, put it in the request as an attribute, and read the attribute on the recieving server.
So, before you do rd.forward you have to do request.setAttribute("hey", requestedPage.trim()) then in the receiving servlet, pick it up, request.getAttribute("hey"); and do something with it.
And by the way, if you are using a filter to forward to servlets or jsp, you are doing it horribly wrong. A filter should only mangle data around, not select which servlet/jsp to invoke. A filter is not meant to act as a controller, the servlet is.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527745",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Redirecting inside the controller I do some postdata handling on my webpage, but need some help with the redirecting.
How can i redirect as the code below does not work? I've breakpointed it and it enters RedirectToRoute function but goes to the return :(
if (Session["auth"] != null)
RedirectToRoute("/Home");
return null;
A: You need to return the RedirectToRouteResult like this:
if (Session["auth"] != null)
return RedirectToRoute("/Home");
return null;
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527750",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Why does OpenWrap cause my projects to fail with a "InitializeVisualStudioIntegration" compilation error? Suddenly I cannot compile the following openrasta projects (see errors at end):
*
*OpenRasta.Codecs.WebForms
*OpenRasta.Hosting.AspNet
This has happened after I did two things:
*
*I installed the latest version of OpenWrap from the wiki. This is the first time I have installed openwrap. I did nothing else, just ran the installer. No messing around.
*Pulled the latest versions of the following projects from GitHub:
*
*OpenRasta.Core
*OpenRasta.Codecs.WebForms
*OpenRasta.Hosting.AspNet
I then attempted a rebuild of my main project, which includes project references to the OR projects above. This gave me the "InitializeVisualStudioIntegration" errors (see end).
I found one mention of this problem online (http://tinyurl.com/3d8oxsf), something to do with nesting levels of the project files so FYI my OR projects all live at the following levels of nesting:
F:\Development\OpenRasta\openrasta-codecs-webforms\src\OpenRasta.Codecs.WebForms\OpenRasta.Codecs.WebForms.csproj
Any thoughts?
Thanks
Jonny
Errors
The "WrapDescriptor" parameter is not supported by the "InitializeVisualStudioIntegration" task. Verify the parameter exists on the task, and it is a settable public instance property. OpenRasta.Codecs.WebForms
The "InitializeVisualStudioIntegration" task could not be initialized with its input parameters.
The "WrapDescriptor" parameter is not supported by the "InitializeVisualStudioIntegration" task. Verify the parameter exists on the task, and it is a settable public instance property. OpenRasta.Hosting.AspNet
The "InitializeVisualStudioIntegration" task could not be initialized with its input parameters.
A: I've had one user with that problem before and we never managed to find out what was going on, somehow the msbuild tasks and openwrap dlls got out of sync, which was indeed very strange.
Can you make sure you have the shell version 2.0.0.10 shell? If all fails, delete the content of /wraps and do an update-wrap that'd get a clean copy
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527759",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to override 'Save As' event in Excel XP COM add-in I am working on a C# COM add-in specifically targeting Excel XP. I need to display my own 'Save As' dialog rather than the normal Excel dialog.
I tried handling the applicationObject.WorkbookBeforeSave and ActiveWorkbook.BeforeSave events and setting the 'ref bool Cancel' parameter to true, but Excel still pops up the 'Save As' dialog. Saving the Workbook in these event handlers doesn't make any difference.
If I handle the Click event on the Save button then the dialog doesn't pop up, but that doesn't take of when the user presses Ctrl-S to save.
Any ideas?
Thanks.
A: I have found a solution. It seems there is a problem with trying to cancel some events through C# in Excel XP. I found that using the code in this thread solves my problem: http://www.tech-archive.net/Archive/Excel/microsoft.public.excel.programming/2009-10/msg04732.html
Edit: The issue causing my problem and workaround is detailed here: http://support.microsoft.com/kb/830519
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527760",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to control the HTML CakePHP creates i'm working on an application built on the CakePHP framework and that uses AJAX (with jQuery).
I'm having troubles using the jQuery plugin "tablesorter" with AJAX-modified tables, since I think my View isn't producing the output it's supposed to : table structure in the actual HTML output isn't what my PHP code should do (missing tags, tags appearing from nowhere).
I'm new to CakePHP, so my question is :
Is there a way to control how CakePHP modifies the HTML output ? Or -even better- to disable this annoying feature ?
Maybe am i dreaming and maybe CakePHP isn't guilty for this one, but I never saw anything like that before (I used to code in PHP without framework).
PS : sorry for my english, french inside.
EDIT :
here's the code in my view :
echo'<thead>
<th>ID</th>
<th>Dénomination</th>
<th>Stock</th>
</thead>';
?>
<?php foreach ($products as $product){ ?>
<tr>
<td><?php echo $product['Product']['id']; ?></td>
<td>
<?php echo $this->Html->link($product['Product']['denomination'], '/products/view/'.$product['Product']['id'], array('escape'=>false)); ?>
</td>
<td><?php echo $product['Product']['quantity']; ?></td>
</tr>
<?php }
?>
<script>
$("#result").tablesorter();
</script>
and here's the HTML output :
<table id="result">
<tbody>
<tr> <td>64</td>
<td>
....
I don't think it's usefull to go any further since <thead> isn't there and <tbody> is.
A: Use this code in your search.ctp file for viewing table.
<table id="result" cellpadding="0" cellspacing="0" border="0" class="emailTable display table" width="100%">
<thead>
<th>ID</th>
<th>Dénomination</th>
<th>Stock</th>
</thead>
<tbody>
<?php
foreach ($products as $product): ?>
<tr>
<td><?php echo $product['Product']['id']; ?></td>
<td>
<?php echo $this->Html->link($product['Product']['denomination'], '/products/view/'.$product['Product']['id'], array('escape'=>false)); ?>
</td>
<td><?php echo $product['Product']['quantity']; ?></td>
</tr>
<?php
endforeach;
?>
</tbody>
<script>
$("#result").tablesorter();
</script>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527762",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: ASP.NET DataPager not working with ListView I have a problem with DataPager with ListView, I am using ASP.NET with VB.NET. I have searched for the answer, but I just can't seem to get it to work. Whenever I binded the data, the front page was okay, tried second page, still the same data, etc. Then I tried rebinding the data each time pager was changed, the listview dissapeared.
About the code: When a call is made to the UserInterface, to get statistics, it calls DataLayer, to get the test points to a List (Of KeyValuePair(Of String, Integer), reason I used List of KeyValuePair, was due to the need of index-based collection. Dictionary didn't provide it as such. Then the testpoints get the description, and number of failed test points. Then UserInterface binds it.
I put the entire related code to pastebin, hope you don't mind:
http://pastebin.com/stjAi9c2
I have been trying to fix it for many hours, hope anyone can point me in the right direction.
Thank you.
A: Protected Sub ListView1_PagePropertiesChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.PagePropertiesChangingEventArgs) Handles ListView1.PagePropertiesChanging
DataPager1.SetPageProperties(e.StartRowIndex, e.MaximumRows, false)
userInterface.ListViewReBind(ListView1)
End Sub
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527765",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to compile a quotation into a public static method of a new type in F# I am playing with type providers and I am trying to compile a quotation into a public static method of a new generated type. Here is what I have:
let CreateType<'i> name methodName quotation =
let assemblyName = new AssemblyName(Name = "tmpAssembly")
let assemblyBuilder =
System.AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave)
let filename = "tmpAssembly.dll"
let tmpModule = assemblyBuilder.DefineDynamicModule(filename,filename)
// create a new type builder
let typeBuilder =
tmpModule.DefineType(
name,
TypeAttributes.Public ||| TypeAttributes.Class,
null, // parentType
[|typeof<'i>|])
let attr = MethodAttributes.Public ||| MethodAttributes.HideBySig ||| MethodAttributes.Static
let methodImpl =
typeBuilder.DefineMethod(
methodName,
attr,
typeof<unit>, // todo
[||]) // todo
let il = methodImpl.GetILGenerator()
// compile quotation to method
typeBuilder.CreateType()
I know there is a .Compile() method but I think that's not what I need. Any ideas?
A: I haven't really played with the F# 3.0 release yet, but I think that you don't need to generate IL code yourself. The post by Keith explains that there are two types of type providers - generated that create a real .NET type (that exists in some library) and erased that create a fake type and then give the compiler an expression tree to be used in place of the calls to the fake type.
It seems to me that you're trying to implement generated type provider in a situation where erased type would be more appropriate. In the erased case, you should be just able to return the .NET Expression<..> type (not the F# quotation though, but you can use ToLinqExpression from PowerPack) and the F# compiler will compile that for you.
However, I haven't played with it yet, so I don't know what's the exact mechanism.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527766",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: javax.naming.NoInitialContextException getConnection Exception javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial
null
when i run below code this is the exception i am getting.
I have already created respective jndi name connectionpools in glassfishv3
pl give me any solution....
Thanks..
import java.sql.Connection;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class Test {
/**
* @param args
*/
private static DataSource ds;
private static Context initialContext = null;
public static Connection getConnection()
{
try
{
initialContext = new InitialContext();
ds = (DataSource) initialContext.lookup("jdbc/__TimerPool");
System.out.println("data source "+ds);
return ds.getConnection();
}
catch (Exception e)
{
System.out.println(("getConnection Exception " + e));
}
return null;
}
public static void main(String[] args) {
System.out.println(Test.getConnection());
}
}
A: ds = (DataSource) initialContext.lookup("jdbc/__TimerPool");
ds = (DataSource) initialContext.lookup("java:comp/jdbc/__TimerPool");
EDIT: Sorry, "java:comp/env/jdbc/__TimerPool".
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527768",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: GridViewRow Column visible true,false How can I get a Product_ID from a gridviewrow without creating a column because every time I have to make the column visible and invisible to perform gridview data operation.
Thanks in advance.
A: Make it part of one of your columns using a label similar to this:
<asp:TemplateField HeaderText="Name" SortExpression="name">
<ItemTemplate>
<asp:Label ID="productdIdLabel" runat="server" Text='<%# bind("Product_ID") %>' Visible="false"></asp:Label>
<asp:Label Visible="true" runat="server" ID="productNameLabel" Text='<%# bind("Product_Name") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
Hope this helps! Cheers
A: <asp:HiddenField ID="HiddenField1" runat="server" Value"<%# Eval("id")%>" />
A: <asp:TemplateField HeaderText="Name" SortExpression="name" visible="False">
<ItemTemplate>
<asp:label id="prodId" runat=server" Text="<%# Eval("id")%>" ></asp:label>
</ItemTemplate>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527771",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to fetch particular HTML contents from remote URL? I want to fetch particular HTML contents from remote websites url.
The website URL is as follow,
http://www.realtor.com/realestateandhomes-detail/10216-Montwood-Drive_El-Paso_TX_79925_M78337-06548
I want to fetch some specific information from above website url.
Here I attached image it highlight the specific area I want to all highlighted portion from there is a title,image, and descriptions.
How can I fetch the contents using JQuery or Javascript or Json call?
Is any other way to get these?
A: This will help you out:
http://papermashup.com/use-jquery-and-php-to-scrape-page-content/
A: You might be interested in checking out pjscrape (disclaimer: this is my project). It's a command-line tool using PhantomJS to allow scraping using JavaScript and jQuery in a full browser context.
*
*Scrapers can be written in straight Javascript, executed in the context of the site you're scraping, with a very simple, jQuery-friendly syntax.
*It can scrape a single page, an array of pages, or you can define a function to look for more URLs to spider on each page.
*It supports JSON and CSV output, either to file or to STDOUT
If the site is static and the structure is uniform, it should be very fast to scrape all the content you need into a structured data format.
A: When scraping content, it is vital to consider the following:
Is the content static html or will part of it's content be rendered by ajax-calls?
In the first case, simple http-get-routines like the one used in JNDPNT's comment's Link will be sufficient.
In the second case, you may want to look at automating Selenium via it's Webdriver.
In any case it might be better to ask your colleague if he can provide you with an interface to the raw data, e.g. over a webservice.
A: If I'm getting you right, you want The user's Browser to scrape The content of another Domain on The Fly, right?
That will Not Be Possible without proxying The Request through some Script on The Same Domain (or via a jsonp Request to a Service that returns The HTML to you) due to The Same Origin Policy.
Sorry to disappoint.
A: Use the Yahoo Pipes (http://pipes.yahoo.com/pipes/ )service.
This can be used to grab and manipulate the page HTML, extracting the bits you want. Data can then be posted server side using the Web Service module or sent directly to the clients browser using an ordinary javascript callback.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527775",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Programmatically close Java Tray Balloon I am using java.awt.SystemTray to create and manage the tray icon and balloon messages. Everything works fine.
But I would like to know whether it is possible to close or fade the message after it is displayed.
Right now, the user needs to click the balloon or close it, otherwise the message will not go away.
A: I'm not sure about other platforms, but on Windows, the message will only disappear if the machine is in use - i.e. if the user is typing something or moving the mouse. If you don't move the mouse or type anything, the message will stay where it is.
The following code shows a message for me. If I move the mouse, it disappears about 5 seconds later. If I don't, it stays around until such time as I move the mouse or type something, at which point it disappears.
final TrayIcon ti = new TrayIcon(XTPSkin.getInstance().getAppIcon().getImage());
final SystemTray st = SystemTray.getSystemTray();
st.add(ti);
ti.displayMessage("foo", "bar", MessageType.INFO);
There's no direct way to remove the message before its time is up - however, you can remove the TrayIcon (and if necessary immediately re-add it, although this really isn't recommended). Removing the TrayIcon causes the message to also be removed.
The following code, added to the above, causes the TrayIcon and the message to both be removed:
SwingUtilities.invokeLater(new Runnable(){
public void run() {
try {
Thread.sleep(1000); // Don't do this
st.remove(ti);
} catch (InterruptedException ie) {
// You won't need this when the sleep is removed
}
}
});
Notes:
*
*You need to wrap the first block of code above with some exception handling for AWTException
*The Thread.sleep in the second block is strictly for demonstration purposes. Since this code will execute on the AWT thread, you should not include that sleep in actual code.
*Continually removing and re-adding the TrayIcon in this way is probably a bad idea. Since the message does disappear if the user is using the machine, it's probably wisest not to do this.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527776",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: User search use MySQL LIKE or integrate a search engine (such as solr, sphinx, lucene etc.)? In my mysql db I have a user table consisting of 37,000 (or thereabouts) users.
When a user search for another user on the site, I perform a simple like wildcard (i.e. LIKE '{name}%}) to return the users found.
Would it be more efficient and quicker to use a search engine such a solr to do my 'LIKE' searches? furthermore? I believe in solr I can use wildcard queries (http://www.lucidimagination.com/blog/2009/09/08/auto-suggest-from-popular-queries-using-edgengrams/)
To be honest, it's not that slow at the moment using a LIKE query however as the number of users grows it'll become slower. Any tips or advice is greatly appreciated.
A: We had a similar situation about a month ago, our database is roughly around 33k~ and due to the fact our engine was InnoDB we could not utilize the MySQL full-text search feature (that and it being quite blunt).
We decided to implement sphinxsearch (http://www.sphinxsearch.com) and we're really impressed with the results (me becoming quite a 'fanboy' of it).
If we do a large index search with many columns (loads of left joins) of all our rows we actually halved the query response time against the MySQL 'LIKE' counterpart.
Although we havn't used it for long - If you're going to build for future scailablity i'd recommend sphinx.
A: you can speed up if the searchword must have minimum 3 chars to start the search and index your search column with a index size of 3 chars.
A: It's actually already built-in to MySQL: http://dev.mysql.com/doc/refman/5.0/en/fulltext-search.html
A: we're using solr for this purpose, since you can search in 1-2 ms even with milions of documents indexed. we're mirroring our mysql instance with Data Import Handler and then we search on Solr.
as neville pointed out, full text searches are built-in in mysql, but solr performances are way better, since it's born as a full text search engine
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527778",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: tableview cell value I am making an iphone application. In one of the view of the application I have implemented the table view. On each table view cell I have put one or two buttons. Now I want that whenever I click the button it give me the value of cell. How can I do it if anybody has an idea about this please let me know.
The code which I have implemented to display the button is:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [rangetime objectAtIndex:indexPath.row];
NSString *checkstatus = [finalstatusarray objectAtIndex:indexPath.row];
if ([checkstatus isEqualToString:@"YES" ])
{
UIButton *submitbutton1 = [UIButton buttonWithType:UIButtonTypeCustom];
submitbutton1.tag=1;
submitbutton1.frame = CGRectMake(200, 4, 28, 29);
UIImage * btnImage1 = [UIImage imageNamed:@"yes.png"];
[submitbutton1 setImage:btnImage1 forState:UIControlStateNormal];
cell.accessoryView = submitbutton1;
[submitbutton1 addTarget:self action:@selector(updatestatus) forControlEvents:UIControlEventTouchUpInside];
}
else if ([checkstatus isEqualToString:@"NO" ])
{
UIButton *submitbutton2 = [UIButton buttonWithType:UIButtonTypeCustom];
submitbutton2.tag = 2;
submitbutton2.frame = CGRectMake(200, 4, 28, 29);
UIImage * btnImage1 = [UIImage imageNamed:@"no.png"];
[submitbutton2 setImage:btnImage1 forState:UIControlStateNormal];
[submitbutton2 addTarget:self action:@selector(updatestatus) forControlEvents:UIControlEventTouchUpInside];
cell.accessoryView = submitbutton2;
}
else if ([checkstatus isEqualToString:@"s" ])
{
UIButton *submitbutton1 = [UIButton buttonWithType:UIButtonTypeCustom];
submitbutton1.tag = 1;
submitbutton1.frame = CGRectMake(255, 5, 28, 29);
UIImage * btnImage1 = [UIImage imageNamed:@"no.png"];
[submitbutton1 setImage:btnImage1 forState:UIControlStateNormal];
[cell addSubview:submitbutton1];// = submitbutton1;
[submitbutton1 addTarget:self action:@selector(updatestatus) forControlEvents:UIControlEventTouchUpInside];
UIButton *submitbutton2 = [UIButton buttonWithType:UIButtonTypeCustom];
submitbutton2.tag = 2;
submitbutton2.frame = CGRectMake(285, 5, 28, 29);
UIImage * btnImage2 = [UIImage imageNamed:@"yes.png"];
[submitbutton2 setImage:btnImage2 forState:UIControlStateNormal];
[cell addSubview:submitbutton2];
[submitbutton2 addTarget:self action:@selector(updatestatus) forControlEvents:UIControlEventTouchUpInside];
}
return cell;
}
Thanku very much.
A: You can do with the help of following code.
I had edited your answer in target method of UIButton and added event as argument so you can get indexPath of the row.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
cell.textLabel.text = [rangetime objectAtIndex:indexPath.row];
NSString *checkstatus = [finalstatusarray objectAtIndex:indexPath.row];
if ([checkstatus isEqualToString:@"YES" ])
{
UIButton *submitbutton1 = [UIButton buttonWithType:UIButtonTypeCustom];
submitbutton1.tag=1;
submitbutton1.frame = CGRectMake(200, 4, 28, 29);
UIImage * btnImage1 = [UIImage imageNamed:@"yes.png"];
[submitbutton1 setImage:btnImage1 forState:UIControlStateNormal];
cell.accessoryView = submitbutton1;
[submitbutton1 addTarget:self action:@selector(updatestatus:event:) forControlEvents:UIControlEventTouchUpInside];
}
else if ([checkstatus isEqualToString:@"NO" ])
{
UIButton *submitbutton2 = [UIButton buttonWithType:UIButtonTypeCustom];
submitbutton2.tag = 2;
submitbutton2.frame = CGRectMake(200, 4, 28, 29);
UIImage * btnImage1 = [UIImage imageNamed:@"no.png"];
[submitbutton2 setImage:btnImage1 forState:UIControlStateNormal];
[submitbutton2 addTarget:self action:@selector(updatestatus:event:) forControlEvents:UIControlEventTouchUpInside];
cell.accessoryView = submitbutton2;
}
else if ([checkstatus isEqualToString:@"s" ])
{
UIButton *submitbutton1 = [UIButton buttonWithType:UIButtonTypeCustom];
submitbutton1.tag = 1;
submitbutton1.frame = CGRectMake(255, 5, 28, 29);
UIImage * btnImage1 = [UIImage imageNamed:@"no.png"];
[submitbutton1 setImage:btnImage1 forState:UIControlStateNormal];
[cell addSubview:submitbutton1];// = submitbutton1;
[submitbutton1 addTarget:self action:@selector(updatestatus:event:) forControlEvents:UIControlEventTouchUpInside];
UIButton *submitbutton2 = [UIButton buttonWithType:UIButtonTypeCustom];
submitbutton2.tag = 2;
submitbutton2.frame = CGRectMake(285, 5, 28, 29);
UIImage * btnImage2 = [UIImage imageNamed:@"yes.png"];
[submitbutton2 setImage:btnImage2 forState:UIControlStateNormal];
[cell addSubview:submitbutton2];
[submitbutton2 addTarget:self action:@selector(updatestatus:event:) forControlEvents:UIControlEventTouchUpInside];
}
return cell;
}
- (void)updatestatus:(id)sender event:(UIEvent *)event
{
NSIndexPath *indexPath = [tblCityList indexPathForRowAtPoint:[[[event
touchesForView:sender] anyObject] locationInView:YourTableName]];
**Now You can access the row value with the help of indexPath.row**
}
A: First of all, you have to modify the below code...
[submitbutton1 addTarget:self action:@selector(updatestatus:) forControlEvents:UIControlEventTouchUpInside];
Instead of,
[submitbutton1 addTarget:self action:@selector(updatestatus) forControlEvents:UIControlEventTouchUpInside];
And write the following code in updatestatus:
- (IBAction) updatestatus:(id)sender
{
UIButton *btn = (UIButton*) sender;
UITableViewCell *cellSelected = (UITableViewCell*) [btn superview];
NSIndexPath *idxPath = [tableView indexPathForCell:cell];
// Your code...
}
A: Have the following code
-(void)showCellValue:(UIControl *)button{
UITableViewCell *cell = (UITableViewCell*)button.superview;
NSIndexPath *indexPath =[aTableView indexPathForCell:cell];
NSLog(@"The cell value is %@",[tableData objectAtIndex:indexPath.row]);
}
Assign this method showCellValue to the selector of the button. tableData is the array from which u load the data to the table. And in ur case it s rangeTime array
Hope this helps.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527779",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Get confused of some rails concepts, needs some explanations I got confused of some Rails' concepts like: gemset, rubygems, bundler . I have following three questions:
1. After I installed the RVM tool, what are the correct steps to setup the development enviroment for creating a rails project (say rails v2.3 project)
2. What is the difference between "gem install XXX" and "bundle install"? Can I understand it in the way that "bundle install" install all gems needed in the app at once while "gem install XXX" only install the specified "XXX" gem ? Are there any other difference? Why not use bundler to install specific rails then?
3. If I want to use rails v3.0 for project_one, and use rails v2.3 for project_two. How to create the two projects with the specific rails versions? How about different ruby versions for different projects? Do I only need to specify the needed version in Gemfile or install the needed version under the project path?
A: RVM allows you to create different gemsets alongside different ruby versions.
You can install different versions of ruby with rvm install.
rvm install 1.8.7
rvm install 1.9.2
rvm list known will tell you the available ruby implementations you can install.
Say, you have two projects: project_one and project_two, and both of them have different gem dependencies. So you'll want to create two empty gemsets with, say, Ruby 1.9.2.
rvm gemset create 1.9.2@project_one
rvm gemset create 1.9.2@project_two
To use project_two's gemset, you can use rvm use to select the gemset.
rvm use 1.9.2@project_two
You can also add the above command into a file called .rvmrc in the root path of your rails application, which rvm will load automatically whenever you cd into the app's root directory.
If you want to use Rails 2.3.8 for project_one,
rvm use 1.9.2@project_one
gem install rails -v 2.3.8
and Rails 3.1.0 for project_two,
rvm use 1.9.2@project_two
gem install rails -v 3.1.0
The difference between gem install and bundle install is that gem install installs only the specified gem into your gemset, while bundle install installs all the gems located in your app's Gemfile.
A: 1) If you have a rvm setup I propose add in in your app file .rvmrc
and in that file:
rvm --create ree-1.8.7-2011.03@myappname
This will alway use specify version of ruby (in that case 'ree-1.8.7-2011.03') and all gems will be installed in rvm gemset named: myappname. This file will always make sure every time you go to that folder from bash_console it will point rvm to correct environment.
2) If you have rvm setup then:
gem install XXX creates gem in specify rvm gemset or if not global rvm gemset
sudo gem install XXX will add gems to you Global gems
Like you said, you should always use Bundle install, and group gems for development,test, production.
3) This can achieve like I said in point 1) just create this file in your app
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527781",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Change a ListView image item's source when selected Below is a sample of what I am after:
I have decided to implement that using a ListView (tried a custom control based on Selector but I could not managed to output anything satisfying).
My list displays fine but I am struggling to find how to change the image source when the item gets selected. Here is my code:
<UserControl.Resources>
<DataTemplate x:Key="PagingIndicatorTemplate">
<Image Width="20" Height="20">
<Image.Style>
<Style TargetType="Image">
<Setter Property="Source" Value="/MyProject;component/Resources/Images/ic_paging_button_normal.png" />
<!-- I guess that's where I need to put my stuff to change the image ? ... -->
</Style>
</Image.Style>
</Image>
</DataTemplate>
</UserControl.Resources>
<ListView Name="PagingIndicator"
Height="30"
ItemTemplate="{DynamicResource PagingIndicatorTemplate}"
ItemsSource="{Binding Path=News}">
<ListView.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Center" />
</ItemsPanelTemplate>
</ListView.ItemsPanel>
<ListView.ItemContainerStyle>
<Style TargetType="ListBoxItem">
<Style.Resources>
<SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}" Color="Transparent"/>
</Style.Resources>
</Style>
</ListView.ItemContainerStyle>
</ListView>
A: *
*There is one thing wrong... you are using ListView but targetting style to ListBoxItem. It should be ListViewItem.
*In Image's style use a DataTrigger where check the binding on RelativeSource ListViewItem and Path=IsSelected (if its True) and change the Source of the image.
A: I have decided to solve the problem like that:
*
*Make two different item templates (each with their own images, styles for mouse over, mouse pressed, ...)
*Change the Template property of the ListViewItem with a trigger on its IsSelected property.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527783",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to decrypt excel file 2007 by POI 3.8 if it is protected by "Restrict Editing" In excel 2007, we can Protect Workbook by select "Protect Workbook" on menu and select "Protect Structures and Windows".
I have file with extension ".xlsm" and it is protected like the way above. I have password of this file and I need to read it by POI 3.8 in java, how can I do that?
I used to use the class "Decryptor" to verify the password, but it useless.
Please help me, I have stucked in this for 3 days...
A: You can make this
*
*Create a Excel Object
*Open workbook
*Unprotect with password ActiveWorkbook.Unprotect
*Save file
*Open in POI
*Remake steps 1 to 4, but protect file
[]'s
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527785",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How to obscure the id in a url (ruby on rails) I have a web app made with Ruby On Rails. For now when I want to display an object I have to access the following page: http://mywebapp.com/object/1234 with 1234 the id of the object.
I would like to encode that object id and have the following result: http://mywebapp.com/object/5k (it is just an example).
How can it be done?
Many thanks,
Martin
A: All these converting methods are reversible, so IMHO if your object has some name or title or whatever, then the best way is adding a slug.
In such case add a new attribute :slug to your object, let automatically generate it's value from object name (or something else) on the model:
class MyObject
validates_format_of :slug, :with => /\A[a-z\-0-9]*\Z/
before_validation :generate_slug, :on => :create
def generate_slug
if self.slug.blank?
slug = self.name.mb_chars.downcase.normalize(:kd).to_s.gsub(/-/, " ").squeeze(" ")
slug = slug.gsub(/\s/, "-").gsub(/[^a-z\-0-9]/, "")
current = 1
self.slug = slug
while true
conflicts = MyObject.where("slug = ?", self.slug).count
if conflicts != 0
self.slug = "#{slug}-#{current}"
current += 1
else
break
end
end
end
end
end
then the URL can be http://mywebapp.com/object/my_object_slug, because in action you find the object via this slug:
class MyObjectController
def some_action
my_object = MyObject.find_by_slug(params[:slug])
...
end
end
Don't forget modify routes.rb:
match "object/:slug", :to => "my_objects#some_action"
A: You could probably do this with Base64 encoding (although if you're really trying to keep the internal id secret someone could probably guess you're using Base64 encoding and easily determine the id).
Your controller would need to look a bit like this
class ThingsController < ApplicationController
require 'base64'
def show
@thing = Thing.find Base64.urlsafe_decode64(params[:id])
end
def edit
@thing = Thing.find Base64.urlsafe_decode64(params[:id])
end
#These are just a couple of very simple example actions
end
Now actually encoding your URLs is going to be a little bit trickier - I'll look into it as it seems like an interesting problem (but I'm not making any promises).
*
*Edit -
A bit of reading reveals that ActionView uses the to_param method in url_for to get the id of an object. We can override this in the model itself to encode the id like so
class Thing < ActiveRecord::Base
def to_param
Base64.urlsafe_encode64 self.id.to_s
end
end
Everything I've written here is conjectural. I haven't done this before or tested the code so I can't give any guarantee as to whether it will work or whether it will introduce unforeseen problems. I'd be very interested to hear how you go.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527787",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Fix first four numbers in textbox PHP I want to restrict first four number in textbox in PHP, Here's my sample code:
<label>Number </label>
<input name="phone" type="text" class="required" id="phone" value="<?=$phone_number?>" maxlength="11" />
Anyone can help?
A: Like this...
$phone_number = '0116' . $_POST['phonenumber'];
This can be the same
<label>Number </label>
<input name="phone" type="text" class="required" id="phone" value="?=$phone_number?>" maxlength="11" />
Whereever you use the phone number add the digits you want via php.
A: <label>Number </label>
<input name="phone" type="text" class="required" id="phone" value="1234<?=$phone_number?>" maxlength="11" />
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527788",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Specifying Maven memory parameter without setting MAVEN_OPTS environment variable I was wondering if it is possible to specify Maven memory boundaries with a syntax similar to:
mvn -Dtest=FooTest -DXmx=512M clean test
I tried a couple of variations till now, unsuccessfully.
I am aware of MAVEN_OPTS environment variable, but I would like to avoid that.
Related to the above question, it would be nice to know if there is the possibility to specify the memory behavior of the surefire plugin in a similar manner, so that it forks the jvm using the overridden memory amount (eventually overriding the <argLine> parameter in the pom plugin configuration, if present)
A: To specify the max memory (not via MAVEN_OPTS as originally requested) you can do the following:
mvn clean install -DargLine="-Xmx1524m"
A: Since Maven 3.3.1 a default can also be specified in ${maven.projectBasedir}/.mvn/jvm.config
It is documented here: https://maven.apache.org/docs/3.3.1/release-notes.html#JVM_and_Command_Line_Options
A: You can configure the surefire-plugin to use more memory. Take a look on
Strange Maven out of memory error.
Update:
If you would like to set the parameter from command-line take a look on {{mvn.bat}} (or {{mvn}} shell script) in your maven installation directory. It uses with additional options specified in command line.
Next possibility is to set surefire-plugin and use properties specified in command-line, e.g. mvn ... -Dram=512
and
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.5</version>
<configuration>
<forkMode>once</forkMode>
<argLine>-Xms${ram}m -Xmx${ram}m</argLine>
</configuration>
</plugin>
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527789",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "32"
} |
Q: How do I know, when the player stops playing? public function videoPlayer()
{
connection = new NetConnection();
connection.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
connection.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
connection.connect(null);
}
private function connectStream():void
{
stream= new NetStream(connection);
stream.addEventListener(NetStatusEvent.NET_STATUS, netStatusHandler);
stream.addEventListener(AsyncErrorEvent.ASYNC_ERROR, asyncErrorHandler);
stream.client = this;
stream.bufferTime = 30;
video = new Video(600,313);
video.attachNetStream(stream);
stream.play(vName);
addChild(video);
}
}
private function netStatusHandler(event:NetStatusEvent):void
{
trace(event.info.code);
}
If the video ended playing its not tracing "NetStream.Play.Stop" info code. Why?
A: You need to look at http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/net/NetStream.html#event:onPlayStatus
From Adobe:
Establishes a listener to respond when a NetStream object has completely played a stream. The associated event object provides information in addition to what's returned by the netStatus event. You can use this property to trigger actions in your code when a NetStream object has switched from one stream to another stream in a playlist (as indicated by the information object NetStream.Play.Switch) or when a NetStream object has played to the end (as indicated by the information object NetStream.Play.Complete).
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527795",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: uploading video in Facebook, ¿parameters? I'm uploading a video to facebook form my iphone app. More customized is better. I would like to know how many parameters I can set in params, and what are them. but i'm not able to find it, any help?
This is the function:
[facebook_ requestWithGraphPath:@"me/videos"
andParams:params
andHttpMethod:@"POST"
andDelegate:self];
I have "content type", "title", "description" and the video... anything else?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527796",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: draggable element color changed back when refreshing The draggable elememnt color will be changed to #DF2525 when stop dragging. But the color is changed back to original one when page is refresh. I want color won't be changed back when refreshing.
Is there anyone know solution? Thanks in advance.
$(function() {
$( "#draggable" ).draggable({
stop: function(){
var position = $(this).position();
$(this).css({"color":"#ff00ff","background":"#DF2525"});
}
});
});
<div class="demo">
<div id="draggable" class="ui-widget-content">
<p>Drag</p>
</div>
</div>
A: If I understand this well, you want the color to be saved? You can use cookies or localStorage for this.
A: jQuery animation functions only work on the client's side. You can't permanently change the website code using it. If you want to interact with server side, think of using AJAX and some data aquisition.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527797",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How do you set up the correct HTTP Response object for a Range request coming from BITS (Background Intelligent Transfer Service)? I have a requirement to implement a web-service that can issue files to the bits (Background Intelligent Transfer Service). The language is ASP.NET (C#). The problem I am having is with the "range" stuff.
My code currently receives the http request (with a valid range is present in the http headers of 0 - 4907), and subsequently dishes out a portion of a byte array in the response object.
Here's my server code:
_context.Response.Clear();
_context.Response.AddHeader("Content-Range", "bytes " + lower.ToString() + "-" + upper.ToString() + "//" + view.Content.Length.ToString());
_context.Response.AddHeader("Content-Length", upper.ToString());
_context.Response.AddHeader("Accept-Ranges", "bytes");
_context.Response.ContentType = "application/octet-stream";
_context.Response.BinaryWrite(data);
_context.Response.End();
What happens next is that the subsequent request does not have any "range" key in the header at all... it's like it is asking for the entire file! Needless to say, the bits job errors stating that the servers response was not valid.
I suspect that it's all down to the headers that the server is returning in the response object... I am pretty sure that I am following protocol here.
If anyone can help with this it would be greatly appreciated... mean while... I'll keep on searching!
Regards
A: Yes, I found that I had a few issues in total. IIS was an initial problem, then my length calculations... and then like you say, the range request it's self. Ignoring the latter, my final code for this segment was:
_context.Response.StatusCode = 206;
_context.Response.AddHeader("Content-Range", string.Format("bytes {0}-{1}/{2}", lower.ToString(), upper.ToString(), view.Content.Length.ToString()));
_context.Response.AddHeader("Content-Length", length.ToString());
_context.Response.AddHeader("Accept-Ranges", "bytes");
_context.Response.OutputStream.Write(view.Content.ToArray(), lower, length);
Handling multi-request ranges can be tackled a different day! Should BITS request in this way (like it does on the second request after the first request which asks for the entire file), my code simply returns nothing... and then BITS sends a single range in the request... things work ok from there.
Thanks for the response.
A: You could also test-run your BITS request(s) against a known static file and sniff the packets with WireShark. That's sure to reveal exactly how to do it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527799",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Set image width to span tag I have this html code
<ul>
<li><a href="#"><img src="path_to_image1"><span>some text</span></a></li>
<li><a href="#"><img src="path_to_image2"><span>some text</span></a></li>
<li><a href="#"><img src="path_to_image3"><span>some text</span></a></li>
</ul>
Images are of different width.
I need to set width of SPAN element to be equal as IMG width.
Here is the code that I wrote by looking over the StackOverflow board.
$(document).ready(function() {
$("ul li a").each(function() {
var theWidth = $(this).find("img").width();
$("ul li a span").width(theWidth);
});
});
Now this code returns only width of the last image.
What to change so I can have width of span element same as img?
Thanks
A: $('ul li img').each(function() {
var imgWidth = $(this).width();
$(this).next('span').css({'width': imgWidth});
});
A: You just need to correct one line:
$("ul li a span").width(theWidth);
Replace with:
$(this).find('span').width(theWidth);
A: Replace this line
$("ul li a span").width(theWidth);
with
$(this).find('span').width(theWidth);
Explanation: the line $("ul li a span").width(theWidth); sets the width for all three span elements.
The 'each' loop runs 3 times.
The first time it sets all three spans to the width of the first image.
The second time it sets all three spans to the width of the second image.
...
A: the answer is in your own code, almost..
$(this).find("span").width(theWidth);
A: Can you just set the widths of the <li>'s to the same width as the image and set the <span> as display: block;
The spans will then be as wide as their contain (the <li>) and it saves you a little extra jquery trying to dig down to span level.
Also, to help speed up your jquery selector simply add an id to the list and target that instead of trying to match ul li a...; now all you have to do is match #widths.
Example
<ul id="widths">
<li><a href="#"><img src="path_to_image1"><span>some text</span></a></li>
<li><a href="#"><img src="path_to_image2"><span>some text</span></a></li>
<li><a href="#"><img src="path_to_image3"><span>some text</span></a></li>
</ul>
$(document).ready(function() {
$('#widths img').each(function() {
var imgWidth = $(this).width();
$(this).next('span').css({'width': imgWidth});
});
});
A: There are many ways around this, this worked for me though.
$(document).ready(function () {
$("ul li a img").each(function (index) {
$(this).next().width($(this).width()).css("display", "block");
});
});
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527802",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Cannot find -lgcc -s while Compiling C program with GCC I am trying to compile a C program with gcc using the below command
gcc -r client.c -o exe
But getting these errors, and no generation of exe file:
/usr/bin/ld cannot find -lgcc -s
collect2: ld returned 1 exit status
Anyone tell me what I am missing and what is ld here?
A: ld is the linker or link editor. It is invoked by gcc to link the .o files produced by compiling your code together with various libraries (including libgcc) to produce an executable (exe).
Why are you passing -r to gcc? Do you know what it does? Don't do that.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527806",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Where is the best place to format Model properties in ASP.NET MVC(3)? I've been looking a lot recently as best practices within the ASP.NET MVC framework, specifically around sparation of concern. My question here is, if I have a property on a model, where is the best place to do some formatting on that property?
I've thought about a few options but am not sure which is best. The example uses a DateTime. Sorry this got a bit long.
Option 1:
In the view: @Model.TheDate.String("{0:'blah'dd/MM/yyyy}")
I know this isn't right because the format string shouldn't be here (what if I want to change the format throughout the whole app)
Option 2:
Extension method used within the view: @Model.TheDate.DisplayItNicePlease()
This kind of makes sense because the view is chosing the extension method to use for formatting and the viewmodel just exposes the date property to the view. Not sure if the view or view model should be responsible for formatting though.
Option 3:
In an Html Helper method, i.e. something like Where should I place Declarative HTML helpers in ASP.NET MVC 3 so you could use:
@Html.DisplayDateNice(Model.TheDate)
Option 4:
Extra property on the view model to format it and return a string e.g.:
public string TheDateStr
{
get
{
return TheDate.DisplayItNicePlease();
}
}
And then in the view you just have
@Model.TheDateStr
Fairly similar to option 3 only it keeps the view really, really simple - the view literally just outputs what is in the model and doesn't care about the format of the data.
Option 5:
DisplayFormat attributes, e.g.:
On the view model:
[DisplayFormat(DataFormatString = "{0:'blah'dd/MM/yyyy}")]
public DateTime TheDate { get; set; }
And then on the view:
@Html.DisplayFor(m => m.TheDate)
I like this apart from again the format string is not reused, so bring on option 5...
Option 6:
Some kind of custom DisplayFormatAttribute e.g. NiceDateDisplayFormatAttribute.
This seems to me like it might be the nicest solution and works well if you just want a simple string formatting. I think this gets more complicated if you want something more complicated, e.g showing relative time (Calculate relative time in C#), in which case maybe this is best being in an extension method/html helper.
There are probably other ways I'm not even aware of...
A: Either use an extension helper to format the type if this type formatting will be used a lot or add an extra property in the Model to return a formatted version of the original property.
A: For a single view, I personally use option 5: putting it in the view model.
If date format's being used for multiple pages, you can create a html helper extension for formatting the date. So in the view, you'd have something like
@Model.TheDate.ToDateString()
But overall, i still prefer option5 because i create viewmodels for everypage, and just throw a DisplayFormat attribute on it.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527810",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "15"
} |
Q: Why i can't get my GPS position? i'm trying to get my GPS position and update with it a textview (tv2) that it is on the top of the Activity. My Activity shows the camera view and captures GPS coordenates and it haves to write them on the textview. It also get's compass & accelerometer data, but it is not the problem now.
Something is wrong because i can't capture the GPS data... but i dont understand what is wrong. If i create a new project from scratch and paste the GPS location request code it get's the code correctly, but here on this app i can't get the GPS positions... with the same code. ¿what is going wrong?
for the cameraView i'm using the default cameraView code written on this guide: http://www.devx.com/wireless/article/42482/1954
and this is my main class:
public class AugmentedRealitySampleActivity extends Activity implements Runnable{
private CustomCameraView cv=null;
private TextView tv1;
private TextView tv2;
private TextView tv3;
private TextView tv4;
private TextView tv5;
private TextView tv6;
public static SensorManager sensorMan;
//variables para obtener mi posicion:
LocationManager mLocationManager;
Location mLocation;
MyLocationListener mLocationListener;
Location currentLocation = null;
private float direction; //compass
//private Location curLocation; //gps
public volatile float inclination; //accelerometer
double lat=-1;
double lon=-1;
public void onCreate(Bundle savedInstanceState)
{
//try{
super.onCreate(savedInstanceState);
cv = new CustomCameraView(this.getApplicationContext());
FrameLayout rl = new FrameLayout(this.getApplicationContext());
LinearLayout ll= new LinearLayout(this.getApplicationContext());
ll.setOrientation(LinearLayout.VERTICAL);
setContentView(rl);
rl.addView(cv);
rl.addView(ll);
//} catch(Exception e){}
tv1=new TextView(getApplicationContext());
tv2=new TextView(getApplicationContext());
tv3=new TextView(getApplicationContext());
tv4=new TextView(getApplicationContext());
tv5=new TextView(getApplicationContext());
tv6=new TextView(getApplicationContext());
tv1.setBackgroundColor(Color.BLACK);
tv2.setBackgroundColor(Color.BLACK);
//tv3.setBackgroundColor(Color.BLACK);
//tv4.setBackgroundColor(Color.BLACK);
//tv5.setBackgroundColor(Color.BLACK);
//tv6.setBackgroundColor(Color.BLACK);
ll.addView(tv1);
ll.addView(tv2);
ll.addView(tv3);
ll.addView(tv4);
ll.addView(tv5);
ll.addView(tv6);
sensorMan = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
sensorMan.registerListener(Compasslistener, sensorMan.getDefaultSensor(SensorManager.SENSOR_ORIENTATION), SensorManager.SENSOR_DELAY_FASTEST);
sensorMan.registerListener(Accelerometerlistener, sensorMan.getDefaultSensor(Sensor.TYPE_ACCELEROMETER), SensorManager.SENSOR_DELAY_FASTEST);
//LocationManager locMan;
//locMan = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
//locMan.requestLocationUpdates(LocationManager.GPS_PROVIDER, 100, 0, gpsListener);
//getLatitude(); getLongitude(); bearingTo(); distanceTo();
tv1.setText("Test1");
tv2.setText("Test2");
tv3.setText("Test3");
tv4.setText("Test4");
tv5.setText("Test5");
tv6.setText("Test6");
Thread thread = new Thread(this);
thread.start();
}
////////////////////////////////////////////////
//COMPASS:
////////////////////////////////////////////////
SensorEventListener Compasslistener = new SensorEventListener()
{
public void onAccuracyChanged(Sensor arg0, int accuracy){ }
public void onSensorChanged(SensorEvent evt)
{
float vals[] = evt.values;
direction = vals[0];
tv1.setText("Direction= " + direction);
}
};
////////////////////////////////////////////////
//ACCELEROMETER:
////////////////////////////////////////////////
private SensorEventListener Accelerometerlistener = new SensorEventListener()
{
public volatile float direction = (float) 0;
//public volatile float rollingZ = (float)0;
public volatile float kFilteringFactor = (float)0.05;
public float aboveOrBelow = (float)0;
public void onAccuracyChanged(Sensor arg0, int arg1){}
public void onSensorChanged(SensorEvent evt)
{
float vals[] = evt.values;
if(evt.sensor.getType() == Sensor.TYPE_ORIENTATION)
{
float rawDirection = vals[0];
direction =(float) ((rawDirection * kFilteringFactor) + (direction * (1.0 - kFilteringFactor)));
inclination = (float) ((vals[2] * kFilteringFactor) + (inclination * (1.0 - kFilteringFactor)));
if(aboveOrBelow > 0)
inclination = inclination * -1;
if(evt.sensor.getType() == Sensor.TYPE_ACCELEROMETER)
aboveOrBelow = (float) ((vals[2] * kFilteringFactor) + (aboveOrBelow * (1.0 - kFilteringFactor)));
tv3.setText("Inclination= " + inclination);
tv4.setText("Direction2= " + direction);
tv5.setText("kFilteringFactor= " + kFilteringFactor);
tv6.setText("aboveOrBelow= " + aboveOrBelow);
}
}
};
////////////////////////////////////////////////////////////////////////
//Métodos del Hilo que obtiene la posicion GPS del usuario periodicamente.
///////////////////////////////////////////////////////////////////////
public void run() {
mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
if (mLocationManager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
Looper.prepare();
mLocationListener = new MyLocationListener();
try{
mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 200, 0, mLocationListener);
}catch(Exception e){}
//try {
// wait(100);
//}catch (InterruptedException e) {}
Looper.loop();
}
}
private class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc) {
if (loc != null) {
try{
currentLocation = loc;
handler.sendEmptyMessage(0);
}catch(Exception e){}
}
}
public void onProviderDisabled(String provider) { }
public void onProviderEnabled(String provider) { }
public void onStatusChanged(String provider, int status, Bundle extras) { }
}
private Handler handler = new Handler() {
public void handleMessage(Message msg) {
if (currentLocation!=null)
{
lat=currentLocation.getLatitude();
lon=currentLocation.getLongitude();
if (lat==-1 && lon ==-1) /// si no existe ninguna posicion GPS anterior en el telefono, no hago nada
{
}
else //// si existe alguna posicion anterior (es decir, si el GPS del telefono ha sido activado al menos alguna vez en su vida util)
{
tv2.setText("Location= "+lat+" "+lon);
}
}
}
};
}
A: Did you put in your AndroidManifest the permission?
Like:
<android.permission.ACCESS_COARSE_LOCATION" />
<android.permission.ACCESS_FINE_LOCATION" />
or see more permissions in the android developer documentation:
http://developer.android.com/reference/android/Manifest.permission.html
A: I think it's some kind of bug of the phone, it can't works fine with accelerometer, compass and GPS being used at the same time
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527811",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: PHP redirection without header I want to redirect a PHP page and post data to that page without using Header("Location:http://www.example.com").
If anybody knows please help me.
I tried some Zend functions also. Please explain anybody clearly.
Thanks
A: You cannot redirect to a POST.
You can redirect to a GET and header() us perfectly fine for that.
A: What is the matter of not using header('Location:.... ?
If you describe exactly what is the problem, then is easyer to get an answer.
A: If you are using Zend Framework you can redirect from one controller action to another action as such:
return $this->_forward("action", "controller", "module");
A: Well you could use AJAX code to post data to another page in the background and then update the current page with the posted data's results. That would do the job, though it very much depends what you want to do after submitting the data to your other page.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527812",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Smarter where clause? I've been experimenting with LINQ to SQL recently and have a quick question.
The basic premise is I have a search request which contains a Make and Model which I use to search a DB containing cars.
The expression for my Where Clause is shown below:
.Where(c => c.make == search.make && c.model == search.model)
This is fine when my search contains both a make and a model. The problem arises when it only contains a make(or vice versa) and not both search fields. I want it to return all cars of that make, it is however returning none.
Im assuming this is because it is looking for the make plus a model that is null or empty?
Is there an elegant way to get around this other than manually building up the query with a series of "if not null append to query" type steps?
A: Have you tried:
.Where(c => (search.make == null || c.make == search.make) && (search.model == null || c.model == search.model))
Update: There's actually a nice treatment of the general problem, and clean solutions, here:
LINQ to SQL Where Clause Optional Criteria. The consensus seems to be that an extension method is cleanest.
A: .Where(c => (search.make == null || c.make == search.make) &&
(search.model == null || c.model == search.model))
A: IMO, split it:
IQueryable<Car> query = ...
if(!string.IsNullOrEmpty(search.make))
query = query.Where(c => c.make == search.make);
if(!string.IsNullOrEmpty(search.model))
query = query.Where(c => c.model== search.model);
This produces the most appropriate TSQL, in that it won't include redundant WHERE clauses or additional parameters, allowing the RDBMS to optimise (separately) the "make", "model" and "make and model" queries.
A: This should work.
.Where(c =>
(search.make == null || c.make == search.make) &&
(search.model == null || c.model == search.model))
A: you could write something like this:
.Where(c => c.make == search.make ?? c.make && c.model == search.model ?? c.model)
A: .Where(c => (string.IsNullOrEmpty(c.make) || c.make == search.make) &&
(string.IsNullOrEmpty(c.model) || c.model == search.model))
A: .Where(c => (string.IsNullOrEmpty(search.make) || c.make == search.make) &&
(string.IsNullOrEmpty(search.model) || c.model == search.model))
That's assuming the properties are strings.
A: Where(c => (search.make == null || c.make == search.make) &&
(search.model == null || c.model == search.model))
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527813",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: test over 3rd dimension MATLAB I have a 3d array. 1st dim is xcoordinate of pixel
2nd dimension is y - coordinate of pixel.
3rd coordinate is time (or could be though of as the frame number).
I want to do a test to see if any pixel is equal to zero for every single frame (along 3rd dimension).
How would I write this test?
I need returned the pixels which are ALWAYS true!!!
A: Rather than all you could use any. If I understand you correctly, the code would go something like this for a single "pixel"
any(A(x,y,:))
where A is the 3d matrix. If the result is 1, then the given pixel does have a non-zero value for at least one frame, and 0 otherwise.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527818",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Prompting for authorization when accessing protected external resources in Chrome I'd like to embed external, NTLM authorization protected resources (pictures) from another domain (say, secret.com) in my web page (say, mypage.com). The mypage.com server has no access to those resources, but the end user does. Also, the end user may or may not have active session with secret.com
If I place <img src='secret.com/1.jpg' /> tag in my page, users with already initialized sessions with secret.com can see the picture, logged out users on IE get automatically authorized, Firefox users get prompted for their credentials, but Chrome just dumps a warning "Resource interpreted as Image but transferred with MIME type text/html." and an error "Failed to load resource: the server responded with a status of 401 (Unauthorized)" in console and displays the default missing picture icon.
However, when accessing secret.com/1.jpg directly, Chrome properly prompts for authorization.
Are there any meta tags/JS tricks/something else that can be used to make Chrome ask for the credentials?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527822",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Ruby: dynamically generate attribute_accessor I'm trying to generate the attr_reader from a hash (with nested hash) so that it mirror the instance_variable creation automatically.
here is what i have so far:
data = {:@datetime => '2011-11-23', :@duration => '90', :@class => {:@price => '£7', :@level => 'all'}}
class Event
#attr_reader :datetime, :duration, :class, :price, :level
def init(data, recursion)
data.each do |name, value|
if value.is_a? Hash
init(value, recursion+1)
else
instance_variable_set(name, value)
#bit missing: attr_accessor name.to_sym
end
end
end
But i can't find out a way to do that :(
A: You could do a bit of meta-magic to solve this, using method_missing:
class Event
def method_missing(method_name, *args, &block)
if instance_variable_names.include? "@#{method_name}"
instance_variable_get "@#{method_name}"
else
super
end
end
end
What this will do is allow access to object instance variables via object.variable syntax, if the object has those variables defined, without resorting to modifying the entire class via attr_accessor.
A: You need to call the (private) class method attr_accessor on the Event class:
self.class.send(:attr_accessor, name)
I recommend you add the @ on this line:
instance_variable_set("@#{name}", value)
And don't use them in the hash.
data = {:datetime => '2011-11-23', :duration => '90', :class => {:price => '£7', :level => 'all'}}
A: attr_accessor is a class method and as such needs to be invoked on the class. It is also a private method, so you need to invoke it in a context in which the class object is self.
As an example:
class C
def foo
self.class.instance_eval do
attr_accessor :baz
end
end
end
After creating an instance of C and calling foo on that instance, that instance -- and all future instances -- will contain methods baz and baz=.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527832",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: startActivityForResult problem I have ActivityA calling ActivityB using startActivityForResult. If I open a browser from ActivityB and surfing a bit, my ActivityB gets killed and it doesnt know anymore that it should return anything to ActivityA.
//ActivityB.getCallingActivity() == null
As a result of this the onActivityResult in ActivityA wont be called.
Can this be fixed somehow?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527845",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: What type of code that interprets correctly in procedural programming will cause an error when included in a class (outside of a function)? I'm new to oop and was surprised to see that code that worked properly in procedural programming,
<?php
$number_of_floors = 5;
$stairs_per_floor= 10;
echo $total_stairs= $number_of_floors*$stairs_per_floor;
?>
Lead to an error when included inside of a class:
<?php
// Class
class Building {
// Object variables/properties
public $number_of_floors = 5; // These buildings have 5 floors
public $stairs_per_floor= 10;
public $total_stairs= $number_of_floors*$stairs_per_floor;
private $color;
// Class constructor
public function __construct($paint) {
$this->color = $paint;
}
public function describe() {
printf('This building has %d floors. It is %s in color.',
$this->number_of_floors,
$this->color
);
}
}
// Build a building and paint it red
$bldgA = new Building('red');
// Tell us how many floors these buildings have, and their painted color
$bldgA->describe();
?>
If you remove
public $total_stairs= $number_of_floors*$stairs_per_floor;
Everything works.
Are you not allowed to write arithmetic expressions inside of a class if they are outside of a function? What type of code that interprets correctly in procedural programming will cause an error when included in a class (outside of a function)?
A: You can not do the operation at the time of defining them. Instead you should add this to your constructor and do:
$this->total_stairs = $this->number_of_floors * $this->stairs_per_floor;
Furthermore I advise you to use the generally accepted coding standards of PHP which would mean, not to use underscores in variable names.
public $totalStairs;
public $numberOfFloors;
public $stairsPerFloor;
Even more important is the choice of meaningful and readable variables names. So $bldgA should be:
$buildingA
A: you can't assign value by mathematical calculation while defining variable. Calculate value in constructor.
<?php
// Class
class Building {
// Object variables/properties
public $number_of_floors = 5; // These buildings have 5 floors
public $stairs_per_floor= 10;
public $total_stairs=0;
private $color;
// Class constructor
public function __construct($paint) {
$this->color = $paint;
$this->total_stairs = $number_of_floors*$stairs_per_floor;
}
public function describe() {
printf('This building has %d floors. It is %s in color.',
$this->number_of_floors,
$this->color
);
}
}
// Build a building and paint it red
$bldgA = new Building('red');
// Tell us how many floors these buildings have, and their painted color
$bldgA->describe();
?>
A: To answer your question: within an object oriented design, all code belongs inside a method; either a "special" method like the constructor, within a regular method, or (in languages other than PHP) in getter/setter methods (http://php.net/manual/en/language.oop5.properties.php has a way of implementing those in PHP).
Outside of methods, you're allowed to declare properties or attributes - but you should think of that really as a declaration, not a way of executing logic. The fact you can assign literals during the declaration is purely a convenience.
A: Don't assign expressions as variable. Do it in the Constructor:
$this->total_stairs = $this->number_of_floors * $this->stairs_per_floor;
or do
public $total_stairs= $this->number_of_floors * $this->stairs_per_floor;
A: you have to use the instance variables, without $this-> they are interpreted as local variables.
$this->total_stairs = $this->number_of_floors*$this->stairs_per_floor;
also, move those to the constructor, as they are (look like) instance specific.
A: You can't execute expressions when define properties, even with constants and heredocs.
Calculate them in __construct method.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527846",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: How to extract parameters from a list and pass them to a function call What is a good, brief way to extract items from a list and pass them as parameters to a function call, such as in the example below?
Example:
def add(a,b,c,d,e):
print(a,b,c,d,e)
x=(1,2,3,4,5)
add(magic_function(x))
A: You can unpack a tuple or a list into positional arguments using a star.
def add(a, b, c):
print(a, b, c)
x = (1, 2, 3)
add(*x)
Similarly, you can use double star to unpack a dict into keyword arguments.
x = { 'a': 3, 'b': 1, 'c': 2 }
add(**x)
A: Use the * operator. So add(*x) would do what you want.
See this other SO question for more information.
A: I think you mean the * unpacking operator:
>>> l = [1,2,3,4,5]
>>> def add(a,b,c,d,e):
... print(a,b,c,d,e)
...
>>> add(*l)
1 2 3 4 5
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527849",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "65"
} |
Q: Mail functionality using OPA import stdlib.web.mail
from = {name="name" address={local="username" domain="gmail.com"}}
to = {name="name" address={local="username" domain="gmail.com"}}
r = Email.try_send(from, to, "Subject", {text = "This is Great!"})
server = Server.one_page_server("Mail", [], [], r)
the following error I'm getting
Error
File "mail.opa", line 6, characters 4-66, (6:4-6:66 | 166-228)
Function was found of type
Email.email, Email.email, string, Email.content -> Email.send_status but
application expects it to be of type
{ address: { domain: string; local: string } / 'c.b; name: string } / 'c.a,
{ address: { domain: string; local: string } / 'c.d; name: string } / 'c.c,
string, { text: string } / 'c.e -> 'a.
Types string and { none } / { some: string } are not compatible
Hint:
Error occurred through field name.
Can anyone help me with Mail functionality in Opa?
A: There is a number of problems with this code:
*
*Notice that in Email.email type the name field is optional; so if you want to include it you should provide some("name"), not just "name"
*Server.one_page_server contains 2 arguments not 4.
*The last argument to one_page_server should be the xhtml of the page, whereas your r is the result of sending an email.
After those fixes your code could look something like this:
import stdlib.web.mail
from = {name=some("name") address={local="username" domain="gmail.com"}} : Email.email
to = {name=some("name") address={local="username" domain="gmail.com"}} : Email.email
page() =
status = Email.try_send(from, to, "Subject", {text = "This is Great!"})
<>Email sent</>
server = Server.one_page_server("Mail", page)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527865",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: regex - URL extension redirect help I have a couple of domain extensions that I'd like to redirect to specific pages.
Like example.de has to redirect to example.de/de/ and example.fr to example.fr/fr/.
How can I achieve this? I'm new to regex.
A: You will edit your .htacess file and put something like to :
RedirectMatch permanent example\.de/$ http://example.de/de
RedirectMatch permanent example\.fr/$ http://example.fr/fr
....
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527867",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Cannot parse JSON data jQuery autocomplete I am having trouble getting autocomplete to work, and I believe it is because of parsing.
JavaScript code:
$('#id_emp_name').autocomplete({
source: '/mycompany/employees.json',
minLength: 1,
dataType: 'json',
delay: 0,
parse: function(data) {
var parsed = [];
for(var i = 0; i < data.fields.length; i++) {
parsed[parsed.length] =
{
data: data.fields[i],
value: data.fields[i].eng_name,
result: data.fields[i].eng_name
};
}
return parsed;
},
formatItem: function(item) {
var name = '';
name = '(' + item.eng_name + ', ' + item.rank + ')';
return name;
}
});
Sample JSON output: url.com/mycompany/employees.json?term=e:
[
{
"pk": 1,
"model": "system.employees",
"fields": {
"salary": "1234",
"rank": "manager",
"entity_status": "n1",
"chi_name": "n/a",
"eng_name": "Eli",
"department": "marketing",
"employment_end_date": null,
"employment_date": "2011-09-20"
}
}
]
View:
def employeeJSON(request):
if request.method == 'GET' and request.GET['term']:
q_term = request.GET['term']
emp_list = Employees.objects.filter(eng_name__icontains=q_term)
json_serializer = serializers.get_serializer('json')()
json_data = json_serializer.serialize(emp_list, ensure_ascii=False)
return HttpResponse(
json_data, mimetype='application/json; charset=utf-8'
)
I am using jQuery UI autocomplete. I get no values when I type into the textbox, the autocomplete popup partially pops up with no values.
However, whenever I type, I am calling GET requests:
[23/Sep/2011 18:59:51] "GET /mycompany/employees.json?term=e HTTP/1.1" 200 241
[23/Sep/2011 18:59:53] "GET /mycompany/employees.json?term=el HTTP/1.1" 200 241
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527883",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Validate image size in carrierwave uploader All uploads should be at least 150x150 pixels. How to validate it with Carrierwave?
A: It surprised me just how difficult it was to search around for a clear-cut way to validate image width & height with CarrierWave. @Kir's solution above is right on, but I wanted to go a step further in explaining what he did, and the minor changes I made.
If you look at his gist https://gist.github.com/1239078, the answer lies in the before :cache callback he has in the Uploader class. The magic line is
model.avatar_upload_width, model.avatar_upload_height = `identify -format "%wx %h" #{new_file.path}`.split(/x/).map { |dim| dim.to_i }
in his case, avatar_upload_width & avatar_upload_height are attributes of his User model. I didn't want to have to store width&height in the database, so in my model I said:
attr_accessor :image_width, :image_height
Remember, you can use attr_accessor for attributes you want to have on hand when messing with a record, but just don't want to persist them to the db. So my magic line actually turned into
model.image_width, model.image_height = `identify -format "%wx %h" #{new_file.path}`.split(/x/).map { |dim| dim.to_i }
So now I have the width & height of my image stored in the model object. The last step is to write a custom validation for the dimensions, so in your model you need something like
validate :validate_minimum_image_size
And then below it define your custom validation method, same as in the gist
# custom validation for image width & height minimum dimensions
def validate_minimum_image_size
if self.image_width < 400 && self.image_height < 400
errors.add :image, "should be 400x400px minimum!"
end
end
A: I just made a custom validator that aims to be more Rails 4+ syntax friendly.
I took ideas from the others responses on this thread.
Here is the gist: https://gist.github.com/lou/2881f1aa183078687f1e
And you can use it like this:
validates :image, image_size: { width: { min: 1024 }, height: { in: 200..500 } }
In this particular case it should be:
validates :image, image_size: { width: 150, height: 150 }
A: Why not to use MiniMagick? Modified DelPiero's answer:
validate :validate_minimum_image_size
def validate_minimum_image_size
image = MiniMagick::Image.open(picture.path)
unless image[:width] > 400 && image[:height] > 400
errors.add :image, "should be 400x400px minimum!"
end
end
A: I made a slightly more complete validator based on @skalee's answer
class ImageSizeValidator < ActiveModel::EachValidator
def validate_each(record, attribute, value)
unless value.blank?
image = MiniMagick::Image.open(value.path)
checks = [
{ :option => :width,
:field => :width,
:function => :'==',
:message =>"Image width must be %d px."},
{ :option => :height,
:field => :height,
:function => :'==',
:message =>"Image height must be %d px."},
{ :option => :max_width,
:field => :width,
:function => :'<=',
:message =>"Image width must be at most %d px."},
{ :option => :max_height,
:field => :height,
:function => :'<=',
:message =>"Image height must be at most %d px."},
{ :option => :min_width,
:field => :width,
:function => :'>=',
:message =>"Image width must be at least %d px."},
{ :option => :min_height,
:field => :height,
:function => :'>=',
:message =>"Image height must be at least %d px."},
]
checks.each do |p|
if options.has_key?(p[:option]) and
!image[p[:field]].send(p[:function], options[p[:option]])
record.errors[attribute] << p[:message] % options[p[:option]]
end
end
end
end
end
Use it like validates :image, :image_size => {:min_width=>400, :min_height => 400}.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527887",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "21"
} |
Q: Dijit events not working in dynamic panes Can someone tell me why none of the following will work?
EDIT
(Just incase the link goes down this question is about how you can't seem to fire events in a page that is loaded into a dijit pane. This is applicable for Firefox 6.0.2, Crome 12.0.742.100 and Opera 11.00.1156 )
<!-- index.html -->
<script>
dojo.addOnLoad(function() {
dijit.byId("mainSettings").set("href","index2.html");
});
</script>
<body class="claro">
<div id="main" dojoType="dijit.layout.BorderContainer">
<div dojoType="dojox.layout.ContentPane" splitter="false" id="mainSettings" region="center"></div>
</div>
</body>
<!-- index2.html -->
<!-- THIS WORKS!!! -->
<select dojoType="dijit.form.Select">
<option value="bool">On/Off</option>
<option value="date">Date</option>
<option value="float">Number</option>
<option value="text">Text</option>
<script type="dojo/method" event="onChange">
alert("change");
</script>
</select>
<!-- NONE OF THIS WORKS!!! -->
<select dojoType="dijit.form.Select" onChange="change1">
<option value="bool">On/Off</option>
<option value="date">Date</option>
<option value="float">Number</option>
<option value="text">Text</option>
</select>
<script type="dojo/method" event="change1">
alert("change1");
</script>
<button dojoType="dijit.form.Button" onClick="change2">
change2
</button>
<script type="dojo/method" event="change2">
alert("change2");
</script>
<script>
dojo.addOnLoad(function() {
dojo.connect(dijit.byId('button2'), 'onClick', function(){
alert("change3");
});
});
</script>
<button dojoType="dijit.form.Button" id="button2">
button2
</button>
EDIT
Dojango code:
#forms.py
type = CharField(widget=Select(choices=VARIABLE_CHOICES,attrs={'onChange':'letterVariableTypeSelectChange'}))
#template
{{ form.type }}
<script>
function letterVariableTypeSelectChange(){
alert("dave");
}
</script>
A: Try setting the executeScripts and parseOnLoad properties to true on the dojox.layout.ContentPane
<div id="main" dojoType="dijit.layout.BorderContainer">
<div dojoType="dojox.layout.ContentPane" executeScripts="true" parseOnLoad="true" splitter="false" id="mainSettings" region="center"></div>
</div>
There also appears to be a fundamental disparity to how you are using dojo/method.
The <script type="dojo/method"> tags should go inside the elements that they are overriding
Notice how your snippet that works is defined:
<select dojoType="dijit.form.Select">
<option value="bool">On/Off</option>
<option value="date">Date</option>
<option value="float">Number</option>
<option value="text">Text</option>
<!--Script tag inside widget node, event is the name of the event to override -->
<script type="dojo/method" event="onChange">
alert("change");
</script>
</select>
versus the ones that don't work:
<!--onChange here is specified directly on the widget (which is incorrect), should be in the
<script type="dojo/method" event="OnChange">
-->
<select dojoType="dijit.form.Select" onChange="change1">
<option value="bool">On/Off</option>
<option value="date">Date</option>
<option value="float">Number</option>
<option value="text">Text</option>
</select>
<!--script tag outside the select. event refers to a nonexistent event for the widget.-->
<script type="dojo/method" event="change1">
alert("change1");
</script>
You get can the list of available events that you can use dojo/method to override at the reference documentation for a given widget.
http://dojotoolkit.org/api/dijit/form/FilteringSelect
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527888",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Oracle query Java EE, Entity Manager If I have an Oracle database, with structure, SCHEMA/TABLE1 SCHEMA/TABLE2 and I want to create a query to select all rows from Table1, would it be,
"Select x from SCHEMA.TABLE1 x"
A: If you have an entity such as:
@Entity
@Table(schema="SCHEMA", name="TABLE1")
public class Table1Class {
...
}
Then, the following basic JPQL Query would select all the Table1Class entities:
Select x from Table1Class x.
Summing up, you don't need to (not that you can, either) specify schema and table name on JPQL queries, just the class name the table is mapped to.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527892",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to call the ok button in the EditTextPreference I have an EditTextPreference in the PreferenceActivity. When user click the EditTextPreference will show a dialog. In the dialog, user can input a value, and the dialog has "OK" and "Cancel" buttons. I want to call the click event of ok button to check the value, but I do not know how to call the click even.
I know I can use EditTextPreference.setOnPreferenceChangeListener(), but I want to know if I can use OK button click event.
A: You can extend EditTextPreference to get control over the click handler.
package myPackage;
public class CustomEditTextPreference extends EditTextPreference {
public CustomEditTextPreference(Context context) {
super(context);
}
public CustomEditTextPreference(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomEditTextPreference(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
}
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
// add Handler here
}
super.onClick(dialog, which);
}
}
In the Xml instead of <EditTextPreference/> reference it like this:
<myPackage.CustomEditTextPreference android:dialogTitle="Registration Key" android:key="challengeKey" android:title="Registration Key" android:summary="Click here to enter the registration key you received by email."/>
A: Actually you can't since the preference is using an internal AlertDialog.Builder and creates a new dialog every time you click the preference. The next problem is that the dialog builder sets the click listener for you and if you override them you might destroy the close behavior of the button click.
This bothered me since I wanted a preference which only closes on valid input (otherwise a toast is shown and user should press cancel if he can't get it right).
(If you really need a solution for exactly this problem) You can find general solution of a validating DialogPreference here and a validating EditTextPreference here which I wrote myself.
A: Your preference activity doesn't appear to be implementing a
OnSharedPreferenceChangeListener
You may want to read over the excellent answer to the question: Updating EditPreference
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527894",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: How to match whitespace, carriage return and line feed using regular expression in PHP? I am working with a regular expression in PHP. I have the following string:
<img
src="/files/admin/hotel_website.gif" alt="Go To The Hotel's Web
Site" align="absmiddle" border="0" class="hotel_icon" />
This string contains carriage return and line feed characters.
I want my regular expression to replace html img tags with IMG but this does not work with the above text.
I discovered it contained these characters by looping through each character in the string and printing out the hexadecimal representation which can be found here (http://pastebin.com/ViNdBsRV).
Here is my regular expression:
strip_tags(preg_replace('/^\s*<img\s*.*\/?>\s*$/i', '[IMG]', $test));
Appreciate the help.
A: This worked for me it matches multiple spaces and multilines, also any other character or symbol.
[\S+\n\r\s]+
Hope this helps anyone.
It matches for example:
stpd : asdfasdf
this is also matching ***
A: [\n\r]+ Will match new lines. For White spaces add [\n\r\s]+
A: This:
preg_replace("#<img.+?/>#is", '[IMG]', $test)
Personally when I'm making a regular expression I always try to go the shortest/simplest.
Here you want to replace an entire tag, which starts with '<img' and ends with '/>', '.+?' is a non greedy (lazy) catch.
And for the modifiers 'i' for the case and 's' to . the possibility to be a new lines.
More on greedyness vs lazyness : http://www.regular-expressions.info/repeat.html
More on modifiers: http://www.php.net/manual/en/reference.pcre.pattern.modifiers.php
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "52"
} |
Q: What does joomla 1.7 lack in comparison with drupal 7 Drupal is considered as more powerful among the two. However, with release of joomla 1.6 some new features have been added like Nested Categories, Granular ACL System, Tableless Core Components etc which were lacking in comparison with drupal previously. So is there any point in using drupal now?
A: In my opinion Drupal is better for more complicated sites...Joomla (and Wordpress) can be extended to function as more complex websites but their great strength is that out of the box they can provide the majority of functionality that's needed for a basic website; essentially Joomla is more of an 'off-the-shelf' solution while Drupal is a lot more powerful (it's entire makeup is extensible and modular) but requires more configuration and a slightly steeper learning curve.
Check out this article, very good comparison of Drupal 7 and Joomla 1.6. The line that sticks out more than any other to me is:
Drupal 7.0 remains the more powerful framework and indeed extends its lead.
A: Thats a little bit the issue. I would say that Drupal is inferior to Joomla due to its lack of object orientation, while most of the shortcomings of Joomla can be solved by the huge number of extensions available.
I would say that there is no good answer to this question and the best solution for you will be to test both systems and see which one suits you better.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Entity Framework, how to manually produce inner joins with LinQ to entitites Let's imagine I have an table called Foo with a primary key FooID and an integer non-unique column Bar. For some reason in a SQL query I have to join table Foo with itself multiple times, like this:
SELECT * FROM Foo f1 INNER JOIN Foo f2 ON f2.Bar = f1.Bar INNER JOIN Foo f3 ON f3.Bar = f1.Bar...
I have to achieve this via LINQ to Entities.
Doing
ObjectContext.Foos.Join(ObjectContext.Foos, a => a.Bar, b => b.Bar, (a, b) => new {a, b})
gives me LEFT OUTER JOIN in the resulting query and I need inner joins, this is very critical.
Of course, I might succeed if in edmx I added as many associations of Foo with itself as necessary and then used them in my code, Entity Framework would substitute correct inner join for each of the associations. The problem is that at design time I don't know how many joins I will need. OK, one workaround is to add as many of them as reasonable...
But, if nothing else, from theoretical point of view, is it at all possible to create inner joins via EF without explicitly defining the associations?
In LINQ to SQL there was a (somewhat bizarre) way to do this via GroupJoin, like this:
ObjectContext.Foos.GroupJoin(ObjectContext.Foos, a => a.Bar, b => b.Bar, (a, b) => new {a, b}).SelectMany(o = > o.b.DefaultIfEmpty(), (o, b) => new {o.a, b)
I've just tried it in EF, the trick does not work there. It still generates outer joins for me.
Any ideas?
A: In Linq to Entities, below is one way to do an inner join on mutiple instances of the same table:
using (ObjectContext ctx = new ObjectContext())
{
var result = from f1 in ctx.Foo
join f2 in ctx.Foo on f1.bar equals f2.bar
join f3 in ctx.Foo on f1.bar equals f3.bar
select ....;
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527897",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: how to arrange the divs in the page like google map or other map site We are now trying to build a map library like google/bing/yahoo,we will use it offline.
However I found that I have no idea about how to arange the divs in the page,since there are some many different types of divs.
1) the map tiles (small image 256X256)
2)the overlayer(marker/informationwindow/polygon...)
3)the control.
I have to try to read the html source codes of google and bing and etc. But I found it is difficult to understand them.
For exmaple,this frangment is copyed from another online map site of China.
As you can see,it is just a exmaple for how to adding a marker to the map.
But take the code,there are so many nested divs,most of them have the property of "width:0;height:0",I do not know why?
Since in my opinion,the marker is just an icon,just put it in the page.
Why use so many nested divs and even the "map" tag?
But I think they must have the advantages which I can not find.
Any one can give some suggestions?
A: Typically you insert a div in HTML when you want to create a block element but there is no more semantically-loaded element available with the correct meaning.
I think the answer to your question is to use just as many div elements as you need for your purposes. Do not add more just because you can. Sometimes you don't need any div elements at all - you can use other more meaningful elements such as img, ul, p, etc. You can sometimes avoid inserting a wrapping div by using CSS to change an inline element such as a into a block element.
If you need more later then add them later. Don't worry about what Google/Bing/Yahoo do. Their requirements are probably different to yours.
A: Have you looked at the Google Maps sample code and demo gallery?
http://code.google.com/apis/maps/documentation/javascript/demogallery.html
http://code.google.com/apis/maps/documentation/javascript/examples/index.html
I'm not sure how you would use this "offline" considering the sample you provided makes a call to the internet to get the map. Also all of these types of maps rely heavily on javascript and ajax calls to constantly update the map. Do you mean these pages would be secured and not public?
A: How about you just use maybe a 5x5 grid of divs, move them as they are dragged out of view, and then texture them dynamically with AJAX calls.
If I am understanding you correctly, all of the layers can be thrown on top of each other with z-index.
<div id="control" style="z-index:-1;"></div>
<div id="overlay" style="z-index:-2;"></div>
<div id="map" style="z-index:-3;"></div>
Then you can use each of these divs as containers for different parts of your map.
As you drag 1 div off to, say, the right, then it will automatically bump itself to the left side of your grid and retexture itself (background-image) through an ajax call.
That's what I would do, at least.
A: Use the Google Maps API you can see an example of custom tiles here: http://code.google.com/apis/maps/documentation/javascript/examples/maptype-base.html
You would need to copy all the files to your computer to be exceccible offline. Your javascript would look something like this:
function CoordMapType() {
}
CoordMapType.prototype.tileSize = new google.maps.Size(256,256);
CoordMapType.prototype.maxZoom = 19;
CoordMapType.prototype.getTile = function(coord, zoom, ownerDocument) {
var div = ownerDocument.createElement('DIV');
div.style.backgroundImage=coord+'.js';
return div;
};
CoordMapType.prototype.name = "Tile #s";
CoordMapType.prototype.alt = "Tile Coordinate Map Type";
var map;
var chicago = new google.maps.LatLng(41.850033,-87.6500523);
var coordinateMapType = new CoordMapType();
function initialize() {
var mapOptions = {
zoom: 10,
streetViewControl: false,
mapTypeId: 'coordinate',
mapTypeControlOptions: {}
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
google.maps.event.addListener(map, 'maptypeid_changed', function() {
var showStreetViewControl = map.getMapTypeId() != 'coordinate';
map.setOptions({'streetViewControl': showStreetViewControl});
});
// Now attach the coordinate map type to the map's registry
map.mapTypes.set('coordinate', coordinateMapType);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: vkontakte api for C# I want develop a music finder program. I choose music database, vkontakte. But I can't find the vkontakte api example for c# .
A: https://github.com/grunichev/rhythmbox-vkontakte
http://silverlightvkapi.codeplex.com/
http://xternalx.com/sexy/vkontakte-c-api/
A: Vkontakte api .NET wrapper
A: Silverlight API:
Silverlight vkontakte API
A: Download VKMusic from this website
and use It.) It is joke. Better go to http://www.gotdotnet.ru/forums/2/127256/ Russian programers know about vk more and you don't need to use english.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: HTML Interface for a java chatclient I have this project thats about to start. We're making a Chatclient that we want to integrate to a webapp.
We have the following requirments:
- Java server
- Java client
We've practically compleated the coding of both the client and server, but the thing is that we want to integrate the client applet into a webapp with all the layouting done in HTML. Basically, we need a interface in HTML but the backend in java on the browser. How do we do that?
A: you should consider rendering your HTML client code with Java Servlets os JSP.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527904",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Minimize form to system tray I want to hide my form while keeping my application running in background.
I've used notifyIcon and it remains always visible.
I've used "this.Hide();" to hide my form but unfortunately my application gets close (no exception).
I am also using threading and this form is on second thread.
Please tell me how can I solve it.
A: add the following event handlers for form resize and notify icon click event
private void Form_Resize(object sender, EventArgs e)
{
if (WindowState == FormWindowState.Minimized)
{
this.Hide();
}
}
private void notifyIcon_Click(object sender, EventArgs e)
{
this.Show();
this.WindowState = FormWindowState.Normal;
}
but this is not close you application
A:
I am also using threading and this form is on second thread.
My crystal ball says that you've used ShowDialog() to show the form. Yes, calling Hide() on a modal dialog will close it. Necessarily so, a modal dialog normally disables all of the windows in the application. If you hide it then there's no way for the user to get back to the program, there are no windows left to activate. That this form runs on another thread otherwise doesn't factor into the behavior.
You'll need to call Application.Run(new SomeForm()) to avoid this. Now it isn't modal and you can hide it without trouble. But really, do avoid showing forms on non-UI threads. There's no reason for it, your main thread is already quite capable.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
} |
Q: How to use time format on Java I have 2 variables: first variable for hours and second variable for minutes. But format for this data is "24 hours", but I need resulting string similar "5:30 pm".
How can I format my time for this format?
A: Since you already have the hours and minutes as variables, date and date format objects might be overkill. You can use a method like this:
public String getTimeString(int hours, int minutes)
{
String AmPm = "AM";
if(hours > 12)
{
hours -= 12;
AmPm = "PM";
}
return String.format("%d:%02d %s", hours, minutes, AmPm);
}
A: public static void main(String[] args) {
formatTime(1, 23);
formatTime(11, 33);
formatTime(14, 43);
}
private static void formatTime(int hours, int minutes) {
Calendar calendar = new GregorianCalendar();
calendar.set(Calendar.HOUR, hours);
calendar.set(Calendar.MINUTE, minutes);
SimpleDateFormat df = new SimpleDateFormat("hh:mm a");
System.out.println(df.format(calendar.getTime()));
}
Output will be:
01:23 PM
11:33 PM
02:43 AM
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527915",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: greyscale Iplimage to android bitmap I am using opencv to convert android bitmap to grescale by using opencv. below is the code i am using,
IplImage image = IplImage.create( bm.getWidth(), bm.getHeight(), IPL_DEPTH_8U, 4); //creates default image
bm.copyPixelsToBuffer(image.getByteBuffer());
int w=image.width();
int h=image.height();
IplImage grey=cvCreateImage(cvSize(w,h),image.depth(),1);
cvCvtColor(image,grey,CV_RGB2GRAY);
bm is source image. This code works fine and converts to greyscale, i have tested it by saving to sdcard and then loading again, but when i try to load it using below method my app crashes, any suggestions.
bm.copyPixelsFromBuffer(grey.getByteBuffer());
iv1.setImageBitmap(bm);
iv1 is imageview where i want to set the bm.
A: I've never used the OpenCV bindings for Android, but here's some code to get you started. Regard it as pseudocode, because I can't try it out... but you'll get the basic idea. It may not be the fastest solution. I'm pasting from this answer.
public static Bitmap IplImageToBitmap(IplImage src) {
int width = src.width;
int height = src.height;
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
for(int r=0;r<height;r++) {
for(int c=0;c<width;c++) {
int gray = (int) Math.floor(cvGet2D(src,r,c).getVal(0));
bitmap.setPixel(c, r, Color.argb(255, gray, gray, gray));
}
}
return bitmap;
}
A: Your IplImage grey has only one channel, and your Bitmap bm has 4 or 3 (ARGB_8888, ARGB_4444, RGB_565). Therefore the bm can't store the greyscale image. You have to convert it to rgba before use.
Example:
(your code)
IplImage image = IplImage.create( bm.getWidth(), bm.getHeight(), IPL_DEPTH_8U, 4);
bm.copyPixelsToBuffer(image.getByteBuffer());
int w=image.width(); int h=image.height();
IplImage grey=cvCreateImage(cvSize(w,h),image.depth(),1);
cvCvtColor(image,grey,CV_RGB2GRAY);
If you want to load it:
(You can reuse your image or create another one (temp))
IplImage temp = cvCreateImage(cvSize(w,h), IPL_DEPTH_8U, 4); // 4 channel
cvCvtColor(grey, temp , CV_GRAY2RGBA); //color conversion
bm.copyPixelsFromBuffer(temp.getByteBuffer()); //now should work
iv1.setImageBitmap(bm);
I might it will help!
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527917",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: splitting a string into N number of strings I want to split a string into N number of 2char strings. I know I must use String.subSequence. However I want it to keep creating these until the string is > 2
A: Try this:
int n = 3;
String s = "abcdefghijkl";
System.out.println(Arrays.toString( s.split("(?<=\\G.{2})(?=.)", n + 1 ) ) );
//prints: [ab, cd, ef, ghijkl], i.e. you have 3 2-char groups and the rest
The regex works as follows: find any position after 2 characters (zero-width postive look behind (?<=...)) starting from the last match position (\G) and before at least one more character (zero-width positive look ahead (?=.)). This should not match the positions at the start and end of the string and thus n can be as big as you want without resulting in an empty string at the start or the end.
Edit: if you want to split as much as possible, just leave out the second parameter to split.
Example:
String digits = "123456789";
System.out.println(Arrays.toString( digits.split("(?<=\\G.{2})(?=.)" ) ) ); //no second parameter
//prints: [12, 34, 56, 78, 9]
A: String s = "asdasdasd";
List<String> segments = new ArrayList<String>();
for (int i = 1; i < s.length(); i=i+2) {
segments.add(s.substring(i-1, i+1));
}
System.out.println(segments.toString());
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527923",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: How can i map a POJO to a directory with ApacheDs? i have downloaded ApacheDS as my LDAP server, now i am trying to map a pojo to a directory, is there any ODM (Object Directory Mapper) out there? i mean something like Hibernate but for LDAP.
i have found s2Directory and LDAP-ODM, but the tutorial and user support on these seems not to be sophisticated. so do you know anything for this purpose?
thnx
A: The UnboundID LDAP SDK for java provides a relatively simple persistence framework for use with LDAP directories.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to programatically get ALL (read and unread) messages from gmail, read status, etc? I have a customer service web app requirement, which requires that I work pull & integrate data from Gmail, eBay, Amazon, and Paypal. My solution is going to be developed in ASP.Net 4 with C#.
The issue that I'm running into is that my client needs pretty much all of the information that Gmail has about each and every email that comes in & the ATOM feed coming from Gmail seems to be a bit lacking. I realize I can also use POP3 or IMAP, but they too are lacking for a number of reasons.
Specifically, the client needs the read status of emails (whether or not THEY have read emails that were sent to THEM). They also need for all of the filters to remain intact. So if an email is tagged with x,y, & z, then I need to know about it.
The ATOM feed only shows me unread emails, so that's out.
POP3 has no clue (and rightfully so) whether or not they've read an email or not (unless I pull it into a database and manage read status, myself...but that doesn't work if they actually read a mail from within gmail itself).
IMAP seems like it would give me everything I need, but I'm not 100% sure on that. What do you all think? Also, IMAP is SOOO slow. Is anyone aware of any decent libraries that are fairly fast. We're talking about a customer inbox with some 360,000'ish messages at the present time, & the client would prefer to keep those messages at gmail & not work with a disconnected database.
Thoughts / Opinions?
A: IMAP does provide read/not-read status for each message and you can pull from particular 'labels' (folders) or just pull from the 'all messages' bucket. You don't need to pull the entire message either, you can ask for headers only, giving you the ability to quickly scan many emails.
I've been working on a program to pull my entire gmail dataset down for my own tinkering and processing. I'm using linux, and while there are a multitude of imap 'mirror' and imap 'processing' applications out there, I just want to play with the data, being able to do what I want with it, without stuffing it back into an imap server locally. It's been working decently and I'm using the email's UID (modified slightly) as a file name to dump the headers & email data. Of course, you could massage the data and update a database or whatever at that point, I'm just stashing it for post-processing later. Looking for trends in my email, mostly tinkering.
I tried using the etpan libraries for IMAP processing, didn't find them to my liking, so I've been pulling imap routines from other email programs and servers to play with. I have the RFC's, but really really trying to not reinvent the wheel here if I can help it.
Yup, not the best answer, but hopefully some information to help. I imagine there are nice libraries for PHP, or other web-based systems, I've been working with C++/C myself.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527937",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: How to find the number of numeric starts with and find the top 3 count among them? I have a list which contains numeric strings. The numeric strings in list may start with any number from 1 to 9 (it doesn't start with "0"). Now i need to find three top occurrences in the list.
Ex:
1234
2345
2343
4356
6434
2343
2222
4545
6666
6653
top three occurrences in the above list respectively are 2,6,4.
A: int occurences[10]; // Store numbers occurences in number index
For example if occurence of 5 is equal to 6 then occurences[5] = 6
Second thing you must do is write a function to get count of occurences.
int occurence(int number)
{
int i=0;
for(;i<listSize;i++) {
if(atoi(myList[i]) == number)
occurences[number]++;
}
}
The last thing you must do is find the biggest 3 element in occurences array.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-2"
} |
Q: Custom right-click menu - OnAction works straight away rather than on button-press I'm creating a custom menu in Excel which consists of various sub-menus. It's for picking various machinery items and there's about 250 possible outcomes.
In any case, I've got the menu built and want it so that the .Caption is entered into the cell when the menu is used. I've put the .OnAction into the relevant buttons but, unfortunately, the .OnAction activates when the file is opened, not when the button is clicked. As such, all 250-odd .Captions are quickly entered into the same cell in quick succession.
Quick edit - the important bit is towards the bottom of the BuildMenus, where the .OnAction calls the function AddStuff. I know this is running on the Workbook_Activate which is why it runs straight away but everywhere else I've looked online does it the same way.
Private Sub Workbook_Activate()
BuildMenus
End Sub
Private Sub BuildMenus()
'Workbook_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)
Dim AmountOfCats As Integer
Dim ThisIsMyCell As String
ThisIsMyCell = ActiveCell.Address
'this is where we would set the amount of categories. At the moment we'll have it as 15
AmountOfCats = 15
Dim cBut As CommandBarControl
Dim Cats As CommandBarControl
Dim SubCats As CommandBarControl
Dim MenuDesc As CommandBarButton
On Error Resume Next
With Application
.CommandBars("Cell").Controls("Pick Machinery/Plant...").Delete
End With
Set cBut = Application.CommandBars("Cell").Controls.Add(Type:=msoControlPopup, Temporary:=True)
cBut.Caption = "Pick Machinery/Plant.."
With cBut
.Caption = "Pick Machinery/Plant..."
.Style = msoButtonCaption
End With
Dim i As Integer
Dim j As Integer
Dim k As Integer
Dim SC As Integer
Dim AmountOfMenus As Integer
SC = 1
Dim MD As Integer
MD = 1
Dim MyCaption As String
For i = 0 To AmountOfCats - 1
Set Cats = cBut.Controls.Add(Type:=msoControlPopup, Temporary:=True)
Cats.Caption = Categories(i + 1)
Cats.Tag = i + 1
For j = 0 To (SubCatAmounts(i + 1) - 1)
Set SubCats = Cats.Controls.Add(Type:=msoControlPopup, Temporary:=True)
SubCats.Caption = SubCatArray(SC)
SubCats.Tag = j + 1
AmountOfMenus = MenuAmounts(SC)
For k = 0 To AmountOfMenus - 1
Set MenuDesc = SubCats.Controls.Add(Type:=msoControlButton)
With MenuDesc
.Caption = MenuArray(MD)
.Tag = MD
MyCaption = .Caption
.OnAction = AddStuff(MyCaption)
End With
MD = MD + 1
Next
SC = SC + 1
Next
Next
On Error GoTo 0
End Sub
Function AddStuff(Stuff As String)
Dim MyCell As String
MyCell = ActiveCell.Address
ActiveCell.Value = Stuff
End Function
A: OnAction expects a string value: instead you are calling your AddStuff sub while creating your menu...
.OnAction = "AddStuff """ & MyCaption & """"
is what you want (assuming I got my quotes right)
A: I was making a mistake with my AddStuff - I was calling it as a function when instead it should have been a macro (or a regular sub). A slight modification to Tim Williams' .OnAction code
MyButton.OnAction = "AddStuff(""" & MyButton.Caption & """)"
did the trick.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527943",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Loading values into an array from two different arrays iphone sdk Here I am having a situation, I'm using the following code:
int x=0;
for (int i=0; i<=[arrayDeals count]-1; i++) {
x++;
//NSString *deal = [arrayDeals objectAtIndex:i];
combinedArr = [[NSMutableArray alloc]initWithObjects:
[CustomObject customObjectWithName:[arrayDeals objectAtIndex:i] andNumber:x],nil];
}
I need to load the values from arrayDeals and the 'x' value into combinedArr. So, I put this in a for loop. But i got only one value from each arrays. What is went wrong here? Please help me. (here CustomObject is a NSObject)
Thank you.
A: Well there are many things wrong with the code you posted, but I think this is what you want:
int x = 0;
NSMutableArray *combinedArr = [[NSMutableArray alloc] init]:
NSInteger count = [arrayDeals count];
for (int i = 0; i < count; i++) {
x++;
CustomObject *customObject = [CustomObject customObjectWithName:[arrayDeals objectAtIndex:i] andNumber:x];
[combinedArr addObject:customObject];
}
To give you some idea of what is wrong with the code you posted:
combinedArr = [[NSMutableArray alloc]initWithObjects:
[CustomObject customObjectWithName:[arrayDeals objectAtIndex:i] andNumber:x],nil];
Here you create a new NSMutableArray to which you assign an new object to taked the object from the array arrayDeals. But you create this NSMutableArray for every item in the array arrayDeals and you assign them to the same variable.
So each iteration you leak the NSMutableArray.
Also :
for (int i=0; i<=[arrayDeals count]-1; i++) {
is the same as
for (int i=0; i < [arrayDeals count]; i++) {
but the count is called every time you iterate, so as per my example I saved the count in a int to just speed things up.
You could even speed the code up using fast Enumeration:
NSInteger x = 0;
NSMutableArray *combinedArr = [[NSMutableArray alloc] init]:
for (id object in arrayDeals) {
id secondObject = [secondArray itemAtIndex:x];
// Arrays start at 0 so only up it after we've got the object.
x++;
CustomObject *customObject = [CustomObject customObjectWithName:object andNumber:x];
[combinedArr addObject:customObject];
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: cruisecontrol.net build number doesn't increment We use Cruise Control .Net as our build server. For our version numbering we use SvnRevionLabeller with the following config
<labeller type="svnRevisionLabeller">
<major>0</major>
<minor>1</minor>
<versionFile>VersionInfo.cs</versionFile>
<url>$(svn_src)/project/trunk</url>
<executable>$(svn_exe)</executable>
<username>$(svn_user)</username>
<password>$(svn_password)</password>
<incrementOnForce>true</incrementOnForce>
</labeller>
This works fine except after a broken build. The build number generated is the same as the build number of the last correct build before the broken ones.
What setting do we need to give the new correct build an incremented build number?
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: htaccess conflicting with wordpress htaccess I have the following code in my htaccess file:
RewriteEngine On
RewriteCond %{HTTP_HOST} !^www.example.com$
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301]
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
I avoid editing the automated code by Wordpress because the changes may be erased and I'll have to do it all again. I have another site running the first three lines of code and it's working perfectly to replace example.com for www.example.com. That's all I really need for this example.com site but still preserving the Wordpress properties.
The problem
example.com is not redirecting to www.example.com but instead displaying a 301 error.
A: I'm using the following lines in all my WordPress-Sites before the # BEGIN WordPress. This should solve your problem. The L (for last) is the solution
RewriteEngine On
RewriteBase /
RewriteCond %{HTTP_HOST} !^www\.example\.com$
RewriteRule ^(.*)$ http://www.example.com/$1 [L,R=301]
A:
"I avoid editing the automated code by Wordpress because the changes
may be erased and I'll have to do it all again."
You can avoid a WordPress installation from modifying its root .htaccess file.
Simply connect via FTP, or other means and chmod your WordPress root .htaccess file properties to 0444.
A: Where is the conflict? I can't see any conflict. WordPress only touches the lines after # BEGIN WordPress
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: Regex to match any character or fullstop? I'm trying to create a regex that takes a filename like:
/cloud-support/filename.html#pagesection
and redirects it to:
/cloud-platform/filename#pagesection
Could anyone advise how to do this?
Currently I've got part-way there, with:
"^/cloud-support/(.*)$" => "/cloud-platform/$1",
which redirects the directory okay - but still has a superfluous .html.
Could I just match for a literal .html with optional #? How would I do that?
Thanks.
A: "^/cloud-support/(\w+).html(.*)" => "/cloud-platform/$1$2"
A: Would something like this work?
"^/cloud-support/([^.]+)[^#]*(.*)$" => "/cloud-platform/$1$2"
A: Can you try the regex
"^/cloud-support/(.*)\.html(#.*)?$"
The \.html part matches .html while (#.*)? allows an optional # plus something.
A: Maybe something like this:
"^/cloud-support/(.*?)(\.html)?(#.+)$" => "/cloud-platform/$1$3"
where the first group is a non-greedy match (.*?)
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527958",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: use case for getProductAdditionalInformationBlock in magento I'd like to put some additional info under each item in the cart. I have this info already saved in table "sales_flat_quote_item" in "additional_info" field. So the question is only how to show it globally at all places where the items are shown.
I saw in several places under item name there is a structure like this:
<?php if ($addtInfoBlock = $this->getProductAdditionalInformationBlock()):?>
<?php echo $addtInfoBlock->setItem($_item)->toHtml() ?>
<?php endif;?>
For example in this files:
/app/design/frontend/base/default/template/checkout/cart/item/default.phtml
/app/design/frontend/base/default/template/checkout/onepage/review/item.phtml
So I suppose this is the place I should use for such task.
What I figured out is that:
I have to add my own block definition to for example:
<checkout_cart_index>
<block type="core/text_list" name="additional.product.info" translate="label">
<label>Additional Product Info</label>
<block type="various/itemrendererdefault" name="glass.additional" as="glass" template="checkout/cart/glass_additional.phtml"/>
</block>
</checkout_cart_index>
This is no problem so far. My class is loaded
class Site1_Various_Block_Itemrendererdefault extends Mage_Core_Block_Template {
public function setItem(Varien_Object $item) {
$this->setData('item', $item);
return $this;
}
public function getItem() {
return $this->_getData('item');
}
}
and the template checkout/cart/glass_additional.phtml is called.
But inside the template I have no idea how to get the info about what $item should I process. I tried:
$_item = $this->getItem();
print_r($_item);
$_item = $this->getData();
print_r($_item);
but it returns nothing.
So my question is: How to get $item data inside my template.
Can I access the data set in?
...
$addtInfoBlock->setItem($_item)->toHtml();
...
A: Krystian, the OP, already self-answered his question.
Quote:
I just solved the issue by setting my block as "additional.product.info"
<checkout_cart_index>
<block type="various/itemrendererdefault" name="additional.product.info" translate="label" template="checkout/cart/glass_additional.phtml"></block>
</checkout_cart_index>
Note: It's absolutely OK to self-answer your own question. Please just post it as an real answer, but not in a question or comment. Posting as real answer helps to keep the "Unanswered" list more clear (avoids making other people wasting their time).
A: I think to get the item instance you have to try this:
class Site1_Various_Block_Itemrendererdefault extends Mage_Core_Block_Template {
public function setItem(Varien_Object $item) {
$this->setData('item', $item);
return $this;
}
public function getItem() {
$parent = $this->getParentBlock();
if ($parent) {
$item = $parent->getItem();
}
}
}
Thanks !
A: I was having issues with this as well until I used a block type of core/template and a call to getParentBlock() in my custom template file. This might work for any custom block type but I didn't test.
In your layout/local.xml file:
<checkout_cart_index>
<reference name="additional.product.info">
<block type="core/template" name="additional.product.info.your_template" as="your_template" template="checkout/cart/item/your-template.phtml"/>
</reference>
</checkout_cart_index>
The $addtInfoBlock->setItem($_item)is called on the additional.product.info block, which would be the parent of any blocks you add underneath it. Because of this, you can call $this->getParentBlock() in your template to get access to it's data.
So now, in your checkout/cart/item/your-template.phtml:
$_item = $this->getParentBlock()->getItem();
/* get access to all product attributes, with a performance hit. */
$_product = $_item->getProduct()->load();
/* Some product attributes */
echo $_product->getName();
echo $_product->getSku();
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527959",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
} |
Q: Java ScrollPane overlapping contents I'm having what I am sure is very much a beginners problem with my JScrollPanes. The problem is that the vertical scrollbar overlaps the components within the enclosed panel (on the right hand side). It becomes a bit of a pain when the scrollbar overlaps the drop-down bit of JComboBoxes.
I have boiled the problem down to this little snippet - I hope it illustrates the issue.
public class ScrollTest extends JFrame
{
public ScrollTest()
{
super("Overlap issues!");
JPanel panel = new JPanel();
panel.setLayout(new GridLayout(100,0));
for(int b=0;b<100;++b)
{
panel.add(new JButton("Small overlap here ->"));
}
JScrollPane scrollpane = new JScrollPane(panel);
add(scrollpane);
pack();
setVisible(true);
}
public static void main(String[] args)
{
new ScrollTest();
}
}
I had a look first but couldn't see if anyone else had already addressed this problem. Sorry if it's a duplicate and many thanks for any help anyone can offer a java-newb like me!
A: The problem is that the default for a JScrollPane is to layout the components with a default of JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED which in turn adds the scrollbar without laying out the components again.
In your example you know you will need a scrollbar so change it to always display the scrollbar
public class ScrollTest extends JFrame
{
public ScrollTest()
{
super("Overlap issues!");
JPanel panel = new JPanel();
//Insets insets = panel.getInsets();
//insets.set(5, 5, 5, 25);
//insets.set(top, left, bottom, right);
panel.setLayout(new GridLayout(100,0));
for(int b=0;b<100;++b)
{
panel.add(new JButton("Small overlap here ->"));
}
JScrollPane scrollpane = new JScrollPane(panel);
scrollpane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
add(scrollpane);
pack();
setVisible(true);
}
public static void main(String[] args)
{
new ScrollTest();
}
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527962",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: passing command line parameter to spring config I want to laod the spring context file based on the command line. Basically I am going to get the region from the command line and instanciate the beans in the context file based on region. Is there a way to pass the command line param to FileSystemXmlApplicationContext without maintaining 2 different context files?
Thanks in advance.
A: Yes, it depends on where exactly you want to load it:
*
*use <import resource="${command.line.param}/context.xml" /> in your common applicationContext.xml
*use <param-value>${command.line.param}/applicationContext.xml</param-value> in your web.xml, in a context-param named contextConfigLocation
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527966",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Detecting browsers that don't support onunload/onbeforeunload Of all the browsers, it seems that only Opera doesn't support onunload/onbeforeunload events. (It's been fifteen years now, Opera!) Solutions for this issue have been covered many times, here for example: onbeforeunload support detection
Unfortunately, as of Opera 11.51, ("onbeforeunload" in window) == true, but the actual onbeforeunload event is never executed!
My web application needs to send data to server when a user leaves the page; I'm using a synchronous ajax request for this. It looks like I have to resort to using a "Save" button somewhere on the page to cover up for Opera issues. However, I don't want this button to confuse users whose browsers are capable of auto-saving through ajax, so I'd really like the button to only show up in Opera.
Is my only choice browser-detection? The problem is, Opera has an option to disguise itself as other browsers anyway.
A: I can't reproduce your finding that 'onbeforeunload' in window is true in Opera 11.5x. This is the best way to do it and should still work. Are you sure you haven't left in some definition somewhere, e.g. you've written
onbeforeunload = function (){ ... }
later in the same script that does the feature detection? If you do alert(window.onbeforeunload), what do you see? Could you share a link to the page with the problem?
A: Opera screwed the pooch on this one. I detect for Opera by looking for window.opera and if it exists, I deny Opera what it can't handle.
Using unload is no good I think, because it occurs too late in the game. Sometimes onbeforeunload is the only thing that'll do the trick. Once again, I just look for opera on the window object, and, if it exists, deny it the things it can't do. :)
PPK talks about it here: http://www.quirksmode.org/js/detect.html
A: For anyone stumbling across this post, this is a code snippet I use for detecting onbeforeunload support and if the browser doesn't support it I switch to onunload (note the use of jquery, obviously not required). In my case I use this code (and a little extra) to check if any AJAX requests are still active and stop the user navigating away. Keep in mind that using onunload isn't ideal because the browser will still navigate away from the page but at least it gives you a chance to warn the user that data might have been lost and they should go back and check.
You'll notice I'm using the isEventSupported() function available at https://github.com/kangax/iseventsupported for cross browser support detecting available events.
// If the browser supports 'onbeforeunload'
if (isEventSupported('beforeunload', window)) {
$(window).on('beforeunload', function(){
return 'This page is still sending or receiving data from our server, if you recently submitted data on this page please wait a little longer before leaving.';
});
}
// The browser doesn't support 'onbeforeunload' (Such as Opera), do the next best thing 'onunload'.
else {
$(window).on('unload', function(){
alert('This page was still sending or receiving data from our server when you navigated away from it, we would recommend navigating back to the page and ensure your data was submitted.');
});
}
A: See my answer to a similar / duplicated question. Basically, it sets up detection on the very first page on your domain and stores that detection result for all subsequent pages in localStorage. Including working example code.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
} |
Q: Removing license I'm nearing the end of my master's thesis, which was done in collaboration with a local company. I used their computers during the work, but they could not provide me with a Visual Studio licence, thus I used my own MSDN Academic Alliance licence. Now that I'm leaving the company, I need to remove the licence. Does a uninstallation completly remove the licence? Is there a way of just removing the licence without uninstallation?
It's Visual Studio 2010 Professional edition, installed on a Windows XP computer.
A: MSDNAA FAQ:
Q: Does the license (or "key") permanently unlock the software?
A: No - the key allows you to install the software once. If you need to re-install the software, you will need to contact the PA (Program Administrator) at your school. Your PA's contact email information can be found in the support page. To view this information, please click on the Support button above.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
} |
Q: Applying .gitignore to committed files I have committed loads of files that I now want to ignore. How can I tell git to now ignore these files from future commits?
EDIT: I do want to remove them from the repository too. They are files created after ever build or for user-specific tooling support.
A: After editing .gitignore to match the ignored files, you can do git ls-files -ci --exclude-standard to see the files that are included in the exclude lists; you can then do
*
*Linux/MacOS: git ls-files -ci --exclude-standard -z | xargs -0 git rm --cached
*Windows (PowerShell): git ls-files -ci --exclude-standard | % { git rm --cached "$_" }
*Windows (cmd.exe): for /F "tokens=*" %a in ('git ls-files -ci --exclude-standard') do @git rm --cached "%a"
to remove them from the repository (without deleting them from disk).
Edit: You can also add this as an alias in your .gitconfig file so you can run it anytime you like. Just add the following line under the [alias] section (modify as needed for Windows or Mac):
apply-gitignore = !git ls-files -ci --exclude-standard -z | xargs -0 git rm --cached
(The -r flag in xargs prevents git rm from running on an empty result and printing out its usage message, but may only be supported by GNU findutils. Other versions of xargs may or may not have a similar option.)
Now you can just type git apply-gitignore in your repo, and it'll do the work for you!
A: *
*Edit .gitignore to match the file you want to ignore
*git rm --cached /path/to/file
See also:
*
*How do I git rm a file without deleting it from disk?
*Remove a file from a Git repository without deleting it from the local filesystem
*Ignoring a directory from a Git repo after it's been added
A: *
*Add your filename/file-path into the .gitignore file.
*Now run command in git bash git rm --cached file/path/from/root/folder
*Now commit your code using git commit.
Now the file should not get tracked in the git status command.
A: to leave the file in the repo but ignore future changes to it:
git update-index --assume-unchanged <file>
and to undo this:
git update-index --no-assume-unchanged <file>
to find out which files have been set this way:
git ls-files -v|grep '^h'
credit for the original answer to
http://blog.pagebakers.nl/2009/01/29/git-ignoring-changes-in-tracked-files/
A: Be sure that your actual repo is the latest version and without ongoing changes
*
*Edit .gitignore as you wish
*git rm -r --cached . (remove all files)
*git add . (re-add all files according to gitignore)
then commit as usual
A: Old question, but some of us are in git-posh (powershell). This is the solution for that:
git ls-files -ci --exclude-standard | foreach { git rm --cached $_ }
A: I tend to forget / am too lazy to read what these git commands do. So I do it like this:
*
*I move all files, which I want to ignore, temporarily outside the repository
*I commit these "deleted files" in my git GUI (they are now untracked)
*I update the .gitignore file
*I move the files back into the repository (or delete them, if that was my intention)
A: İf you already committed, you can use this:
*
*Add folder path to .gitignore file.
*Run this command for removing exe (for another file extensions, just write "*extension") files.
git rm --cached *exe
*Commit changes.
You should do this for every extension that you wanted to remove.
A: After editing .gitignore file.
git rm -r --cached ./ && git add ./ && git commit -a -m "Removing ignored files" && git push
A: Follow these steps:
*
*Add path to gitignore file
*Run this command
git rm -r --cached foldername
*commit changes as usually.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "580"
} |
Q: HTML table that uses rowspan and colspan gets overlapped by the next element I am designing a very simple table that contains a data element's properties. This element will be used to represent each element of a AJAX response in a kind of list.
The table is using "rowspan" and "colspan" to enlarge some cells. The problem, is that when I add an element below, this element overlaps the table, I don't know why. The HTML is valid, and the rowspan attributes indicate the exact amount of rows to merge.
I have deployed an example here: http://jsfiddle.net/vtortola/KzjKg/9/
As you can see, the green block overlaps the table, and that is the thing I want to avoid.
Any idea why is this happening?
Cheers.
A: You've attributed max-height:50px; to the div which contains the table. Remove this CSS declaration, and the table won't be overlapped any more.
A: I think the problem:
1) You maybe remove the max-height where your table is more than 50px.
div.mobileRow{
width:100%;
font-family:Arial;
margin:5px;}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527984",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: X-Cart stopped working, it seems like it goes somewhere and never comes back I am facing a very strange issue in X-Cart, I am working on localhost. It was working fine and now it is not working anymore. It shows nothing but a blank page, it seems like it goes somewhere and then doesn't come back.
We installed another X-Cart on localhost and it worked fine. I am just doing theming, client will purchase license. So is it because of some sort of licensing problem? That it works for some time and then stops working?
I tried to debug and seems like problem is in sessions.php file in include directory. It seems like statement creating problem is x_session_start().
A: If your seeing a blank page it's probably because there's been an error and you have error reporting disabled.
You can enable it by putting this code on the first line of the script...
ini_set('display_errors', 1);
error_reporting(E_ALL);
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527988",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: How can I log progress of multiple sql queries in a single JdbcTemplate execute() and PostgreSQL I have a SQL script with many statements which I execute using JdbcTemplate.execute(). Some queries are slow and I'd like to write progress of the whole script to the logs.
As it stands, I only get logs written once all the statements have completed.
A: There is another way to get what you want. Use the PostgreSQL server log. Set the options in the config file postgresql.conf and reload, or set parameters per session like this:
Log every single SQL statement:
set log_statement = 'all';
Or hunt for slow queries in particular, for example: everything that takes longer than 1000 ms:
set log_min_duration_statement = 1000;
The manual about logging-parameters:
log_statement (enum)
Controls which SQL statements are logged. Valid values are none (off), ddl, mod, and all (all statements).
If you log everything remember to turn it off afterwards or the log files may grow huge.
log_min_duration_statement (integer)
Causes the duration of each completed statement to be logged if the statement ran for at least the specified number of milliseconds. Setting this to zero prints all statement durations. (...)
The manual on how to set parameters.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527989",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: Calling Objective-C class from basic C, xcode project I am try to implement an cocoa application For USB Detection. Whenever user connects the USB it automatically detected, this entire part is one C program (Normal C) is orking Fine.
My need is if the system detects a particular USB device, I want to call another application (i.e. another cocoa application) using system function. I open that application, but my problem is if the user removes that USB device (this is also detected in C program), I want to close the second application automatically.
Or, if I add a cocoa user interface/objective-c class in the first application, is it possible to call that class from inside the C program?
A: One class you could use for this is NSDistributedNotificationCenter. Your C program would need to post notifications and your other program(s) would subscribe to them. The scenario would go like this:
*
*Second App: on launch register to receive "USB Device Removed" messages
*C Program: dectect removed USB device
*C Program: post notification "USB Device Removed"
*Second App: receives notification "USB Device Removed"
*Second App: quits itself
Of course your C program would now become an objective-c program. There is also C alternative, which is CFNotificationCenterGetDistributedCenter.
A: If the object already exists and you can pass a pointer to it, you can use the Objective-C runtime function objc_msgSend. For example:
#include <objc/runtime.h>
#include <objc/message.h>
void sendDoneToApp(id app)
{
/* [app done]; */
/* get selector for "done" */
SEL doneSel = sel_registerName("done");
/* cast objc_msgSend to the type we need */
void (*sendNoArgsNoRet)(id obj, SEL selector) = (void (*)(id, SEL))objc_msgSend;
/* send the message */
sendNoArgsNoRet(app, doneSel);
}
A: Yes it is possible. You could for example look at how libdispatch/Grand Central Dispatch manages this.
The basic idea is to pass C function-pointers + void-pointers to your C library. And then in the passed function you can call Obj-C functions. Example:
struct test_s {
NSString *my_string;
};
void my_function(void *data) {
struct test_s *context = data;
NSLog(@"%@", [@"Hello " stringByAppendingString:context->my_string];
}
void main(void) {
struct test_s context = { @"World!" };
/* dispatch_sync_f is a C function unaware of Obj-C */
dispatch_sync_f(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0),
&context,
my_function);
}
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527992",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
} |
Q: What does the dollar sign mean in PHP? What does the dollar sign mean in PHP? I have this code:
<?php
class Building {
public $number_of_floors = 5;
private $color;
public function __construct($paint) {
$this->color = $paint;
}
public function describe() {
printf('This building has %d floors. It is %s in color.',
$this->number_of_floors,
$this->color
);
}
}
$bldgA = new Building('red');
$bldgA->describe();
?>
It seems that the $ indicates a variable like:
$number_of_floors
$color
But I get confused when I see the following:
$bldgA->describe();
$bldgA->number_of_floors;
Why are there no dollar signs before these variables?
A: $ is the way to refer to variables in PHP. Variables in PHP are dynamically typed, which means that their type is determined by what's assigned to them. Here's the page about variables from the PHP manual.
$a = "This is a string";
$b = 1; // This is an int
$bldgA = new Building('red'); // bldgA is a variable and an object (aka an instance) of class Building.
$bldgA->describe(); // This calls describe(), which is a member function of class Building (remember that $bldgA was declared as being an object of class Building)
$bldgA->number_of_floors; // number_of_floors is a data member of class Building. You can think of it as a variable inside a class, but since it's part of the class with a fixed name, you don't refer to it with $.
A: $bldgA = new Building('red');
in this case $bldgA is an object.
$bldgA->describe();
calls the function describe() from the object $bldgA
$bldgA->number_of_floors;
acces the variable number_of_floors from the object $bldgA
but you should really take a look at php.net/manual/en/language.oop5.basic.php
A: You are right, the $ is for variable. But in a class instance, you don't use $ anymore on properties because PHP would interpret and this can cause you an error. For example, if you use
$bldgA->$number_of_floors;
this will not return the $number_of_floors property of the object but PHP will first look at the value of $number_of_floors, let's say 3 for instance, so the previous line would be
$bldgA->3;
And that will give you an error
A: Yes, that's variable with assigned instance of class to it. And when it object then youre calling/getting arguments like so. Read about OOP in PHP, please. It could be very handy for You and help you understand how it works :)
A: The $bldgA is a variable for the class Building
so you can access the class function by using $Building->function_name
example:
$foo = $bldgA->describe();
the $number_of_floors is a variable inside the class
A: $bldgA->number_of_floors; Does not call a local variable but a property (it's like a local variable part of the class definition) of a class.
However it is possible to call $bldgA->$property_name;where $property_name is a name of the property you want to call. This is called variable variables and something you probably should look into after you've grasped OOP basics.
A: When writing $bldgA = new Building('red'); you assign the variable $bldgA a newly created object of class Building. Objects are a possible type of variables.
In general when you see $ it always refers to variables. $bldgA->number_of_floors; should be read as: access the property of the object in variable $bldgA
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7527999",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
} |
Q: handling line breaks in primefaces textarea submitted value I have a primefaces textarea. User simply enters multiple lines in it and submits the form. In my backing bean, value is split at line-breaks. Each line is validated. The valid lines are removed from the string and invalid lines are kept, and again sent to the user.
Split code:
StringTokenizer tokens=new StringTokenizer(value,"\n\r");
Re-fill value with invalid lines:
valueStrBldr.append(invalidLine).append("\n\r");
The problem is that when value is reloaded to text area it has a lot of unwanted line breaks and empty lines. Does it have to do something with platform dependent line breaks?
When I remove \r , the problem is solved, but then the value is not split correctly -- I mean why inconsistency?
A: I suggest to use BufferedReader#readLine() instead to read lines on linebreaks. This covers all possible platform specific linebreaks such as \r\n, \r and \n without that you need to worry about (please note that \n\r is not a valid linebreak sequence).
BufferedReader reader = new BufferedReader(new StringReader(value));
String line = null;
while ((line = reader.readLine()) != null) {
// ...
}
When writing lines, I suggest to use \r\n. It should work fine in all clients (webbrowsers).
valueStrBldr.append(invalidLine).append("\r\n");
A: I think it should be '\r\n' (reversed order). If I remember it right \r is the end of a line, and \n is a new line.
anyway, try just printing out the ascii code of the input, and look at it. try recognizing the pattern. This sound brute force, but you will see that after 3-4 lines you have an idea of what is happening.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7528001",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
} |
Q: MSSQL 2008 R2 Selecting rows withing certain range - Paging - What is the best way Currently this sql query is able to select between the rows i have determined. But are there any better approach for this ?
select * from (select *, ROW_NUMBER() over (order by Id desc) as RowId
from tblUsersMessages ) dt
where RowId between 10 and 25
A: Depends on your indexes.
Sometimes this can be better
SELECT *
FROM tblUsersMessages
WHERE Id IN (SELECT Id
FROM (select Id,
ROW_NUMBER() over (order by Id desc) as RowId
from tblUsersMessages) dt
WHERE RowId between 10 and 25)
If a narrower index exists that can be used to quickly find the Id values within the range. See my answer here for an example that demonstrates the type of issue that can arise.
You need to check the execution plans and output of SET STATISTICS IO ON for your specific case.
| {
"language": "en",
"url": "https://stackoverflow.com/questions/7528003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.