Year: 2009
Number of Unanswered Questions With Comment: 7042
Sampled Questions List: 100

Id: 2799332
title: Building a document server
tags: sql, xcode, osx, webserver
view_count: 35
body:

Hey, I'm just looking for some rough guidance here on the feasibility of a project.

I have say a few thousand text documents and I want to create a web based system to serve them up to users in a OS X application.

It's just a tiny aside for my family's small business, so it doesn't need to be amazing at the moment, we just want to see if we can can anyone to use it.

I can't believe it can be that hard to do this?

-Some sort of SQL backend database to manage permissions for users?

-Download through the application?

-For the moment just want to view the raw text files.

-If we want people to pay, how would we go about incorporating that?

Sorry for the vague outline. I'm still not 100% sure on what we want.

Thanks for any help.

comments:

1 : You want to read about SOLR: http://lucene.apache.org/solr/

2 : I don't understand why you don't just make it a purely web-based application. Why do you want to wrap it in a dedicated Mac OS X front end?

3 : OMG Ponies: Thanks, I shall check it out. Rob Kengier: It has to be able to be used at offline (building sites) and from a cold start laptop. We also sort of felt the people using it would be more comfortable with an app. If we ignore the comfort factor, could it work as a web app from HTML5 from a cold start? Sorry I'm not that familiar with HTML5.


---------------------------------------------------------------------------------------------------------------
Id: 3077656
title: What is the PHP syntax for launching an ssh connection in the background?
tags: php, background, exec
view_count: 82
body:

I need to launch an ssh shell to a remote server for remote port forwarding in the background from a PHP script using the exec() function.

The command when run in the background is $execStr, so I use exec($execStr ." > /dev/null &"); $execStr works fine manually, but not in the script.

What is the correct syntax?

Here is the rogue program.

#!/usr/bin/php
<?php
/* 
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
 $handle = fopen('accountno', 'r');
 if ($handle) {
   $accountNo = fgets($handle);
   $acc = substr($accountNo, 4, 4);
   $execStr = "ssh -R $acc"."1:localhost:22 -R $acc"."2:localhost:5432  -R $acc"."3:localhost:10000   -i ~/remoteAdmin.key ht$acc@domain.net";

   print("$execStr\n");
   $pid = exec("$execStr > /dev/null &");

   $pidHandle = fopen("rempid","w");
   fwrite($pidHandle, $pid);
   fclose($pidHandle);
   echo "program got to the end\n";
 }
?>
comments:

1 : That is the correct syntax. Are you getting an error, or is it just blocking on the `exec` call?

2 : @Michael - I am not quite sure what you mean - Do you mean if the exec causes php to hang? PHP returns okay.

3 : You don't specify what's going wrong. Are you getting an error message?

4 : I have managed to get it to work by using the -N option to the ssh command. Not sure if there is a PHP syntax which will work without the -N


---------------------------------------------------------------------------------------------------------------
Id: 3289245
title: Application not loading when deploying on production and running in IE6
tags: grails, browser
view_count: 28
body:

My application is using grail . locally on all browser it is running . but on production in IE6 and firefox 1.5x it is not loading . I am not finding why it is behaving like this way?

comments:

1 : if you add details, such as the error message (if any), how you're connecting, and screenshots, it might be possible to help diagnose your problem.

2 : Yes, more details are required before we can help you.


---------------------------------------------------------------------------------------------------------------
Id: 2840372
title: task_current redundant field
tags: linux-kernel, kernel-programming, kernel-module
view_count: 76
body:

I'm writing a kernel module that reads from a /proc file. When someone writes into the /proc file the reader will read it, but if it reads again while there is no "new" write, it should be blocked. In order to remember if we already read, i need to keep a map of the latest buffer that process read.

To avoid that, I was told that there might be some redundant field inside the current-> (task_struct struct) that i can use to my benefits in order to save some states on the current process.

How can I find such fields ? and how can i avoid them being overwritten ? I read somewhere that i can use the offset field inside the struct in order to save my information there and i need to block lseek operations so that field will stay untouched.

How can I do so ? and where is that offset field, i can't find it inside the task_Struct.

Thanks

and I need to save for each process some information in order to map it against other information.

I can write a ma

comments:

1 : Why can't you add a new field to struct task_struct? Also, why aren't you using existing mechanisms to do this with /proc instead of inventing a new one? For example, use inotify with /proc.


---------------------------------------------------------------------------------------------------------------
Id: 2626148
title: Subsonic 3.0.0.4 Does not Update
tags: linq-to-sql, sql-server-2008, update, subsonic3, subsonic-active-record
view_count: 156
body:

I tried 3 variants but doesn't seem to update (I am using Linq Templates and MSSQL)

    Luna.Data.GameDBDB db = new Luna.Data.GameDBDB(); 
    db.Update<Luna.Record.TB_ITEM>()
        .Set(x => x.ITEM_DURABILITY == Convert.ToInt32(quantity))
        .Where(x => x.ITEM_DBIDX == Convert.ToInt32(dbdidx))
        .Execute();

Here is the other one

var db = new Luna.Data.GameDBDB();
var query = (from p in db.TB_ITEMS where p.ITEM_DBIDX == Convert.ToInt32(dbidx) select p).Single();
query.ITEM_DURABILITY = Convert.ToInt32(quantity);
db.tp TP_ITEM_UPDATE();

and the other one

var db = new Luna.Data.GameDBDB();
var query = (from p in db.TB_ITEMS where p.ITEM_DBIDX == Convert.ToInt32(dbidx) select p).Single();
query.ITEM_DURABILITY = Convert.ToInt32(quantity);
db.Update<Luna.Data.TB_ITEM>();

However it worked using LINQ-to-SQL

            LunaDataContext db = new LunaDataContext();
            var query = (from p in db.TB_ITEMs
                         where p.ITEM_DBIDX == Convert.ToInt32(dbidx)
                         select p).Single();
            query.ITEM_DURABILITY = Convert.ToInt32(quantity);
            db.SubmitChanges();

Is this a bug in 3.0.0.4, the database record couldn't be updated using Linq Templates and ActiveRecord.

comments:

1 : NOTE: second snippet ends with ->> db.TP_ITEM_UPDATE();


---------------------------------------------------------------------------------------------------------------
Id: 2710434
title: How to pass parameters to Apache Pivot's wtkx:include tag?
tags: java, xml, apache-pivot
view_count: 256
body:

I need to create a reusable UI component that accepts a number of parameters (e.g. an image URL and some label text), similar to how JSP tags can accept parameters. The Pivot docs for the "wtkx:include" tag say:

The tag allows a WTKX file to embed content defined in an external WTKX file as if it was defined in the source file itself. This is useful for ... defining reusable content templates

I was hoping that I could define my component in a WTKX file using standard Pivot components (e.g. a TextInput) and pass it one or more parameters; for example my reusable template called "row.wtkx" might contain a row with an image and a text field, like this (where the ${xxx} bits are the parameters):

<TablePane.Row xmlns="org.apache.pivot.wtk">
    <ImageView image="@images/${image_url}" />
    <TextInput text="${title}" />
</TablePane.Row>

I could then reuse this component within a TablePane as follows:

<rows>
    <TablePane.Row>
        <Label text="Painting"/>
        <Label text="Title"/>
    </TablePane.Row>
    <wtkx:include src="row.wtkx" image_url="mona_lisa.jpg" title="Mona Lisa"/>
    <wtkx:include src="row.wtkx" image_url="pearl_earring.jpg" title="Girl with a Pearl Earring"/>
    <wtkx:include src="row.wtkx" image_url="melting_clocks.jpg" title="Melting Clocks"/>
</rows>

I've made up the ${...} syntax myself just to show what I'm trying to do. Also, there could be other ways to pass the parameter values other than using attributes of the "wtkx:include" tag itself, e.g. pass a JSON-style map called say "args".

The ability to pass parameters like this would make the include tag much more powerful, e.g. in my case allow me to eliminate a lot of duplication between the table row declarations.

Or is "wtkx:include" not the right way to be doing this?

comments:

1 : I thought of subclassing org.apache.pivot.wtk.TablePane.Row, but it's final. Also it would mean splitting my UI definition between XML and Java, which is starting to get messy.

2 : Greg Wilkins tells me that TablePane.Row is no longer final as of version 1.5.


---------------------------------------------------------------------------------------------------------------
Id: 2749182
title: Generating 2 random images from an array
tags: c#, silverlight, image, generate
view_count: 222
body:

I am writing a Silverlight application. How do I generate 2 pictures from an array of images and display it on my screen?

This is what I have now.

private void PopulateCards(object sender, RoutedEventArgs e)
{
    List<string> Level2 = new List<string> { "1", "2", "3" };

    List<string> randomizedImageList = GetRandomList(Level2);

    for (int i = 0; i < randomizedImageList.Count; i++)
    {
        Picture currentCard = PictureGrid.Children[i] as Picture;
        currentCard.MouseLeftButtonUp += new MouseButtonEventHandler(CardClicked);
        currentCard.Tag = randomizedImageList[i];          
        currentCard.photo.Source = new BitmapImage(new Uri("/LogIn;Component/Image/" + randomizedImageList[i] + ".jpg", UriKind.Relative));
    }
} 
comments:

1 : What exactly are you having trouble with? Choosing two pictures at random from an array? Or displaying a picture on the screen? What technologies are you using? WinForms? WPF? What have you tried? Why didn't that work? Post your code.

2 : @boyboy: I've edited the question to add the information from your "answer". But you still need to explain what you don't understand and why what you have tried doesn't work.


---------------------------------------------------------------------------------------------------------------
Id: 1357915
title: Does ItemsTemplate+DataTemplate obscure bindings?
tags: wpf, templates, binding
view_count: 169
body:

At several points in my current application, I have an ItemTemplate such as the following:

<ItemsControl.ItemsPanel>
        <ItemsPanelTemplate>
            <StackPanel Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </ItemsControl.ItemsPanel>
    <ItemsControl.ItemTemplate>
        <DataTemplate>
        <ToggleButton  Margin="2,0" Content="{Binding}" Tag="{Binding}"  Click="ToggleButton_Click">
            <ToggleButton.IsChecked>

                <MultiBinding Mode="OneWay" Converter="{StaticResource EqualityConverter}">
                    <Binding RelativeSource="{RelativeSource Self}" Path="Tag">
                    </Binding>
                    <Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type cc:ToggleButtonPanel}}" Path="SelectedItem">
                    </Binding>
                </MultiBinding>
            </ToggleButton.IsChecked>
        </ToggleButton>
    </DataTemplate>
    </ItemsControl.ItemTemplate>

Now, I've stepped through the converter and it returns true and false as expected, but the controls do not change their ischecked state... There are no binding errors, and this only happens when using an ItemsTemplate/DataTemplate combo. Has anyone else seen this behaviour?

comments:

1 : Hey there. Based on what you provided it's hard to tell where is the problem and what's the cause. Could you create a minimal compilable example to reproduce the issue you have? Just a side question: what are you trying to achieve? Provided xaml-code looks little awkward to me.

2 : What I'm trying to accomplist is have a list of objects given to a itemscontrol, and have each represented by a generic usercontrol. I inherited this code. This same datatemplate code appears in several places, and I've been retrofitting it all with DependencyProperties that are lists, but there are some cases where the data template would be perfect if it would work. Thanks


---------------------------------------------------------------------------------------------------------------
Id: 3246646
title: Sending XML data from iPhone client to Web Server
tags: iphone, xml, webserver
view_count: 287
body:

I'm looking to keep a high score table for my application in XML format. All I am looking to send is a timestamp, string ID, and value.

So my questions are do I have to create anything to receive the data, or can I simply have the app write out to a hosted XML file? If not can I write out new XML files for each message (and compile them server side)?

Thanks!

comments:

1 : Do you want to send the xml directly or do you want to upload an xml file? The former is more common.

2 : I would like to just append any new data to an already existing XML file on the webserver. If all else fails I can just go with plain text as well.


---------------------------------------------------------------------------------------------------------------
Id: 3011523
title: IE: iframe w/ invalid url and floating divs
tags: html, iframe, internet-explorer
view_count: 132
body:

I've encountered a very interesting issue with IE + iframes + invalid urls + floating divs.

I have a floating div (well not floating with css 'float' but floating as in a higher z-index). This floating div shows over the top of the iframe. However when we try to load an invalid url in the iframe then the iframe gets shown ontop of the div.

I think the best way to explain is with an example:

<html>
    <head>
        <style>
#floater {
    z-index:3;
    position:absolute;
    left:550px;
    top:100px;     
    width:477px;
    border:solid 3px blue;
}
        </style>
    </head>
    <body>
        <div id='container' style='position:relative;'>
            <!-- Change to valid url to see how this should work -->
            <iframe src='http://www.google.invalid' width='600px' height='600px'></iframe>
            <div id='floater'>FLOATER</div>
        </div>
    </body>
</html>

Has anyone ever encountered this piece of IE magic before? Any suggestions? Thanks All

Guido

comments:

1 : I'm not able to reproduce your error.

2 : Wow, so you see the floating div over the top even if the url is invalid??

3 : I've done some more testing given edl's comment above. Tried this on 5 machines (xp 32 and 64 bit and win 7) and it works on all except my dev box (xp64). Who knows what the hell is up with that.


---------------------------------------------------------------------------------------------------------------
Id: 3019513
title: 8 bit music type can play in Assembler 16 bit PC?
tags: assembly, x86
view_count: 108
body:

Possible Duplicate:
Building a music player with assembly

If it's avilable, how i can do that? OS:Windos. Sorry on the bad English..

comments:

1 : Huh? The last version of 16-bit Windows was Windows 3.x, is this what you really mean?

2 : I do the project in tasm and i want to do that in 16 bit in Assembler..

3 : What you mean in Windos 3.x ?


---------------------------------------------------------------------------------------------------------------
Id: 2744098
title: XML Parsing C++
tags: c++, xml, parsing
view_count: 186
body:

I am using MSXML2 for XML Parsing. I am using IXMLDOMNodePrtr , IXMLDOMDocumentPtr ans so on for XML Parsing. I have observed that while my application ends Private Bytes usage of EXE is say 30 MB and it keep on reducing. Previously i was thinking that their might be some memory leaks there. I have different tolls for the same and fix all the issues which i have found.

I want to ask is there any Garbage Collection mechanism implemented by Microsoft for the same, Because my application Private byte usage keeps on decreasing.

Thanks in advance.

Anjan

comments:

1 : Accept some answers.

2 : Hello All, Please let me know if the answer of the above question is yes. Thanks in advance. Anjan


---------------------------------------------------------------------------------------------------------------
Id: 2996665
title: Internet Explorer cannot 'fully' load ActiveX Control
tags: c++, internet-explorer, com, activex, registry
view_count: 481
body:

Context

I am migrating an installer for an ActiveX control from Per-Machine to Per-User. I did this by programming the installer write to HKCU\Software\Classes instead of HKLM\Software\Classes.

Problem

On my machine (Windows 7 with UAC Enabled), the ActiveX control successfully loads. On the other windows 7 test machines (one with UAC enabled, one with UAC disabled), the control 'partially' loads.

What is Partially?

When a user visits a page with the ActiveX control, Internet Explorer displays a warning message in a yellow bar on the top of the window. If you click the 'Run add-on' button in the bar, the control becomes visible and begins to run, but Javascript code that tries to access properties of the control return the error: Library not registered.

Differences between machines

On the dev machine reads from HKCR\CLSID\<GUID> succeed while on the test machines these reads fail. Reads from HKCU succeed on both dev and test machines. Reads from HKLM fail on both test and dev machines. (I collected reads using Sysinternals Process Monitor) Strangely, the keys that Internet Explorer fails to read are clearly visible if I use regedit to view HKCR\CLSID\<GUID> on the test machines.

Question

What can I do to get the per-user control to load on the test machines? What could cause this difference between the dev machine and the test machines? Why can I see the key in HKCR with RegEdit but Internet Explorer cannot see the key?

Any help is appreciated. Thank you.

comments:

1 : Have you tried manually to install it i.e. not using IE but physically copying the dll to the machine and then register it? ( Just to see if it has to do with rights )

2 : manually registering with regsvr32.exe /i MyLib.dll seems to work if i use an admin command prompt. (i think regsvr32.exe writes to HKLM)


---------------------------------------------------------------------------------------------------------------
Id: 2834597
title: How to open webpage in HIDDEN default browser? DELPHI
tags: delphi, webbrowser, hidden, shellexecute
view_count: 889
body:

I have been trying to open a hidden default browser from delphi but coulnd't.

I tried

ShellExecute(self.WindowHandle,'open','www.google.com',nil,nil, SW_HIDE);

and I get my chrome browser open but not hidden, and it opens a tab not a new window, also tried with TStartupInfo with the same results. Is there another way to achieve this?

comments:

1 : Nothing that's guaranteed to work. At the least, any browser that opens new URLs as tabs will ignore TStartupInfo. Why would you even want to do this?

2 : why do you care?

3 : Two reasons. 1, because the more information we have about what you're trying to do, the better answers we can give. 2, because trying to open a webpage and hide it from the user sounds kinda suspicious, and we're honorable coders here who don't want to help anyone write malware. So please convince us you've got some legitimate reason to want to do this, or you're not likely to get any answers.

4 : +1 @Mason. Same thoughts I had.


---------------------------------------------------------------------------------------------------------------
Id: 3271499
title: make a rails plug-in
tags: plugins
view_count: 12
body:

I want to make a rails plug-in they have small and useful please suggest the topic

comments:

1 : you mean a gem? and who has small and useful?


---------------------------------------------------------------------------------------------------------------
Id: 3015590
title: windows media player command arguments
tags: windows-mobile, mediaplayer, windows-media-player
view_count: 125
body:

Is it possible to launch a mp3 or wmv file using windows media player at a specified time offset? e.g I watched 10 seconds of video and closed it. the next time my app launches the video it starts playing a timeline of 10 seconds. The videos and mp3s are being launched in windows mobile 5 and 6 apps.

comments:

1 : This might be ultimately used in a program, but the specifics of the question itself are more appropriate for superuser.com


---------------------------------------------------------------------------------------------------------------
Id: 2842436
title: Ruby Mechanize - Basic Get Failing
tags: ruby, mechanize
view_count: 274
body:

a = WWW::Mechanize.new { |agent| agent.user_agent_alias = 'Mac Safari' agent.history.max_size=0 }

page = a.get('http://livingsocial.com/deals?preferred_city=18')

Trying a very basic GET request using mechanize but get a 500, yet when I CURL I have no problems. Is there a problem with including parameters in a get() call? I know I am missing something simple

comments:

1 : Works fine on my computer. Mac OS X 10.6.3, ruby 1.8.7, Mechanize 1.0

2 : 10.6.3, 1.8.7, but using mech 0.8.5 (pre nokugirl) because deployment platform is app engine.

3 : Using mech 0.8.5 i can't execute the first line. "uninitialized constant WWW". Anything special with that version?

4 : Try sniffing network packets to see what's being sent and received (yes, that is the only thing I know how to say!)


---------------------------------------------------------------------------------------------------------------
Id: 2780544
title: How can i do the same thing with Gallery in Android
tags: android, gallery
view_count: 925
body:

I am navigating images with the clicks of next and previous buttons.Here is my code:

package com.myapps.imagegallery;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class ImageGallery extends Activity {
    /** Called when the activity is first created. */

    int imgs[] = {R.drawable.bluehills,R.drawable.lilies,R.drawable.sunset,R.drawable.winter};
    String desc[] = {"Blue Hills", "Lillies", "Sunset", "Winter" };
    int counter=0;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        final ImageView imgView = (ImageView)findViewById(R.id.ImageView01);
        imgView.setImageResource(imgs[counter]);

        final TextView tvDesc = (TextView)findViewById(R.id.tvDesc);

        Button btnNext = (Button)findViewById(R.id.btnNext);
        btnNext.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View arg0) {
                try{
                // TODO Auto-generated method stub
                if (counter < desc.length -1)   
                counter++;
                imgView.setImageResource(imgs[counter]);
                tvDesc.setText(desc[counter]);
                }catch(Exception e)
                {
                    Toast.makeText(ImageGallery.this, e.toString(), Toast.LENGTH_SHORT).show();
                }

            }


        });


        Button btnPrev = (Button)findViewById(R.id.btnPre);
        btnPrev.setOnClickListener(new View.OnClickListener(){

            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub

                try{
                    // TODO Auto-generated method stub
                    if (counter > 0)
                    counter--;
                    imgView.setImageResource(imgs[counter]);
                    tvDesc.setText(desc[counter]);
                    }catch(Exception e)
                    {
                        Toast.makeText(ImageGallery.this, e.toString(), Toast.LENGTH_SHORT).show();
                    }           

            }});

    }
}

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >

<ImageView 
android:id="@+id/ImageView01"
android:layout_x="70dip" 
android:layout_width="200px" 
android:layout_height="200px" 
android:layout_y="90dip"

>
</ImageView>    


<TextView 
    android:id="@+id/tvDesc" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    android:layout_x="90px"
    android:layout_y="300px"
    />



<Button 
android:layout_x="47dip" 
android:layout_height="wrap_content" 
android:text="Previous" 
android:layout_width="100px" 
android:id="@+id/btnPre" 
android:layout_y="341dip">
</Button>

<Button 
android:layout_x="190dip" 
android:layout_height="wrap_content" 
android:text="Next" 
android:layout_width="100px" 
android:id="@+id/btnNext" 
android:layout_y="341dip">
</Button>

</AbsoluteLayout>
comments:

1 : Thanks for this post, i have a doubt, In this code we give the images a static, in case i include parsing concept, that means i parsed set of images from a certain link how can i modify this, please clarify this doubt.

2 : take the hint, dude, you need to start tagging your questions with `android`


---------------------------------------------------------------------------------------------------------------
Id: 2195176
title: How do I use an NSProgressIndicator as the view of an NSToolbarItem and have it show in the customisation sheet?
tags: cocoa, osx, nstoolbar, nsprogressindicator, nstoolbaritem
view_count: 592
body:

I have an NSToolbar set up in my app. It was created in IB. One of the toolbar items uses a spinner-style NSProgressIndicator as its view, the rest are images.

When the toolbar's customization sheet is showing, the spinner does not show in the sheet.

I initially thought that this was because the spinner's -displayedWhenStopped was set to NO. That's not the case: if I set it to YES, the spinner shows in the toolbar when active, but doesn't show in either the toolbar or the sheet when stopped.

comments:

1 : @Fraser: Do you have any code you could post for setting up the progress indicator besides what you've done in IB? I can't reproduce it, like the fellow commentors before me.

2 : IIRC, the toolbar item in the customization sheet is actually just an archived object. When it's dragged off the sheet to an actual toolbar at runtime, a new object is created based on the archive. Thus, the item in the toolbar and on the customization sheet are not the same. Make sure in *IB* that the properties for the item on the customization panel are correct to enable the spinner to display always.

3 : I definitely can't reproduce this ? if displayedWhenStopped is true, it's displayed in both places whether active or inactive. The only thing I can think of is it's being programmatically hidden when inactive, but I know you'd know the effect that would have...

4 : I concur with Brock, I can't reproduce it either, it works fine for me.


---------------------------------------------------------------------------------------------------------------
Id: 2051308
title: Hibernate resolve foreign key lookup id by name
tags: java, hibernate, orm
view_count: 379
body:

I'm in the process of writing a module for an application that bulk imports data. I'm using Hibernate version 3 for data access. I receive a flat table of data let's call it products for simplicity and assume this data layout:

Name, category, sub-category
foo,   main1,  sub11

The category and sub-category fields actually refer to the lookupName column in different lookup tables, and the products table that i'm trying to insert to stores the corresponding id's from each respective lookup table, the database equivalent record or finished result for the input above one looks like this:

Name, category, sub-category
foo,   1,  5

// to get 1 and 5 lookup id's
    String hql = "from Lookup where name = :name";
    String[] paramName = new String[]{"name"};
    String[] paramValue = new String[]{"foo"};
    List<Product> products = (List<Lookup>)this.getHibernateTemplate().findByNamedParam(hql, paramName, paramValue);

My question is when working with Hibernate is to get the lookup id 1 and 5 above is my only option to run a separate query for each lookup before I can insert the product row above? I'm wondering if there is some syntactic sugar where I could supply the lookup name to my product entity and Hibernate will resolve this dynamically just before insert, possible?

comments:

1 : Hmmm... can you rephrase the last paragraph? :)

2 : Is that better?

3 : I believe he is asking if he can insert into a products table without having to lookup the category & sub-category. He would rather insert and just give string names for cat, sub-cat and have Hibernate lookup those object. Please tell me if I am wrong and I will remove comment.

4 : That is what i'm looking for...


---------------------------------------------------------------------------------------------------------------
Id: 3345190
title: Excel formatting
tags: excel
view_count: 73
body:

I have a column of IDs that I am concatenating in order to pass the list as a parameter to an SQL connection.

The stored procedure uses the parameter buried inside some dynamic SQL, so the formatting I need is odd.

Here is the value I am trying to pass:

'''007','011','017','020','025','030','031','037','046','047','051','055','066','067','079','089','097','110','111','120','157','169','174','196','206','217','232','238','263','264','265','272','280','314','315','337','342','363','366','385','386','387','410','417','432','434','446','486','488','490','499','510','520','533','535','547','578','593','596','598','609','620','622','653','654','671','676','685','700','701','712','718','724','726','735','749','757','761','762','769','772','781','833','834','841','853','854','858','908','911','928','953','962','983','996','997','A12','A14','A46','A49','A59','A81','A84','A86','B01','B06','B13','B17','B27','B28','B42','B63','B98','C09','C24','C26','C46','C51','C52','C53','C66','C70','C72','C96','D03','D19','D20','D24','D31','D45','D54','D56','D58','D62','D64','D65','D67','D71','D73','D76','D78','D81','D87','D99','E01','E04','E17','E20','E24','E34','E38','E39','E54','E55','E56','E57','E72','E73','E83','E97','E99','F05','F07','F13','F19','F21','F25','F30','F37','F39','F43','F44','F45','F50','F62','F63','F66','F72','F78','F82','F84','F87','F88','F91','F97','G02','G03','G08','G10','G14','G17','G21','G30','G36','G37','G38','G39','G44','G48','G49','G50','G55','G60','G65','G68','G72','G77','G79','G92','G93','G94','G95','H16','H27','H28','H29','H34','H38','H39','H47','H50','H64','H65','H72','H93','H96','I02','I20','I22','I23','I30','I31','I32','I33'''

The problem is that the query tool wants this value as text but excel sees it as a number? If I convert the field to text, all I get is #########.

Is there an easy way to work around this?

comments:

1 : Is this for XL3003? "Only 1,024 display in a cell; all 32,767 display in the formula bar." (You have 1,407).

2 : Bit premature, XL2003.

3 : `#########` means Doesn't Fit, so make your column wider to see the real error...

4 : Even if I copy and paste it out of the column into notepad, all I get are pound signs. I also used 'auto-adjust' column width, with the same result.

5 : Weird, I've never seen a problem like that. Will the number of pound signs increase?

6 : Try copying and pasting from the Formula Bar(if you haven't). I sometimes run into this, and it's almost like Excel can't tell what your data is once it gets past a certain length... It annoys me, too.

7 : @AllenG: No luck with that.

8 : @Mvan: The number of pound signs doesn't seem to increase.


---------------------------------------------------------------------------------------------------------------
Id: 1648590
title: C# fluorine Client only working when Charles Web proxy is open
tags: c#, fluorinefx, netconnection
view_count: 584
body:

Hi: I created a console application that it should run every hour in order to push updates to a different server using FluorineFx for C# client (NetConnection). It works great, but only when I have Charles open and so I can see what is being sent. On the other hand, if Charles is closed, it does not send the data. I am running this on Windows Server 2003.

Thx.

RS

comments:

1 : You'll need to share more information about what happens when Charles is not running. How exactly is the connection being made? Does it connect? Does it send data? Does the server show the connection? Does the server receive data? Does the server send a response? Does the client receive any response? If you can't answer all these questions, then add more logging. You can also test with a more passive monitoring app like WireShark (I use Charles daily and love it, so not saying anything bad against Charles.. just in this particular case, obviously it's affecting your testing).

2 : I now notice that this is happening intermittent. Sometimes is sending the data using AMF and sometimes does not work. I am now installing WireShark. Thx and I will let you know all my findings.

3 : Did you find anything yet? I've had the same problem on my local machine using flex-weborb. Some of my colleagues have the same issue while others don't... very strange. Have even contacted weborb but they couldn't help me either... Maybe it's a security thing... crossdomain? Maybe using the ip-address instead of the name of the server?


---------------------------------------------------------------------------------------------------------------
Id: 2414122
title: Spring MVC manual form elements
tags: java, spring, spring-mvc
view_count: 766
body:

How would explicit hidden input elements be bound a model attribute?

I'm not using <spring:bind> or <form:hidden>. I have a Form bean that has an object with a child collection. A user adds to that collection on the fly...

public class Parent {
    List<Child> children = new ArrayList<Child>();
}

public class Child {
    String name;
}

public class Form {
    Parent parent;
}

public String onSubmit(@ModelAttribute("form") Form form, ...) {
    // form.getParent().getChildren() is always empty
}

In my JSP I have:

<input type="hidden" name="parent.children[index].name" value="" />

The value is populated by Javascript eventually, but when I debug the form post, the @ModelAttribute never has a value for any of the children and the HttpServletRequest doesn't have any of the child parameters.

Is there a way to do this manually?

I'm also adding on the fly:

function add_on_fly(stuff) {
    var index = $('#myTable tr').length - 1;
    $('#myTable tr:last').after('<input type="hidden" name="parent.children['+index+'].name" value="'+stuff+'" />');
}

Any ideas?

EDIT: got this working...

Hopefully this will help someone else in the future. It's not enough to instantiate an empty array of child elements because:

parent.children[index]

becomes

parent.getChildren().get(index)

which returns null because it isn't created yet. I got to work via:

http://mattfleming.com/node/134

Using the commons-collections LazyList:

List<Child> children = LazyList.decorate(new ArrayList<Child>(), new Factory() {
    public Object create() {
        return new Child();
    }
});

So each add() and get() calls have a Factory generated object to set properties via reflections on the Spring backend. I tried overriding add and get to no avail.

Also, there's no need to include parent reference, i.e. this works:

children[index].name
comments:

1 : You can also use Spring's `AutoPopulatingList`.

2 : Nice. I ended up using that ax.


---------------------------------------------------------------------------------------------------------------
Id: 3287214
title: Problem executing an SQL script from within the User-Menu in ISQL 4.10
tags: informix
view_count: 216
body:

I have the following SQL script with two unload statements:

UNLOAD TO "actives.unl"
   SELECT * 
     FROM table1 AS t1
    WHERE t1.status = "A"
 ORDER BY t1.fk_id;

 UNLOAD TO "inactives.unl"
   SELECT * 
     FROM table1 AS t1
    WHERE t1.status = "I"
 ORDER BY t1.fk_id;

When I execute the script from within ISQL's QueryLanguage Menu it works fine, but when I add this script as a menu option in SYSMENUITEMS and execute it from within the User-Menu, the two unload statements execute but unload 0 rows. I went back to my perform screen and queried table1 and all the rows were there???

comments:

1 : How do you determine zero rows are unloaded? By finding empty files 'actives.unl' and 'inactives.unl', or by not finding the files, or by seeing a report '0 rows unloaded'? Could current working directory be a factor?

2 : @Jonathan: before running the unloads, I checked table1 to make sure it has rows which satisfy the query criteria in the unload statements, it does..then I executed the unload statements from within isql's query-language menu [dbaccess equivalent]. Both unloads returned '0 row(s) unloaded'. Just in case, I ran bcheck[secheck equiv.] and no problems were detected with the table, so i dunno what's happening?

3 : Clutching at straws; what happens if you add 'DATABASE dbname;' as a first line in the script? I don't think it should make any odds if you've already got the database selected, but I'm not sure what else could be going on.

4 : @Jonathan: Yes, I'm very familiar with adding the DATABASE statement to some of my sql scripts because in 2.10, the connection would sporadically disappear when exeking sql scripts from the user-menu, but if that was the case, I would be getting the 'Database not selected' or 'backend busy/not avail...' err msg.. I have even isolated the unload stmts into a separate script and ran it as the first of a series of scripts from the menu, but to no avail. Btree consistency seems to be fine so that doesnt seem to be the problem.


---------------------------------------------------------------------------------------------------------------
Id: 2065879
title: Visual Source Safe - AjaxControlToolkit - Unexpected checkout
tags: visual-studio, ajaxcontroltoolkit, visual-sourcesafe
view_count: 181
body:

Let me start by saying I'm aware there are better version control systems than VSS, and also aware that a "web project" instead of a "web site" may be a better approach. Unfortunately, neither of those suggestions help solve my problem.

Basically, I have a series of AjaxControlToolkit.dll or AjaxControlToolkit.resource.dll files in my web project's bin folder. Each time a new developer begins working on a project, it checks out these files, but Visual Studio does not show them as checked out. The developer needs to go into Visual Source Safe, use [ctrl]+[s] to show all checked out files, and manually check those AjaxControlTollkit files back in.

Is there some file attribute that would cause this? I also have not found a way to 'include' a binary file in the Visual Studio project, although I expect this would be a bad idea considering the project needs to potentially write to this file during compilation.

Suggestions welcome.

** edit ** deleting additional files does not work. A compilation of the solution will actually re-generate all the files in question. I'm not sure if there is a debug/release separate versions of this toolkit, perhaps someone could enlighten me.

comments:

1 : You shouldn't need write access to AjaxControlToolkit.dll (assuming you don't recompile it from source)

2 : I agree. I suppose that is part of the confusion as to why a project build is checking the files out.


---------------------------------------------------------------------------------------------------------------
Id: 2978943
title: Executing cucumber in Rails results in error
tags: ruby-on-rails, cucumber
view_count: 43
body:

I am trying to learn ruby on rails, and am trying to set up cucumber. I get this error when trying to run it. I think the picture may say more than I could.alt text

comments:

1 : Have you tried doing `gem install win32console`?

2 : what the frak!?! Jakub please enter an answer, so I can accept it.

3 : Your question title sounds like a cryptic crossword clue. ;)


---------------------------------------------------------------------------------------------------------------
Id: 1944424
title: Copying Cell ID information from the Field Test Mode
tags: iphone, cellid
view_count: 914
body:

I'm looking to capture the Cell ID information and also the variable that is responsible for the signal strength bar on the iPhone for testing purposes. The information is accessible via the field test mode - is there any way to capture and store the data?

comments:

1 : You just asked this question, and received a response: http://stackoverflow.com/questions/1943983/copying-data-from-field-test-mode

2 : Noted - the answer asked me to be specific though - hence this question which identified the field that I'm looking to acquire.


---------------------------------------------------------------------------------------------------------------
Id: 2394832
title: Prevent jQuery UI tabs from automatically loading content
tags: jquery, jquery-ui
view_count: 382
body:

Consider a page like this:

<div id="tabs">
  <ul>
    <li><a href="first">First</a></li>
    <li><a href="second">Second</a></li>
  </ul>
  <div id="tabContent" class="ui-tabs-panel">
    This is the content of the ?First? tab!
  </div>
</div>
<script>
$("#tabs").tabs({
  select: function() { return false; },
  selected: 0
});
</script>

Despite the fact that select returns false, when the content of first will be loaded when the selected is set.

Is it possible to prevent jQuery UI's tabs from automatically loading this?

comments:

1 : Ricardo, it could be that something was wrong with your jquery code? Do you mind sharing your code so that we could possibly find the issue?

2 : Sure, just to give some background,what is happening is that the tab widget always loads the url in the tab link in the body of the tab, so if the url is a full page it will be loaded inside the body of the tab. Here's the code im using :


---------------------------------------------------------------------------------------------------------------
Id: 2967329
title: OSX Leopard HID getting simple keyboard input example?
tags: osx, keyboard, mouse, osx-leopard
view_count: 452
body:

I am about to implement simple keyboard and mouse input on osx for my engine. I want to abstract the implementation in more generic c++ classes like Keyboard and Mouse plus appropriate Listeners for portability. Anyways, I came across the Leopard HID Api (http://developer.apple.com/mac/library/technotes/tn2007/tn2187.html#TNTAG9000-SAMPLE_CODE_)which seems to be the right way to go for the osx implementation of these classes. Anyways, the examples of the HID are very complex and I can't really wrap my head around it as fast as I wished I could, so I was wondering if anybody has used it allready to get some basic mouse and keyboard input, or knows about some good examples/resources online. Or Maybe even a totally different way to go?

thanks

comments:

1 : To be honest, I think this might be way more low level than you need. I'm not familiar with OSX at all, but this looks closer to driver-level code than application-level code.

2 : well the problem is all the other cocoa implementations I found are bound to an application window and I would like to seperate windowing and keyboard/mouse/etc.

3 : okay, I just came across this: http://developer.apple.com/mac/library/documentation/Cocoa/Reference/ApplicationKit/Classes/NSResponder_Class/Reference/Reference.html I think This will allow me to seperate the events from any kind of View or Windowing


---------------------------------------------------------------------------------------------------------------
Id: 2774594
title: Implementing and resolving many service decorators in Castle Windsor
tags: c#, castle-windsor, decorator
view_count: 320
body:

I'm new to Castle Windsor, so I'm not sure what the best practise is in cases like the following: I have a service interface (ILoader), that is implemented by multiple Loader classes. I also have an implementation of ILoader that's a decorator:

public interface ILoader { }
public class LoaderImpl0 : ILoader { }
public class LoaderImpl1 : ILoader { }
public class CachedLoader : ILoader
{
    public CachedLoader(ILoader inner) { }
}

For each LoaderImpl... class, I want to register a CachedLoader in my container, that decorates a LoaderImpl... instance.

Here's my first rubbish attempt:

container.Register
(
    Component.For<LoaderImpl0>().Named("loader0"),
    Component.For<LoaderImpl1>().Named("loader1"),
    Component
    .For<ILoader>( )
    .ImplementedBy<CachedLoader>( )
    .ServiceOverrides( ServiceOverride.ForKey( "inner" ).Eq( "loader0" ) )
    .Named("cachedLoader0"),
    Component
    .For<ILoader>()
    .ImplementedBy<CachedLoader>()
    .ServiceOverrides(ServiceOverride.ForKey("inner").Eq("loader1"))
    .Named("cachedLoader1")
);

This just seems wrong, on 2 counts:

Can someone enlighten me where I'm going wrong?

comments:

1 : How do you intend to use it? Do you always resolve all `ILoader`s at once? Or do you just want to have cached loader each time you request an `ILoader`?

2 : Hi, yes I want to resolve all ILoaders at once - well, I think so. I want to inject an array of all of them into a loader manager. I think I have to do this manually, as using an array resolver is a bad idea? Also, not every ILoader implementation suits having a cached loader.

3 : Perhaps using AOP would be better idea then? http://ayende.com/Blog/archive/2007/03/11/AOP-With-Windsor-Adding-Caching-to-IRepositoryT-based-on-Ts.aspx

4 : hmm interesting I'll give it a go. I should really refactor my question, though, because it comes in two parts. AOP would solve the caching of loaders (although it seems a bit of overkill - can't I inject an anonymous LoaderImpl class directly into a CachedLoader), and why does ResolveAll return all 4 loaders? Shouldn't it just return the 2 cached loaders?

5 : That's just how ResolveAll works - it means "Give me all components that I can use as `ILoader` not just these that were registered as `ILoader`". Most of the time that's the preferred behavior.


---------------------------------------------------------------------------------------------------------------
Id: 2147829
title: Overview of the various java web view technologies
tags: java, spring
view_count: 259
body:

Generally speaking, what are the advantages/disadvantages of the various java servlet/spring-mvc view technologies? (jsp, freemarker, velocity, etc)

E.g. is one faster than the other? More built-in support? flexibility? wide-spread usage?

My use case is a cms type application.

comments:

1 : Question too broad scoped. Please narrow it down

2 : Alternatively, consider making this a community wiki.


---------------------------------------------------------------------------------------------------------------
Id: 2036735
title: Simple RPN Calculator in Assembly (mips32)
tags: assembly, rpn
view_count: 842
body:

i have a project in my university about RPN calculator in Assembly language but i dont really know much . can someone help me out with the code ?

thanks !!!

comments:

1 : Then I suggest you either learn, or leave your course and pick one that you actually *do* know things in.

2 : As a start, do you know enough to write an RPN calculator in a higher level language? "Hi, this is my project. Do it for me." may not find many takers here.

3 : i know Java , C++ . i know what is RPN and how it works . i just dont have the write a simple RNP calculator program in assembly language beacuase its our first project .

4 : Next steps: 1) can you code a stack structure in assembly 2) can you manage text IO in assembly. If you can do both you should be good to go.


---------------------------------------------------------------------------------------------------------------
Id: 2820211
title: Asymptotic runtime question
tags: big-theta
view_count: 141
body:

If f(n) is ?(g(n)), then the function 2^(f(n)) is always ?(2^(g(n))). Is this statement true or false, and why?

comments:

1 : It's a tough final?

2 : This sounds like a homework question. If it is, please tag it as such. Also, tell us what progress you have made so far and where you are stuck. SO is not here to do your homework for you, but we will provide help to posters who have made a valid effort on their own.


---------------------------------------------------------------------------------------------------------------
Id: 3374143
title: Anyone having (or solved) these problems with Windows 7 Virtual PC (Recording sound, Drag 'n Drop, etc.)
tags: windows-7, audio, virtual-pc
view_count: 216
body:

Windows Virtual PC problems:

  1. There is no "Shared Folders" option to allow us to access folders on the Host machine within the Client machine using drive letters (E:\ etc.). We have several programs that I need to test and I need to access files on the E:\ drive, etc. Note that the Host folders that you see "D on " is not what I need. I need access via a drive letter. I've tried mapping a network drive and access that way is incredibly slow.
  2. Microphone recording not enabled (in the Client running Win XP, or 7, and probably Vista) *if Integration Features are enable*d. You can test this with Sound Recorder. It simply does not show the Record button if integration features are enabled. If I disable them then it appears
  3. Drag and Drop (from Host to Client) does not work. And (IIRC) Copy and Paste works only to the Desktop of the client.
  4. Integration Features do not work unless you log in (to the Client) using the same User Name and Password as an account on the Host machine.
  5. Virtual PC does not remember the User Name and Password when logging into Win 7 (client) even when you have Logon Credentials saved. (In the Settings window).

Any ideas?

I've checked for newer versions of Virtual PC but all I can find are the old version (pre Win 7) and the Win 7 "XP Mode".

I have Win 7 set to autoupdates so I assume if there were a newer version it would have gotten it.

comments:

1 : Belongs on superuser.com

2 : I posted there but got no response. VPC is, I think, used primarily by software engineers and testers then by "power users".


---------------------------------------------------------------------------------------------------------------
Id: 1377392
title: need an idea for conversion of encoding mechanism in python
tags: encoding
view_count: 56
body:

can somebody suggest me how can i convert the radix64 encoded public key to a MIME encoded key. i am having the public key in radix64 encoding format now i need to convert it in MIME .is there any python API to do this ....

thanks

comments:

1 : What kind of key are you talking about?

2 : it is a public key


---------------------------------------------------------------------------------------------------------------
Id: 3072039
title: Php SOAP yudu example?
tags: php, soap
view_count: 173
body:

I am trying to connect to Yudu's web service via soap/php. When I send this test, I am getting the following fault response and code:

ERROR: env:Server-java.lang.RuntimeException: com.yudu.webservice.InternalError

If I dont specify a subscriptionId I get the following fault:

Client-SOAP-ERROR: Encoding: object hasn't 'subscriptionId' property

So I think I am close but I have no idea what I may be missing or if I am accessing the right node. I am using the test login in the api doc.

Any response would be greatly appriated! Below is my code. Thanks!

   $soapClient = new
SoapClient("http://login.yudu.com/webservice-static/ManageSubscriptions.wsdl");

       // Prepare SoapHeader parameters
       $sh_param = array(
                   'username'    =>    'webservicetest@yudu.com',
                   'password'    =>    'DigitalEditions');

       $headers = new SoapHeader('https://login.yudu.com/webservice/ManageSubscriptions',
'authenticationDetails', $sh_param);

       // Prepare Soap Client
       $soapClient->__setSoapHeaders(array($headers));

       // Setup the RemoteFunction parameters
       $ap_param = array(
                   'subscriptionId'     =>    33136);

       // Call RemoteFunction ()
       $error = 0;
       try {
           $info = $soapClient->__call("viewSubscription", array($ap_param));

       } catch (SoapFault $fault) {
           $error = 1;
           var_dump($info);
           print("ERROR: ".$fault->faultcode."-".$fault->faultstring);
       }
comments:

1 : More information necessary - could you post a URL to the WSDL in question? SOAP connections aren't difficult and are well documented on the PHP web site.

2 : Hey Jarrod, Ty for your response, I just updated my post with my sample code and wsdl. TY so much!


---------------------------------------------------------------------------------------------------------------
Id: 2243485
title: Increasing object allocations, While checking object allocations in the Instruments
tags: objective-c
view_count: 82
body:
- (MKAnnotationView *) mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>) annotation
{
    MKPinAnnotationView *annView = nil;
    annView=[[[MKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:@"currentloc"]autorelease];
    for(int i=0;i<[List count];i++)
    {
        Small *Obj=[List objectAtIndex:i];
        if([[annView.annotation title] isEqualToString:Obj.streetAddress])
        {
            annView.animatesDrop=TRUE;
            annView.canShowCallout = YES;
            annView.calloutOffset = CGPointMake(-5, 5);
            annView.rightCalloutAccessoryView=[UIButton buttonWithType:UIButtonTypeDetailDisclosure];
            [annView setPinColor:MKPinAnnotationColorGreen];

        }

    }

    return annView;
}
comments:

1 : Did you turn *off* NSZombie?

2 : Is there a question somewhere?


---------------------------------------------------------------------------------------------------------------
Id: 1799436
title: Not able to Access WCF Service - IIS
tags: wcf
view_count: 277
body:

I have a problem accessing WCF service that I added for my silverlight project. Here is what I did 1. Created the silverlight project and enabled the project's default web setting to use "Use local IIS web server".

  1. Then I added a WCF enabled web service (Service1.svc) in the web project.This created the service with the default custom binding which looks like

  2. Then I added the reference in my silverlight project to the service (Service1.svc) I created in the web project.

  3. Set the authentication mode to "Anonymous" at the virtual directory level in IIS ( I have IIS 5.1 on WinXP Prof).

  4. Added a button in the silverlight to call the function of the WCF service (Service1.svc).

  5. Now whenever I click the button for the first time, IE pops up the message box asking Username & Password which it usually does during basic authentication! Any subsequent click works fine without popping up the credential box. Next I created another web service and added one more button to call this new webservice. Clicking either of the button for the first time pops-up the credential box but thenafter it goes smooth.

My question is why it pops up the credential box whenever trying to call the web service for the first time with this default "Custom Binding"? As far as I know the security value is set to none in default custom mode.

Next I tried doing the same with basicHttpBinding. In this case the credential IE box pops up again but the call fails all the time giving security error! Can someone please explain why this basicHttpBinding is failing all the time? I am using VS2008 SP1, WinXP Prof, IIS 5.1

comments:

1 : Exact duplicate of: http://stackoverflow.com/questions/1799143/problem-accessing-wcf-service-when-hosted-in-iis

2 : Please don't crosspost - if you need to add something, **EDIT** your original question - thank you!


---------------------------------------------------------------------------------------------------------------
Id: 3098835
title: Cocoa Touch: How can I access resource sub-directory?
tags: cocoa-touch, ipad, nsfilemanager, nsbundle
view_count: 263
body:

Currently I am working on iPad. In the Resources folder of project, I have a sub-directory "sounds". How can I access it to get the contents of this sub-directory?

I have tried:

NSArray *array = [fileManager directoryContentsAtPath:
                  [[[NSBundle mainBundle] bundlePath]
                    stringByAppendingString:@"sounds"]];

But the array I got is empty. Anyone know a solution?

Thank for your help.

Thank you.

comments:

1 : Please ensure the `sounds` directory is correctly copied (right click on the `.app` file in Products, Reveal in Finder, right click on the `.app` in Finder, Show Package Contents.)

2 : are you sure you don't want to access [[NSBundle mainBundle] resourcePath] ?


---------------------------------------------------------------------------------------------------------------
Id: 3134093
title: Help understanding a C++ sample app which uses global mouse event hooks?
tags: .net, c++, event-handling, hook, mouseevent
view_count: 330
body:

I'm trying to understand and implement the sample presented in this MSDN forum thread.

The sample involves implementing a global hook to catch mouse movement and click events, and act on them under certain circumstances.

I know C# pretty well, but I don't know C++ enough to understand what this sample code is doing. The contributor of the sample says a logfile should be created for certain mouse events, but I'm not seeing a log file created in the build folder of the sample, so not sure what's wrong.

I'd like to be able to break down the example and see exactly how the DLL is used by the sample app (located here). In the meantime I'm wading through this informative article on CodeProject which describes global system hooks.

Help in this regard from anyone with C++ expertise would be greatly appreciated!!

comments:

1 : Have you verified whether a WH_MOUSE_LL hook can do the job? It is *much* easier to get going since it doesn't require an injectable DLL.

2 : I don't know what you mean, is WH_MOUSE_LL a different kind of hook? And are you saying I'd be able to use this hook directly in my own test app without having to use the DLL as in the sample?

3 : @Hans: I found an example related to WH_MOUSE_LL here, which I've been able to use successfully: http://support.microsoft.com/kb/318804/en-us


---------------------------------------------------------------------------------------------------------------
Id: 2636014
title: No Cookies at second Webrequest
tags: c#, authentication, cookies, login, webrequest
view_count: 452
body:

I login to a website by HTTPwebrequest, I get an authentication cookie.

When I make a new HTTP-webrequest and add the cookies from the first request to call the next page where I can see my personal data. I see that the cookies will associated with the second request if I debug it but if I check the network traffic I see that are no Cookies transmitted at the second request. I tried many possibilities to see why I don't work but I found nothing.

Does anyone know a solution?

comments:

1 : possible duplicate of [C# WebRequest using Cookies](http://stackoverflow.com/questions/4158448/c-sharp-webrequest-using-cookies)

2 : Can you add a code example of how you are doing the two requests?


---------------------------------------------------------------------------------------------------------------
Id: 2723958
title: How can I save BioPerl sequence nested features in genbank or embl format?
tags: perl, bioinformatics, bioperl
view_count: 213
body:

EDIT: Please close this question.

I asked and got an answer for it on BioStar here.


In BioPerl, a sequence object can have any number of features, and each of these can have subfeatures nested within them. For example, a feature may be a complete coding sequence of a gene, and its subfeatures might be individual exons that are concatenated to form the full coding sequence.

However, when I use BioPerl to write a sequence object to a file in genbank or embl format, only the top-level features are written to the file, not the sub-features nested within the top-level features. How can I store my subfeatures in sequence files? Should I just convert all my subfeatures into top-level features, and then reconstruct the tree structure next time I read in the sequence? Is there another file format that supports subfeatures? Maybe Data::Dump?

comments:

1 : if BioPerl works as BioPython does, I think the sub-features get lost when you write to a file. However, you may get a better anwer by asking it on http://biostar.stackexchange.com/questions or on bioperl's mailing list.

2 : What's the point of subfeatures if you can't save them to a file? Is there some other format I can save that preserves subfeatures?

3 : Also, thanks for the biostar link.

4 : I got an answer for this on BioStar, so this can be closed.

5 : By the way, here's the question on BioStar: http://biostar.stackexchange.com/questions/910/how-can-i-save-bioperl-sequence-nested-features-in-genbank-or-embl-format

6 : assisting with close

7 : Unfortunately, there's not a close reason that closely matches "found on another SE site," so I'm going to have to close as off-topic.

8 : Yes, closing as off-topic seems to be the consensus for such situations: http://meta.stackoverflow.com/questions/48662/can-we-have-belongs-on-some-other-stackexchange-site-as-an-option-when-voting-t


---------------------------------------------------------------------------------------------------------------
Id: 2135123
title: GQL query with "like" operator
tags: google-app-engine, gql
view_count: 1886
body:

Possible Duplicate:
Google App Engine: Is it possible to do a Gql LIKE query?

In SQL (T-SQL at least) you can write a query that uses the "like" operator, something like this:

select * from MyTable where MyColumn like '%something%'

Is there any way to do this in GQL?

comments:

1 : Duplicate of http://stackoverflow.com/questions/47786/google-app-engine-is-it-possible-to-do-a-gql-like-query

2 : Ok, thanks bdukes


---------------------------------------------------------------------------------------------------------------
Id: 3361775
title: two network interface at client side does not connect socket
tags: c++, visual-c++, sockets
view_count: 126
body:

i have two network interface installed on client system interface one has ip 192.168.3.1 and interface 2 has ip 192.168.5.1 ,i want to connect to remote system which has ip 192.168.5.7 but connection not establish.when i disable network interface 192.168.3.1 it will work fine. i am using the following code

#include "windows.h"
#include "stdio.h"
#include "conio.h"
#include "winsock2.h"

bool Connect(const char *addr_name, int port)
{
    int ErrorCode=0;
    SOCKET Socket;

    ::WSAData wsa_data;
     ErrorCode = ::WSAStartup(MAKEWORD(1, 1), &wsa_data);
    if( ErrorCode != 0)
        return ErrorCode;

    // Get binary address to connect to
    u_long addr = inet_addr(addr_name); 

    if (addr == INADDR_NONE)
        ErrorCode=1;
    else
    {
        // Allocate socket
        Socket = ::socket(AF_INET, SOCK_STREAM, 0);
        if (Socket == INVALID_SOCKET)
            ErrorCode = ::WSAGetLastError();
        else
        {
            // Set up sockaddr_in for connect
            sockaddr_in sin;
            memset(&sin, 0, sizeof(sin));
            sin.sin_family = AF_INET;
            sin.sin_port = ::htons((u_short)port);
            sin.sin_addr.s_addr = addr;

            // Connect the socket to the address
            if (::connect(Socket, (sockaddr*) &sin, sizeof(sin)) == SOCKET_ERROR)
            {
                ErrorCode = ::WSAGetLastError();
                ::closesocket(Socket);
                Socket = INVALID_SOCKET;
            }
        }
    }

    return ErrorCode == 0;
}

void main(int argc,char** argv)
{
    Connect("192.168.5.7",1258);
}
comments:

1 : Can you post the subnet mask for each interface involved?

2 : Frank is probably right - `192.168/16` in the routing table would match both IPs but only one interface.


---------------------------------------------------------------------------------------------------------------
Id: 3124115
title: about heap and deleting the i-th item
tags: heap
view_count: 106
body:

hi I want to write an algorithm that will delete the i-th item in the heap which has o(logn),also I want to know that the i-th element will be the less one item in the heap or no? is there any site that help me to write this algorithm? please help me thanks

comments:

1 : also this is not my home work

2 : a heap can be implemented as a binary tree. look up binary tree search and element deletion on google and that's your answer


---------------------------------------------------------------------------------------------------------------
Id: 2650561
title: How to refresh a webpage in IE
tags: vbscript, page, refresh, using
view_count: 527
body:

HI all,

I have Ishare URL " www.example.com\ishare " which i opened it thru wshshell. I want this page to be reloaded every 10 seconds. any help on this would be much appreciated. following is the script,

Dim WSHShell Dim oShell

Set WSHShell = WScript.CreateObject("WScript.Shell")

WSHShell.Run("iexplore https://Infrastructure/IA/Lists/Incidents/AllItems.aspx") oShell = "Incidents - Microsoft Internet Explorer"

WSHShell.appActivate(oShell) WScript.sleep 500 WSHShell.SendKeys "{F5}" Set WSHShell = Nothing

comments:

1 : Hi David, Thanks for your reply, Webpage i access to is located in the server, as a normal user i am accessing this site in this case how can i edit the page... could you please guide me on this

2 : What's wrong with the script? it looks fine to me ..


---------------------------------------------------------------------------------------------------------------
Id: 1651890
title: Hosting Flash ActiveX control in WPF
tags: wpf, flash
view_count: 810
body:

I want to host a Flash animation in a WPF project. It is okay. But the problem is it shows in a tabcontrol. When I click second tabitem I want the flash animation to start. It gives this error:

Exception of type 'System.Windows.Forms.AxHost+InvalidActiveXStateException' was thrown.

My codes are as follows:

C# code.

    private void Maintab_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
        if (this.Maintab.SelectedIndex == 2)//Second tabitem
        {
            System.Windows.Forms.Integration.

            WindowsFormsHost host = new System.Windows.Forms.Integration.WindowsFormsHost();

            xShockwaveFlashObjects.  //What is this ?????

            AxShockwaveFlash axShockwaveFlash1 = new AxShockwaveFlashObjects.AxShockwaveFlash();
            host.Child = axShockwaveFlash1;
            this.FlashGrid.Children.Add(host);
            string swfPath = System.Environment.CurrentDirectory;
            swfPath +=@"\cell.swf";
            axShockwaveFlash1.Movie = swfPath;
        }
    }

XAML:

    <TabControl
      Style="{DynamicResource GelTabControl}"
      Margin="0,0,8,36"
      x:Name="Maintab"
      SelectionChanged="Maintab_SelectionChanged" >

        <TabItem
          x:Name="Actions"
          Header="Actions"
          Style="{DynamicResource GelTabItem2}"
          TabIndex="1">
        </TabItem>

        <TabItem
          Header="Rapid Note"
          Style="{DynamicResource GelTabItem2}"
          TabIndex="2" >
            <Grid x:Name="FlashGrid">
            </Grid>
        </TabItem>

    <!-- Something is missing here !?  -->

Thanks in advance.

comments:

1 : I'd like to know if the same exact code can be used to host it in a Windows Forms window. It should, but then again, so should the above code work. It'd be interesting to know if that works. If the same code can work for hosting the Flash ActiveX control in a Windows Forms window, then create a Windows Forms Control that hosts the Flash control (just as a test). So now the client of the control shouldn't know or care about Flash or ActiveX. As far as they're concerned, it's simply a Windows Forms Ctrl. Then try placing that control in a WPF Container. Curious at which point it'll fail.

2 : Hi; sorry but i didnt understand what you are saying. My english is poor. So Can you be more clear?


---------------------------------------------------------------------------------------------------------------
Id: 1432471
title: jQuery Coda Slider Plugin Tearing sides on Firefox 3.5
tags: jquery, firefox3.5, coda-slider
view_count: 856
body:

I'm currently using this jQuery Coda Slider plugin at www.ndoherty.com/demos/coda-slider/1.1.1/ with some custom code to make it auto-rotate. Works in all browsers but Firefox 3.5 on both Mac and WinXP.

The issue is the sides of the slider seem to be tearing and it tears only partially so I suspect its a rendering issue. And if so I doubt any CSS hacks can fix it.

You can see the issue here. Just wait for it to slide or click the "»" or "«" near the center.

If anyone has any ideas what's wrong I'd love to hear your views.

Remember You'll need Firefox 3.5 to see the error.

comments:

1 : tables for layouts much?

2 : lol. unfortunately amazon's templates are all based on table layouts, which are not even class-ed or id-ed sufficiently.

3 : anyways, it seems to be an issue with firefox 3.5 and jquery's easing plugin. I've since changed the carousel to a simple fade in/fade out plugin. Google ads and jquery's clone function also don't like each other, so that ruled out lots of other carousel plugins.


---------------------------------------------------------------------------------------------------------------
Id: 3295222
title: Problem with UI Layout plugin in combination with Tokenizing autocomplete plugin, MVC .NET application
tags: jquery, jquery-ui, jquery-plugins, autocomplete, tokenize
view_count: 163
body:

i have problem with jquery layout plugin in combination with Tokenizing autocomplete plugin.

When i click on close bar on one of panes inside which sits input text box with tokenizing autocomplete plugin, div close. But, when reope i can find 2 input text boxes with tokenizing plugin.

Anyone have solution for this? Need to prevent duplicating, application is in MVC .NET 2.0. with mentioned plugins.

comments:

1 : Maybe you're initializing something twice, like upon opening a panel.

2 : Nope, it only happens first time, afterwards is fine. So it doesn't duplicate again on second close/open....


---------------------------------------------------------------------------------------------------------------
Id: 3136756
title: Sparkle framework delegation question
tags: objective-c, cocoa, delegates, sparkle
view_count: 93
body:

I have a wrapper application which launches a bundled application and then immediately quits (using [NSApp terminate:nil]). I would like to include Sparkle in this wrapper (it's not going to be possible to include if for the bundled app itself), and I've implemented it without any issues: so long as I comment out the NSApp terminate line. The wrapper itself has no windows, so I can use:

-(BOOL)applicationShouldTerminateAfterLastWindowClosed:(NSApplication *)theApplication
{
 return YES;
}

to terminate the wrapper after the sparkle window is dismissed. This only works though, if there is actually an update. So want I really want to do is have some code that checks if there is an update available, and if not, then terminate the wrapper at the end.

I know this can probably be done with checkForUpdateInformation but I'm still a bit lost with the whole delegation thing, so I'm not sure how to implement it.

Any help would be appreciated.

comments:

1 : Sorry for being off topic, but why do you have a wrapper at all? And why do you want to update that thin wrapper often???

2 : ha! I knew someone would ask that.The wrapper is for the main application which is not written in cocoa, and has various other limitations. Using sparkle within the wrapper will allow me an easy way to notify the user of updates to the *bundled* application (installing the update will then update both the wrapper and the bundled app), as it's not possible to do so from the bundled application


---------------------------------------------------------------------------------------------------------------
Id: 1865239
title: Error when asynchronously waiting for process to exit
tags: c#, compact-framework, processes
view_count: 175
body:

I am getting an error with the following code:

var p = new Process();
p.EnableRaisingEvents = true;
p.StartInfo.FileName = this.CommandLine;
p.StartInfo.Arguments = this.CommandArgs;
p.Exited += new EventHandler(OnProgramExit);
p.Start();

When this code is executed, shortly after the process is started, i get an error within the Framework: NullReferenceException at System.Diagnostics.Process.TermWaiter.WaitForTerm().

If i remove the line "p.EnableRaisingEvents = true", the code executes without a problem, but the Exited event is never fired. If i handle the code synchronously with "p.WaitForExit();" the code works fine, however the program hangs waiting for the process to exit.

Any ideas? It's probably worth emphasizing that this is in the Compact Framework (v 3.5). In my tests i am just running the calculator (\Windows\calc.exe) on a device running CE 5.0.

comments:

1 : Just wondering - are you *sure* it isn't being triggered by an exception in `OnProgramExit` (gotta ask, sorry)

2 : Nah - that method is empty. The exception occurs before the process is exited, so it is never triggered anyway.

3 : I know it's ugly but you could just call the sync version on a background thread so you don't lock your main thread up.

4 : That's how i've resolved it, and it's working fine. I'm still curious as to why this isn't working.


---------------------------------------------------------------------------------------------------------------
Id: 2981830
title: Getting service unavailable message when sending messages to google xmpp using wokkel
tags: python, google, xmpp, instant-messaging
view_count: 218
body:

I made a wokkel (twisted python) bot to send and receive messages from the google xmpp service. Everything (auth, presence) etc works fine. One of the requirements of our project is that we need to send broadcast messages to everyone in the list. Normal messages and replies work fin, but when i send a broadcast message, i get this service unavailable error 503 message.

There are about 1000 user in my contact list. Is this some bug in the code or is it google policy to prevent rapid messaging.

Also, how do other google bots cater to a large contact base ? does google provide a commercial solution for such applications ?

Thanks

comments:

1 : why no answers :-?


---------------------------------------------------------------------------------------------------------------
Id: 3031395
title: Windows 7 DWM weirdness
tags: c#, api, screenshot, task, dwm
view_count: 363
body:

I'm looking to write a FOSS "Alt+Tab" replacement (window switcher) for Windows, since there are a few features I feel it's (still) lacking; but I'm noticing two quirks I can't seem to fix:

#1. (Somewhat Unrelated) In the default Windows 7 window switcher, one computer allows left clicking on a thumbnail to focus the window; however on another, similarly specced computer, I have to use a right click. The only difference between these two fresh installs is the theme. Any ideas?


#2. (Directly Related) In both the default Windows 7 window switcher and the DWM API output, minimized windows often have no thumbnail, and instead show only the taskbar. This has been a long running problem with the Windows API, and in the past I've seen the popular recommendation being "restore (un-minimize) the window, take a screenshot, then re-minimize" - but this is sloppy and causes flickering, etc. Has anyone done this successfully using the newer DWM API?

If sharing code, I'd prefer C# syntax, but VB.NET will do as well. Thanks!

comments:

1 : This is similar to a question i asked (http://stackoverflow.com/questions/3848558/dwm-what-api-to-create-applications-like-flip3d), but starting from a different place. i *assume* Microsoft is using an internal, undocumented, API to power the Flip3D, which is why it has access to the screenshot of minimized windows.


---------------------------------------------------------------------------------------------------------------
Id: 2895764
title: Nhibernate Left Outer Join Return First Record of the Join
tags: nhibernate, criteria, left-join
view_count: 484
body:

I have the following mappings of which Im trying to bring back 0 - 1 Media Id associated with a Product using a left join (I havnt included my attempt as it confuses the situation)

ICriteria productCriteria = Session.CreateCriteria(typeof(Product));

productCriteria  
.CreateAlias("ProductCategories", "pc", JoinType.InnerJoin)  
.CreateAlias("pc.ParentCategory", "category")  
.CreateAlias("category.ParentCategory", "group")  
.Add(Restrictions.Eq("group.Id", 333))  
.SetProjection(  
    Projections.Distinct(  
        Projections.ProjectionList()  
            .Add(Projections.Alias(Projections.Property("Id"), "Id"))  
            .Add(Projections.Alias(Projections.Property("Title"), "Title"))  
            .Add(Projections.Alias(Projections.Property("Price"), "Price"))  
            .Add(Projections.Alias(Projections.Property("media.Id"), "SearchResultMediaId")) // I NEED THIS  
    )  
)  
.SetResultTransformer(Transformers.AliasToBean<Product>());  

IList<Product> products = productCriteria  
.SetFirstResult(0)  
.SetMaxResults(10)  
.List<Product>();  

I need the query to populate the SearchResultMediaId with Media.Id, I only want to bring back the first Media in a left outer join, as this is 1 to many association between Product and Media

Product is mapped to Media in the following way

mapping.HasManyToMany<Media>(x => x.Medias)  
.Table("ProductMedias")  
.ParentKeyColumn("ProductId")  
.ChildKeyColumn("MediaId")  
.Cascade.AllDeleteOrphan()  
.LazyLoad()  
.AsBag();  

Any Help would be fantastic.

comments:

1 : Thanks for cleaning up this post Jon. I dont suppose you would have an answer?


---------------------------------------------------------------------------------------------------------------
Id: 3118093
title: Struts 2 - How to map a wildcard-matched method to an exception?
tags: java, exception-handling, struts2
view_count: 296
body:

I'm working with Struts2. Here's a snippet of my struts.xml file:

<action name="*test" class="fend.config.TestAction" method="{1}">
            <exception-mapping result="fail" exception="java.lang.UnsupportedOperationException"/>
            <result name="success">/registerCrisis.jsp</result>
            <result name="dummy">/dummy.jsp</result>
            <result name="fail">error.jsp</result>
            <interceptor-ref name="configStack"/>
        </action>

When I run the application like: http://localhost:8080/appContext/viewtest.action struts calls the view method in the TestAction class. I the view method I put code that generates a java.lang.UnsupportedOperationException just for testing purpose.

What I intended was to redirect to the result named fail, so that error.jsp is showned. But it's not redirecting to the page. What I've missed?

Thank you.

comments:

1 : Just an errata here, I've mistyped the fail result on the snippet. Where you read error.jsp is /error.jsp.

2 : If you return success does it render the registerCrisis.jsp page? In other words, are you sure the problem is with ``, and not with `` ?

3 : If it return success it renders registerCrisis.jsp. But when I get an UnsupportedOperationException I don't know what struts returns, but its rendering registerCrisis.jsp. I thought that with the mapped exception being thrown struts would render the error.jsp page. If for instance, I get the same exception in the execute method it renders error.jsp correctly.

4 : Can you show us your `` fragment in your struts.xml ? Did you map every exception to a 'fail' result?

5 : @leonbloy I just added this in the xml, just this one inner to this action.

6 : and... ? It does now work? i see you are using a special interceptor stack. Something particular there?


---------------------------------------------------------------------------------------------------------------
Id: 1634683
title: Trouble setting up WebDAV
tags: iis7, webdav
view_count: 435
body:

Rather than using FTP to access my hosting provider, which I read is unsecure, I'm trying to set up WebDAV (which I've never done before). I don't see WebDAV in the Actions pane of IIS Manager. So I found a link at http://www.iis.net/extensions/WebDAV to install it. I'm running Windows 7, so when the Web Platform Installer gave a message that my operating system is not supported, I tried the x64 link from that site. Then I get the message "IIS Version 7.0 is required to use WebDav 7.5 for IIS". That would suggest I didn't install IIS7, which I'm pretty positive I did. In IIS Manager the Help | About says Version 6.1 (Build 7600) at the top (6.1 makes me think IIS6?) but then at the bottom it says "Internet Information Services (Version 7.5.7600.16385), which seems to suggest IIS7, right? Any ideas on how I can get going with WebDAV? Thanks!

comments:

1 : This belongs on serverfault.com

2 : OK, I will, thanks.


---------------------------------------------------------------------------------------------------------------
Id: 1851777
title: Confused over getting GPS location in Blackberry
tags: blackberry, gps
view_count: 504
body:

I am really confused over getting GPS location of user. do i have to implement separate logic for GSM and CDMA devices??...besides there are so many modes for getting GPS location(cellsite , stand alone , cell assisted etc). really confused over which criteria to set..and also some networks refuse some modes(e.g. cellsite).

what i really know that autonomous mode works for all. but that cant be used inside buildings , over near tall buildings...so that doesn't make any sense.

comments:

1 : Have you read KB articles? http://www.blackberry.com/knowledgecenterpublic/livelink.exe?func=ll&objId=800703&objAction=browse&sort=name

2 : yesy i have gone through it...but the real problem is in choosing the criteria... some networks allow cellsite while some don't..for GSM devices the only option available is autonomous mode which doesnt work inside buildings..so do i have to check for criterias one by one...like first check for cellsite ,then for assisted , and if that too fails then go for Autonomous..

3 : Is there any other way i can get my current location without using Location API(JSR 179)...like "Cellsite triangulation"...


---------------------------------------------------------------------------------------------------------------
Id: 2597114
title: Cannot run file_get_contents() on PHP 5.2.9-2
tags: php, ssl
view_count: 309
body:

I am having the same problem as described below.

http://marc.info/?l=php-general&m=124104032703506

That is, I can't run file_get_contents() on PHP 5.2.9-2.

The guy answered his own question by:

"Sorry, didn't pay attention to the registered streams :-(
You need to install a PHP package with ssl or compile it with
--with-openssl."

What does that mean? I'm fairly new to all this stuff and I don't quite understand what he was talking about, (e.g. registered streams, ssl). We have another server that has SSL. Does he mean that if I just transfer to that server, problem solved? (Our web app doesn't need SSL by the way.) Or is there anything else I need to consider?

This is the error message that I got:

Warning: file_get_contents(URL OF THE FILE HERE) [function.file-get-contents]: failed to open stream: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond. in D:\WebServer\Sapphire\CMS_2009\apps\Newswire\send_mails.php on line 54

Fatal error: Maximum execution time of 60 seconds exceeded in D:\WebServer\Sapphire\CMS_2009\apps\Newswire\send_mails.php on line 54

Can you please help me out?

Any help is much appreciated :)

comments:

1 : Try http://superuser.com

2 : Can you provide a code sample and the error message you are receiving?

3 : I added the error message

4 : Are you trying to connect to a url that begins with https? What webserver are you using? This is leaning towards a configuration issue (SF).

5 : Nope. It's just HTTP. So I don't need SSL, right? I tried using fopen() instead of file_get_contents(), but same error.

6 : Two possibilities: Is there a firewall preventing outbound connections from the web server? Is the URL it's accessing actually accessible?

7 : The file being accessed is on the same server (in a subdirectory)

8 : Can you get to the url successfully in a browser?

9 : Can you do a `file_get_contents('http://www.google.com')` ?

10 : What is the file size of the document you're trying to read? Are there any special characters (e.g. spaces) in the file path?


---------------------------------------------------------------------------------------------------------------
Id: 3328607
title: Application development with hotkeys
tags: java, application-design
view_count: 49
body:

I'm writing application that will have global hot keys option and I need keys binding panel where user can define their own key shortcuts. I want something similar to Eclipse binding control in Windows - Preferences - General - Keys. I see that other applications use similar concept when typing keys in that control, for example "ctrl+" is always placed first than goes "alt+", and than "shift+". Is there any standard and documented way to do this? Any java source code?

comments:

1 : Take a lool at http://www.java-forums.org/advanced-java/5252-how-add-hotkey-ctrl-vk-button.html. Google is your friend.

2 : What are you using to build the UI of that application: AWT, SWT, Swing? Or is it web-based?

3 : It doesn't matter, it's desktop app and I will use anything that works.


---------------------------------------------------------------------------------------------------------------
Id: 2662253
title: problem with pasting image over lines in wx DC
tags: python, image, wxpython, bitmap, buffer
view_count: 66
body:

i have the same code as wx Doodle pad in the wx demos
i added a tool to paste images from the clipboard to the pad. using wx.DrawBitmap() function , but whenever i refresh the buffer .and call funtions ( drawSavedLines and drawSavedBitmap) it keeps putting bitmap above line no matter what i did even if i called draw bitmap first and then draw lines .

is there anyway to put a line above the bitmap ?
please inform me if i miss anything
thanx in advance

comments:

1 : You might want to mention that the Doodle pad you're referring to is in the CustomDragAndDrop demo... I had to grep to find the class you were referring to.

2 : put small code, which can be run without modification and demonstrates the problem


---------------------------------------------------------------------------------------------------------------
Id: 1807172
title: Problem making overlay draggable
tags: ajax, jquery-ui, overlay, draggable
view_count: 259
body:

I have created a script that upon clicking a button displays an overlay which loads an html table by ajax. The problem I'm having is with making the overlay draggable. The first time I click on the button the overlay is displayed and is draggable. However when I close the overlay and click the button again the overlay is displayed but is not draggable. Firebug's console reports overlay.draggable is not a function (the second time).

$("#control").click(function() {
       if ($('div.ov').length ==0){
          var height= 400;
          var width = 800;
          var left = (screen.width/2) - (width/2);
          var top =  (screen.height/2) - (height/2);

          $.ajax({
             type : 'GET',
             url:'edit.php',
             data: {},
             dataType: 'html',
             success: function(data) {
                var overlay = $("<div class='ov'></div>");
                overlay.css({'left':left, 'top':top, 'height':height, 'width':width})
                .html(data).appendTo("body");
                overlay.draggable({handle:'th'});
                var closebtn = overlay.find('#close');
                closebtn.click(function() {
                   $(this).parents('div.ov').remove();
                });
             }
          });
       }
    });
comments:

1 : please check what is returned by ajax call in second time. I'm able to perfectly execute it in ff3.5 with firebug.

2 : I was unnecessarily including the jquery library in the php file and that was causing the error. Thank you for testing the script.

3 : BTW the overlay jerks in firefox when I drag it, but not in opera. Any idea why?


---------------------------------------------------------------------------------------------------------------
Id: 1638920
title: Sending USR2 to mongrel_rails sometimes results in an "Address already in use" on the restart
tags: ruby-on-rails, ruby, mongrel, mongrel-cluster
view_count: 246
body:

We have a rolling-restart mode for our mongrel cluster that sends a USR2 signal to each running process.

This works great, most of the time. But very occasionally the mongrel process will shutdown, and then fail to restart, with the following error:

/usr/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel/tcphack.rb:12:in 
 `initialize_without_backlog': Address already in use - bind(2) (Errno::EADDRINUSE)
    from /usr/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel/tcphack.rb:12:in `initialize'
    from /usr/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel.rb:93:in `new'
    from /usr/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel.rb:93:in `initialize'
    from /usr/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel/configurator.rb:139:in `new'
    from /usr/local/lib/ruby/gems/1.8/gems/mongrel-1.1.5/bin/../lib/mongrel/configurator.rb:139:in `listener'

Looking though the mongrel source, the USR2 handler calls a synchronous stop on the running server, so it ought to block until the socket has been released.

Has anyone seen this error?

Does anyone have any ideas what might cause it?

comments:

1 : Are you using mongrel_rails cluster::restart or just sending the USR2 to the processes via some other means?

2 : I'm sending the signal via kill: $ kill -USR2 [mongrel_process_id] This is how we do a rolling restart -- we wait a few seconds before sending the signal to each successive mongrel.


---------------------------------------------------------------------------------------------------------------
Id: 3227710
title: Best way to create a Web Service ON Android
tags: android, web-services, web-applications, android-emulator
view_count: 686
body:

I want to implement a Web Service on Android.. I want to use my device as server. After doing some research on the internet, I found several options:

What is the best?

Alternatively, I could use REST + JSON to implement Web Service on Android? I don't undestand so much what is REST + JSON...

Thanks in advance

Deborah

comments:

1 : Might be difficult. If you can explain what your ultimate goal is, there might be a totally different solution someone can give you?

2 : Hi! I want that one emulator can invoke service that run on another emulator... The service may simply be "Hello World". I am particularly interested in this type of communication. Thanks


---------------------------------------------------------------------------------------------------------------
Id: 3198615
title: Wrote a quick and dirty Brainfuck - interpreter... what could I do better?
tags: c#, interpreter, brainfuck
view_count: 504
body:

So, here is my attempt to write a quick and dirty Brainfuck - interpreter:

/// <summary>
/// This the brainfuck interpreter
/// </summary>
internal sealed class BrainfuckInterpreter
{
    /// <summary>
    /// The "call stack"
    /// </summary>
    private readonly Stack<int> m_CallStack = new Stack<int>();

    /// <summary>
    /// The input function
    /// </summary>
    private readonly Func<byte> m_Input;

    /// <summary>
    /// The instruction set
    /// </summary>
    private readonly IDictionary<char, Action> m_InstructionSet =
        new Dictionary<char, Action>();

    /// <summary>
    /// The memory of the program
    /// </summary>
    private readonly byte[] m_Memory = new byte[32768];

    /// <summary>
    /// The output function
    /// </summary>
    private readonly Action<byte> m_Output;

    /// <summary>
    /// The program code
    /// </summary>
    private readonly char[] m_Source;

    /// <summary>
    /// The data pointer
    /// </summary>
    private int m_DataPointer;

    /// <summary>
    /// The instruction pointer
    /// </summary>
    private int m_InstructionPointer;

    /// <summary>
    /// Constructor
    /// </summary>
    /// <param name="programCode"></param>
    /// <param name="input"></param>
    /// <param name="output"></param>
    public BrainfuckInterpreter(string programCode, Func<byte> input, Action<byte> output)
    {
        // Save the program code
        this.m_Source = programCode.ToCharArray();

        // Store the i/o delegates
        this.m_Input = input;
        this.m_Output = output;

        // Create the instruction set (lol)
        this.m_InstructionSet.Add('+', () => this.m_Memory[this.m_DataPointer]++);
        this.m_InstructionSet.Add('-', () => this.m_Memory[this.m_DataPointer]--);

        this.m_InstructionSet.Add('>', () => this.m_DataPointer++);
        this.m_InstructionSet.Add('<', () => this.m_DataPointer--);

        this.m_InstructionSet.Add('[', () => this.m_CallStack.Push(this.m_InstructionPointer));
        this.m_InstructionSet.Add(
            ']',
            () =>
            {
                var temp = this.m_CallStack.Pop() - 1;
                this.m_InstructionPointer = this.m_Memory[this.m_DataPointer] != 0
                    ? temp
                    : this.m_InstructionPointer;
            });

        this.m_InstructionSet.Add('.', () => this.m_Output(this.m_Memory[this.m_DataPointer]));
        this.m_InstructionSet.Add(',', () => this.m_Memory[this.m_DataPointer] = this.m_Input());
    }

    /// <summary>
    /// Run the program
    /// </summary>
    public void Run()
    {
        // Iterate through the whole program source
        while (this.m_InstructionPointer < this.m_Source.Length)
        {
            // Fetch the next instruction
            char instruction = this.m_Source[this.m_InstructionPointer];

            // See if that IS an instruction and execute it if so
            Action action;
            if (this.m_InstructionSet.TryGetValue(instruction, out action))
            {
                // Yes, it was - execute
                action();
            }

            // Next instruction
            this.m_InstructionPointer++;
        }
    }
}

What would you do different? What could I learn from doing things better / differently?

comments:

1 : At the very least, this question should be CW. @Randy - what?

2 : I think I'm grown up enough - and usually I don't toy around like this, but I have developed an interest in programming language development lately. And I think that creating this quick and dirty interpreter for a Turing - complete language is a good starting point. Next thing I will do is to create an EBNF for it in Irony.NET and then I will try compiling Brainfuck to x86 - assembler (I'm not joking, I already have a few concepts in my mind).

3 : Belongs on Code Review SE. Should be closed as Off Topic, not as Subjective.


---------------------------------------------------------------------------------------------------------------
Id: 2196941
title: Filter fired twice on ajax request
tags: grails, groovy
view_count: 572
body:

I have a filter setup to get executed for all actions and it is executed once per request unless ajax get request is sent to the server. When it's an ajax get request, the filter gets executed twice but I see the browser sending only one request to the server. Is there a way to get the filter to fire only once per request?

Here's how my filter is setup:

class FrontFilters {
   def filters = {
      // filter on all controllers and actions
      first_filter(controller: '*', action: '*') {
         before = {
            println "=>(first_filter), Controller: ${controllerName}, action: ${actionName}, params: ${params}";
            return true;
         }
      }
   }
}

In my demo/index.gsp, I have the following inside the document "head" tag:

<script type="text/javascript">
       $(document).ready(function()
       {
           var url = "http://localhost/filtertest/demo/dutch";
           $.get(url, function(txt) {
                console.log("Hello there. I finished.");
            });
       });
</script>

My action is defined in a controller named 'DemoController':

def index = {
    println "Demo/index action reached";
    render(view: "index");
}

def dutch = {
    log.info("Demo/dutch action reached. Returning text/json render type");
    return render(contentType:'text/json') { 'aPair'('myKey': "myValue") };
}

The server log after http://localhost/filtertest/demo/ is invoked:

=>(first_filter), Controller: demo, action: null, params: [controller:demo]
Demo/index action reached

=>(first_filter), Controller: demo, action: dutch, params: [action:dutch, controller:demo]
Demo/dutch action reached. Returning text/json render type

=>(first_filter), Controller: demo, action: dutch, params: [action:dutch, controller:demo]
Demo/dutch action reached. Returning text/json render type

Note that the 2 lines were generated for one request for the action 'dutch' whereas I was only expecting the 'dutch' action related items to get printed only once.

I don't understand who is initiating the second filter execution.

comments:

1 : You want to see what's going on? Put some real data in your println. How about outputting the controller and action being filtered? My guess is the first hit to /index is generating filter output, followed by the AJAX request's filter output.

2 : Updated the question with better debug output.

3 : Are you sure that you do not have 2 filters defined? It happened to me that 2 filters were defined and therefore 2 lines generated..

4 : Next debug step... use Firebug plugin to track requests being made. Make sure only 2 requests are occurring.

5 : Are you sure the javascript is only being executed once? as Bill suggestedm I would use firebug and look at the HTML generated and the actual number of requests being sent by the browser

6 : I'm certain that the javascript is executed only once. I put in console.log statements before any request invocation. I did however notice that 'referer' header value was empty when the filter invoked the action twice. So based on that, I was able to skip the duplicate.


---------------------------------------------------------------------------------------------------------------
Id: 1743087
title: RegisterClassObjects() Doesn't Find Classes To Register
tags: c++, visual-studio-2008, com, atl, vc6
view_count: 310
body:

I'm in the process of converting an application from Visual Studio C++ 6.0 to Visual Studio 2008 and am running into problems with ATL.

I've been having a whole host of issues, but this is the first call that differs in return values between the two different compilers.

The following line, when compiled with VC++ 6.0, returns S-OK. When running in VS 2008, it returns S-FALSE. According to the MSDN documentation, this means it couldn't find any classes to register.

_Module.RegisterClassObjects(CLSCTX_LOCAL_SERVER | CLSCTX_REMOTE_SERVER, REGCLS_MULTIPLEUSE)

Any help would be greatly appreciated. Thanks!

comments:

1 : That method belongs to ATL. ATL is shipped as full sources. You can just press "Step into" and investigate the problem.

2 : Yea, I've been doing that, but not much has come from it. I've been stepping through the VC++6.0 compiled version and comparing the functions called/return values to that of the VS2008. The functions and parameters are mostly the same, but I haven't been able to figure out how to call the new functions with the parameters that are needed. At this point, I've resolved myself to being stuck in the bowels of COM for a long time... ::sigh::


---------------------------------------------------------------------------------------------------------------
Id: 3047356
title: BluetoothChat problems send message
tags: android, bluetooth
view_count: 621
body:

Hello Can you help me I want to create application ,which can connect Droid and another device with bluetooth I use BluetoothChat as for example to connect Motorola Droid and Nokia N97

They were paired and connect. But when I send message ,connection lost immediatly

How can I solve this problem?


This is my code:

private void sendMessage(String message) {
   // Check that we're actually connected before trying anything
    if (mChatService.getState() != BluetoothChatService.STATE_CONNECTED) {
        Toast.makeText(this, R.string.not_connected, Toast.LENGTH_SHORT).show();
        return;
    }


    // Check that there's actually something to send
    if (message.length() > 0) {
        // Get the message bytes and tell the BluetoothChatService to write
        byte[] send = message.getBytes();
        mChatService.write(send);

        // Reset out string buffer to zero and clear the edit text field
        mOutStringBuffer.setLength(0);
        mOutEditText.setText(mOutStringBuffer);
    }

This is ConnectThread

private class ConnectThread extends Thread {

    private final BluetoothDevice mmDevice;

    public ConnectThread(BluetoothDevice device) {
        mmDevice = device;
        BluetoothSocket tmp = null;

        // Get a BluetoothSocket for a connection with the
        // given BluetoothDevice

        int RFCOMM_CHANEL = 1; //SPP chanel 
        Method m;

            try {
                m = mmDevice.getClass().getMethod("createRfcommSocket", new 
                 Class[] { int.class });
                mmSocket = (BluetoothSocket) m.invoke(mmDevice, 
                         RFCOMM_CHANEL); 


            } catch (SecurityException e) {
                e.printStackTrace();
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InvocationTargetException e) {
                e.printStackTrace();
            }

    }

    public void run() {
        Log.i(TAG, "BEGIN mConnectThread");
        setName("ConnectThread");


        // Always cancel discovery because it will slow down a connection
        mAdapter.cancelDiscovery();

        // Make a connection to the BluetoothSocket
        try {
            // This is a blocking call and will only return on a
            // successful connection or an exception
            mmSocket.connect();
        } catch (IOException e) {
            connectionFailed();
            // Close the socket
            try {
                mmSocket.close();
            } catch (IOException e2) {
                Log.e(TAG, "unable to close() socket during connection failure", e2);
            }
            // Start the service over to restart listening mode
            BluetoothChatService.this.start();
            return;
        }

        // Reset the ConnectThread because we're done
        synchronized (BluetoothChatService.this) {
            mConnectThread = null;
        }

        // Start the connected thread
        connected(mmSocket, mmDevice);
    }

    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) {
            Log.e(TAG, "close() of connect socket failed", e);
        }
    }
}

private class ConnectedThread extends Thread {

    private final InputStream mmInStream;
    private final OutputStream mmOutStream;

    public ConnectedThread(BluetoothSocket socket) {
        Log.d(TAG, "create ConnectedThread");
        mmSocket = socket;
        InputStream tmpIn = null;
        OutputStream tmpOut = null;

        // Get the BluetoothSocket input and output streams
        try {
            tmpIn = socket.getInputStream();

            tmpOut = socket.getOutputStream();
        } catch (IOException e) {
            Log.e(TAG, "temp sockets not created", e);
        }

        mmInStream = tmpIn;
        mmOutStream = tmpOut;

        Log.i("BluetoothChatService","InputStream"+mmInStream);
    }

    public void run() {
        Log.i(TAG, "BEGIN mConnectedThread");
        byte[] buffer = new byte[1024];
        int bytes;

        // Keep listening to the InputStream while connected
        while (true) {
            try {
                // Read from the InputStream
                bytes = mmInStream.read(buffer);


                // Send the obtained bytes to the UI Activity
                mHandler.obtainMessage(BluetoothChat.MESSAGE_READ, bytes, -1, buffer)
                        .sendToTarget();
            } catch (IOException e) {
                Log.e(TAG, "disconnected", e);
                connectionLost();
                break;
            }
        }
    }

    /**
     * Write to the connected OutStream.
     * @param buffer  The bytes to write
     */
    public void write(byte[] buffer) {
        try {
            mmOutStream.write(buffer);

            // Share the sent message back to the UI Activity
            mHandler.obtainMessage(BluetoothChat.MESSAGE_WRITE, -1, -1, buffer)
                    .sendToTarget();
        } catch (IOException e) {
            Log.e(TAG, "Exception during write", e);
        }
    }

    public void cancel() {
        try {
            mmSocket.close();
        } catch (IOException e) {
            Log.e(TAG, "close() of connect socket failed", e);
        }
    }
}

Can you help me to solve this problem?

comments:

1 : Share the code or go google.

2 : What errors do you see in the log (`adb logcat`) when it disconnects?

3 : In the line 435(BluetoothChatService.java) I read bytes: bytes = mmInStream.read(buffer);

4 : This is error 06-25 10:57:25.858: ERROR/BluetoothChatService(6170): disconnected 06-25 10:57:25.858: ERROR/BluetoothChatService(6170): java.io.IOException: Software caused connection abort 06-25 10:57:25.858: ERROR/BluetoothChatService(6170): at android.bluetooth.BluetoothSocket.readNative(Native Method) 06-25 10:57:25.858: ERROR/BluetoothChatService(6170): at android.bluetooth.BluetoothSocket.read(BluetoothSocket.java:286) 06-25 10:57:25.858: ERROR/BluetoothChatService(6170): at android.bluetooth.BluetoothInputStream.read(BluetoothInputStream.java:96)

5 : 06-25 10:57:25.858: ERROR/BluetoothChatService(6170): at java.io.BufferedInputStream.read(BufferedInputStream.java:341) 06-25 10:57:25.858: ERROR/BluetoothChatService(6170): at java.io.FilterInputStream.read(FilterInputStream.java:138) 06-25 10:57:25.858: ERROR/BluetoothChatService(6170): at com.example.android.BluetoothChat.BluetoothChatService$ConnectedThread.run(BluetoothChatService.java:435)


---------------------------------------------------------------------------------------------------------------
Id: 2609379
title: How do I grab the text and formatting from a PDF table with PDFBox?
tags: c#, pdfbox
view_count: 728
body:

Possible Duplicate:
Parsing PDF files (especially with tables) with PDFBox

I am using PDFBox to parse out text using C# from a PDF file. That works fine, but when the parser comes across a table, it parses out the text and destroys the formatting.

How can I parse text from a table but keep the formatting?

comments:

1 : hi did you find a solution?


---------------------------------------------------------------------------------------------------------------
Id: 2780843
title: Problem FlashVars parameter asp.net
tags: asp.net, flex, dynamic, parameters
view_count: 299
body:

Code for asp.net page

<%@ Page Language="VB" AutoEventWireup="false"  CodeFile="trainingupload.aspx.vb"  Inherits="trainingupload" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server">
    <title></title> </head> <body>
    <form id="form1" runat="server">
    <div height>
    <object width="1000" height="800"> <param name="movie" value="player.swf" /> <param name="FlashVars" value='userid=<%=String.Format(getuser())%>" '/> <embed src="bin-release/trainingscentrum.swf" FlashVars='userid=<%=String.Format(getuser())%>" ' width="1500" height="800" /> </embed> </object>
    </div>
    </form> </body> </html>

Code behind

Public Function getuser() As Guid
        Dim user As MembershipUser = Membership.GetUser()
        Dim userid As Guid = (CType(user.ProviderUserKey, Guid))
        Return userid
End Function

In the code above I use an function to return the userid. When I replace <%=String.Format(getuser())%> with an actual userid, I get the value in my flex application. But this code returns nothing. What am I doing wrong?

comments:

1 : still doesn't return anything.

2 : What happens when you use <%= getuser() %>?


---------------------------------------------------------------------------------------------------------------
Id: 2960113
title: Anyone out there using EWDraw
tags: delphi, delphi-2010
view_count: 58
body:

I am working on a project that uses the EWDraw ActiveX componenet and I would like to find out if there are others out there?

comments:

1 : Is this really just a census question?

2 : Please search the site for other questions related to the technology you're using instead of asking poll questions like this. That, or just ask a specific question and see if anyone answers. :)


---------------------------------------------------------------------------------------------------------------
Id: 3291015
title: Solaris OS latest version for i386
tags: operating-system, solaris
view_count: 308
body:

I am running following solaris OS on I386 processors:

$ uname -a SunOS oobleck 5.10 Generic_127128-11 i86pc i386 i86pc $ CC -V CC: Sun C++ 5.8 Patch 121018-11 2007/05/02

I checked on Oracle's web page and it seems that there latest version is Solaris 10 http://www.sun.com/software/solaris/releases.jsp

The instruction set is:

$ isainfo -kv
64-bit amd64 kernel modules

However when I look at the fixpacks available , for solaris 10 it says Solaris OS 5.10 http://developers.sun.com/sunstudio/downloads/patches/ss12_patches.jsp

So I have 2 questions:
1] Does Solaris 10 mean 5.10 ??
2] What is the latest version of OS and fix pack I should upgrade the machine to ?

Any help would be much appreciated .

Thanks

comments:

1 : Belongs on serverfault.com, but yes Solaris 10 = SunOS 5.10, Solaris is just a market term.

2 : cool .. thnx .. didnt knew that website existed. Have posted it there.

3 : @p1, no problem. Hope everything worked out.


---------------------------------------------------------------------------------------------------------------
Id: 3142841
title: Outlook Add-in targeting 2007 & 2010
tags: outlook, outlook-2007, outlook-addin, outlook-2010
view_count: 283
body:

I have an Outlook Add-in that I have developed for Outlook 2007. I am working on having this add-in work on Outlook 2010 as well. My add-in is an adjoining region on the appointment/meeting request window that displays a WPF control. The add-in installs fine on Outlook 2010 but when I go to the appointment/meeting request window I have a blank adjoining region. Any thoughts on what is preventing my WPF control from showing in Outlook 2010?

Thanks

comments:

1 : May be the window hierarchy is completely different in 2007 and 2010.


---------------------------------------------------------------------------------------------------------------
Id: 1477590
title: MaskedEditExtender Is Too Hard to Use For Money
tags: asp.net, javascript, asp.net-ajax, maskedtextbox, maskededitextender
view_count: 2730
body:

The MaskedEditExtender does a good job of enforcing the rules, but my users have trouble typing into its TextBox.

I want to select all the contents of my TextBox when it gains focus.

A regular JavaScript solution does not work.

onfocus="javascript:this.select();"

The MaskedEditExtender interferes.

How can I select all the contents of the TextBox when it gains focus?

<asp:TextBox
    ID="TextBoxPrice"
    runat="server" />
<ajaxToolkit:MaskedEditExtender
    ID="MaskedEditExtenderTextBoxPrice"
    runat="server"
    TargetControlID="TextBoxPrice"
    Mask="9,999.99"
    MaskType="Number"
    MessageValidatorTip="False"
    OnFocusCssClass="MaskedEditFocus"
    OnInvalidCssClass="MaskedEditError"
    InputDirection="RightToLeft"
    AcceptNegative="None"
    DisplayMoney="Left" />
<ajaxToolkit:MaskedEditValidator
    ID="MaskedEditValidatorTextBoxPrice"
    runat="server"
    ControlToValidate="TextBoxPrice"
    ControlExtender="MaskedEditExtenderTextBoxPrice"
    Display="Dynamic"
    IsValidEmpty="False"
    EmptyValueMessage="Price is required"
    InvalidValueMessage="Price is invalid"
    MinimumValue= "0.01"
    MinimumValueMessage="Price is too small"
    MaximumValue="9999.99" 
    MaximumValueMessage="Price is too large" />
comments:

1 : Related forum discussion: http://forums.asp.net/t/1369295.aspx


---------------------------------------------------------------------------------------------------------------
Id: 2053215
title: Syncronize databases
tags: sql, database, synchronization
view_count: 116
body:

I am putting together a site made out of two scripts, with users.

The 2 scripts have info about the members , they will act as one site so I need the users info to be the same on both. When the user fills in the info on the DB1 they should appear in the DB2 as well.

The information fields I would need the same are basic: name, email, phone , website. The edit menu on the second script will be removed, so users can not change data on DB2. So data can come to DB2 only from DB1.

Both databases are on the same server.

comments:

1 : Can you specify which database platform you're using? Some DMBS' contain built-in replication systems for this specific need.

2 : It's a Mysql 5.0.41

3 : Maybe if i use just before each field i need replicated in DB2 a connection that goes to DB1. I found this code ... $dbcnx = @mysql_connect("localhost", "root", "mypasswd"); if (!$dbcnx) { echo( "

Unable to connect to the " . "database server at this time.

" ); exit(); } Is it possible being in DB2 to extract info from DB1 having this code in front of my basic fields : name, email, phone.. ?

4 : I'm not terrifically familiar with MySQL, but would suggest looking for a DMBS based solution rather than code based. A quick search turned up some MySQL documentation that might be a good place to start: http://dev.mysql.com/doc/refman/5.0/en/replication.html

5 : @STW post your comment as an answer. Thanks! ;)


---------------------------------------------------------------------------------------------------------------
Id: 2532787
title: PHP - Rotate a HEX color value (eg swap all colors with "next" hex)
tags: php, colors, hex
view_count: 323
body:

I have a set of hex values in an array in PHP. On my page, I have a slider which the user can "slide" to return a value between 1-100. I want to then, based on this slider value, swap all the colors in the array based on the colors "next" color based on the position in the array. An example of the same sort of thing would be like in photshop where you can rotate the hue of a layer. I want to do the same thing, in PHP, for a hex value.

Any clues?

comments:

1 : You _really_ want to do this with php, i.e. a server roundtrip each time the users moves the slider?

2 : Yes I am asking for the solution in PHP because you cannot update all "colors" on the page with just javascript. OR CAN YOU???

3 : yes you can )))) google "javascript color picker"

4 : and take a look at the demo at http://gusc.lv/jquery/gccolor.html


---------------------------------------------------------------------------------------------------------------
Id: 2742724
title: Function in xcode
tags: iphone
view_count: 269
body:

I have a function which have two global variable 1.temp-a nsmutable array 2.j-a int type variable. But i cant access any global variable inside this function. I'm giving the code sample.

void print( NSArray *array) 
{ 
    NSEnumerator *enumerator = [array objectEnumerator]; 
    id obj;
    while ( nil!=(obj = [enumerator nextObject]) )
    {   
   NSString *tem=[[obj description] cString];   
   [temp insertObject:tem atIndex:j];
   j=j+1;
        printf( "%s\n", [[obj description] cString]); 
    }
}

What should i do to resolve that problem.Looking forward to your response. Thanks in advance..

comments:

1 : Ask a question. You may think that your question is obvious, and perhaps it is to some people. But if you read your post carefully there is no question to be found. Do you want someone to fix your code for you ? Do you want advice on why not to use global variables ? Do you want suggestions on how to do this in C++ ?

2 : Probably because you have not allocated or initialized the NSMutableArray *temp. First, it's strongly discouraged that you use global variables. Second, you should put that code inside a class. Third, use NSLog to print to the console. You can use NSLog(@"%@",array); to log the array's contents.


---------------------------------------------------------------------------------------------------------------
Id: 2201539
title: .Net Remoting: Can the server reference an interface rather than the object?
tags: c#, .net, remoting
view_count: 252
body:

I am using .Net Remoting in an unusual manner whereby a single client will access many servers (this is unavoidable). To increase maintainability, it would be handy to have the server code reference an interface rather than the remoting object itself so that if a change to the remoting object is needed only the client needs to be updated.

Is this possible or is it built in that the server must reference the remote object dll directly? All of the interface examples I have found show how to allow the client to reference an interface (which makes sense as this is how remoting should be used) but I need it the other way around. Any advice or small examples would be appreciated.

Thanks,

James

comments:

1 : Interfaces and objects are two very different things. Do you mean class and not object? Or are you actually talking about switching a concrete instance reference with a ref to an interface type. The latter is asking if you Can use a banana as an aircraft carrier

2 : At the moment both the client and server projects have a reference to the remoting project's dll. What I'd like is for the remoting project to implement an interface so that the server can then reference the dll of the interface rather than the concrete implementation. That way, should the remoting project change, the server project won't need to be updated as it references the interface dll. This seems to be straight forward the other way around - clients can reference an interface dll and the server references the remoting projects dll. But I need the other way! Does this make more sense?


---------------------------------------------------------------------------------------------------------------
Id: 2245165
title: Is it possible to use NHibernate for retrieving data from SP which returns multiple selects?
tags: sql, nhibernate, resultset
view_count: 68
body:

My stored procedure:

CREATE PROCEDURE spSomeStoredProcedure AS
BEGIN
SELECT CategoryName FROM Categories ORDER BY CategoryName
SELECT Top 10 CompanyName FROM Customers ORDER BY CompanyName    
END
GO 

I tried to use ISQLQuery, but List() method returns data only from the first SELECT

comments:

1 : I don't know the answer to your question, but why are you using this stored procedure instead of multiquery/multicriteria?

2 : It is not my stored procedure actually, I've just provided it for example. The real sp I have in the project is much more complex and I don't have enough time to refactor it.


---------------------------------------------------------------------------------------------------------------
Id: 2679693
title: object not found error with dynamic web forms with (jquery) javascript script
tags: javascript, jquery, exception, webforms, dymamic
view_count: 506
body:

In a normal aspx page I've set up a jquery tab system. When a particular tab shows up I wire up an ajax call to get another html page with the following content. It is simply a form with some javascript inside of it.

<!-- demo.htm -->
<form method="post" action="post.aspx">
    <div id="fields">
        Class: <input id="txtclass" name="txtclass" type="text"/>
        Grade: <input id="txtgrade" name="txtgrade" type="text"/>
        <input id="btnupdate" value="Update"/>
    </div>
    <div id="update">
        Reason:<br/>
        <input id="txtreason" name="txtreason" type="text"/>        
        <br/>
        Comments:<br/>
        <textarea id="txtcomments" name="txtcomments"></textarea>
        <br/>
        <input type="button" id="btnsave" value="Save"/>
    </div>

    <script type="text/javascript">
        $(function(){

            //all textboxes should be disabled 
            $('#fields input').each(function(i,j){
                if(! $(this).is(':button') )
                    $(this).attr('disabled', 'disabled')
            }); 


            //update div should be hidden
            $('#update').hide();

            //click event of btnupdate should
            // be set to show the update div contents
            // and enable input fields
            $('#btnupdate').click(function(){

                //enable all textboxes
                $('#fields input').each(function(i,j){
                    $(this).attr('disabled', '');
                });

                //hide btnupdate
                $('#btnupdate').hide();

                //show div update
                $('#update').show();
            });
        });
    </script>
</form>

The script executes normally and the form is shown as intended. The btnupdate is supposed to show the contents in the update div and load the form for accepting user input. Whenever I hit btnupdate button I get an object not found exception on IE 8. IE 8 asks if it should start up its in-built debuggger. But, even in this debugger I cannot see what the problem is...However on clicking "No" in that dialog the button click function executes properly, and the form is displayed as intended. Is there a better way to resolve the problem?

comments:

1 : is it a typo or you're really missing a quote here `$('#update).hide();` ?

2 : @Reigel edited tht...i didn't copy paste the code...this is just a mock up of the original.

3 : I'm guessing btnupdate is missing a type="button" ? I've tried this code in IE 8 and I don't see any JS errors.

4 : Aw trap! Someone had added a function manually in the button's mark up. While migrating the script to jquery we removed that function; and then forgot to make the changes to the button's markup...the browser was trying to look for that function, and hence gave the error "object expected" (or something like that).

5 : if you ppl want to reproduce the error simply edit the markup for the button...add onclick="foo()" (assuming foo() doesn't already exist)


---------------------------------------------------------------------------------------------------------------
Id: 2475170
title: How NOT to skip BOM info (FF FE) when using fread or ifstream?
tags: encoding, iostream, fread, ucs2
view_count: 447
body:

I'm trying to use fread/ifstream to read the first 2 bytes of a .csv with BOM info. But following code always skips the first two bytes (which are 'FF FE'):

ifstream is;
is.open (fn, ios::binary );
char buf[2];
is.read(buf, 2);
is.close();

using FILE*/fread does no better.

comments:

1 : Binary mode shouldn't change the file contents. Are you sure it really has a BOM?

2 : sure. copied in hex from ultraedit: 00000000h: FF FE 73 00 6D 00 73 00 2C 00 73 00 75 00 62 00 ; ??.m.s.,.s.u.b.


---------------------------------------------------------------------------------------------------------------
Id: 2358145
title: Integrated maps (with location markers, etc.) in BlackBerry apps - viable options?
tags: blackberry, android-mapview, blackberry-jde
view_count: 722
body:

I have heard rumors that the use of a MapField or MapView in a BlackBerry app typically presents a problem because carriers such as AT&T and Verizon in the US have locked down the devices so as to not make those API's available or usable. I have three questions:

1) I am new to BlackBerry development. What's the difference between MapField and MapView and their respective availabilities? Are they related or different?

2) Are there actual known carrier restrictions that prevent / prohibit the use of MapField and/or MapView?

3) If there are known carrier issues, what are the best alternatives? So far I've found the following options: a) use of a Browser.Field with Google Static Maps (good suggestions from these StackOverflow questions: How to use Google Map in BlackBerry application? and BlackBerry and map based apps like Yelp and Google Map); b) license the Nutiteq map API library. Any other viable options I might be missing out on?

Thanks for your time in helping out a BlackBerry newbie.

comments:

1 : nutiteq - 2000 euro isn't it too expensive for single app license? I think it is if map functionality is optional, like in some communication or social app

2 : Yes, very expensive, and looking / hoping for alternatives.


---------------------------------------------------------------------------------------------------------------
Id: 1372399
title: How to map this in Fluent.NHibernate
tags: nhibernate, fluent-nhibernate
view_count: 207
body:

I'd like to get this output from fluent.nhibernate

<map name="Dict" table="TABLE">
  <key column="ID_USER" />
  <index-many-to-many column="ID_TABLE" class="TableClass" />
  <element column="COL" type="Int32" />
</map>

where class has:

public class User
{
    public virtual IDictionary<TableClass, int> Dict { get; protected set; } 
}

Closest I've got to is this:

HasMany(x => x.Dict)
         .Table("TABLE")
         .KeyColumn("ID_USER")
         .AsMap<TableClass>("ID_TABLE")
         .Element("COL");

And the output for that is:

<map name="Dict" table="TABLE">
  <key>
    <column name="ID_USER" />
  </key>
  <index type="TableClass">
    <column name="ID_TABLE" />
  </index>
  <element type="Int32">
    <column name="COL" />
  </element>
  <one-to-many class="Int32" /> <!-- BUG -->
</map>

How can I remove the last line (marked with BUG)?

It's not always needed (like in my example it isn't)!

comments:

1 : Same problem here: http://stackoverflow.com/questions/1360976/fluent-code-for-mapping-an-idictionarysomeentity-int


---------------------------------------------------------------------------------------------------------------
Id: 1298293
title: word document open and work on document events throw an error
tags: ms-word
view_count: 1755
body:

i am open word document using word(Word 11.0 library , version 8.3) reference. it opens fine. And then i am working on Document events (like DocumentBeforeprint , documentbeforesave ..).at the time the word document DocumentBeforeprint event parameter word.Document DOC throws An error.

error is function evaluation time out.

my code is

// Global Diclaration of Word object

    Word.ApplicationClass oWordApp = new Word.ApplicationClass();
    Word.Document oWordDoc;        
    object readOnlytrue = true;
    object readOnlyfalse = false;
    object isVisible = true;
    object password = "abc";
    object Count = 200;
    object missing = System.Reflection.Missing.Value;

    private void CreatePdf(string strSeverPath)
    {
        object fileName = strSeverPath;
        object temp = WdTemplateType.wdNormalTemplate;
        object newtemp = false;
        object doctype = WdDocumentType.wdTypeTemplate;
        object visbule = true;
        //oWordDoc = oWordApp.Documents.Add(ref fileName, ref missing, ref missing, ref missing);
        oWordDoc = oWordApp.Documents.Open(ref fileName,
                                   ref missing, ref readOnlytrue,
                                   ref missing, ref missing, ref missing,
                                   ref missing, ref missing, ref missing,
                                   ref missing, ref missing, ref isVisible,
                                   ref missing, ref missing, ref missing, ref missing);
        oWordDoc = oWordApp.ActiveDocument;
        oWordDoc.CommandBars.ActiveMenuBar.Enabled = true;
        oWordDoc.ActiveWindow.Application.CommandBars["Standard"].Visible = true;
        oWordDoc.ActiveWindow.Application.CommandBars["Frames"].Enabled = false;
        oWordDoc.ActiveWindow.Application.CommandBars["Forms"].Enabled = false;
        oWordDoc.ActiveWindow.Application.CommandBars["Picture"].Enabled = false;
        oWordDoc.ActiveWindow.Application.CommandBars["Visual Basic"].Enabled = false;
        oWordDoc.ActiveWindow.Application.CommandBars["Web"].Enabled = false;
        oWordDoc.ActiveWindow.Application.CommandBars["Web Tools"].Enabled = false;
        oWordDoc.ActiveWindow.Application.CommandBars["WordArt"].Enabled = false;
        oWordDoc.ActiveWindow.Application.CommandBars["Reading Layout"].Enabled = false;
        oWordDoc.ActiveWindow.Application.CommandBars["Reviewing"].Enabled = false;
        oWordDoc.ActiveWindow.Application.CommandBars["Formatting"].Enabled = false;
        oWordDoc.ActiveWindow.Application.CommandBars["Drawing"].Enabled = false;

        //INSERTING TEXT IN THE CENTRE RIGHT, TILTED AT 90 DEGREES
        oWordApp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageHeader;
        Word.Shape midRightText;

        midRightText = oWordApp.Selection.HeaderFooter.Shapes.AddTextEffect(
            Microsoft.Office.Core.MsoPresetTextEffect.msoTextEffect1,
            "Display Copy", "Arial", (float)40,
            Microsoft.Office.Core.MsoTriState.msoTrue,
            Microsoft.Office.Core.MsoTriState.msoFalse,
            0, 0, ref missing);
        //FORMATTING THE SECURITY CLASSIFICATION TEXT
        midRightText.Select(ref missing);
        midRightText.Name = "PowerPlusWaterMarkObject2";            
        midRightText.Fill.Visible = Microsoft.Office.Core.MsoTriState.msoTrue;
        midRightText.Line.Visible = Microsoft.Office.Core.MsoTriState.msoFalse;
        midRightText.Fill.Solid();
        midRightText.Fill.ForeColor.RGB = (int)Word.WdColor.wdColorGray375;
        midRightText.ZOrder(Microsoft.Office.Core.MsoZOrderCmd.msoBringToFront);
        //MAKING THE TEXT VERTICAL & ALIGNING
        midRightText.Rotation = (float)-45;
        midRightText.Fill.Transparency = 0.6f;
        midRightText.RelativeHorizontalPosition =
            Word.WdRelativeHorizontalPosition.wdRelativeHorizontalPositionMargin;
        midRightText.RelativeVerticalPosition =
            Word.WdRelativeVerticalPosition.wdRelativeVerticalPositionMargin;
        midRightText.Top = (float)Word.WdShapePosition.wdShapeCenter;
        midRightText.Left = (float)Word.WdShapePosition.wdShapeCenter;
        midRightText.Height = oWordApp.InchesToPoints(2f);
        midRightText.Width = oWordApp.InchesToPoints(5f);
        int i = midRightText.ID;

        //SETTING FOCUES BACK TO DOCUMENT
        oWordApp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;

        if (oWordDoc.ProtectionType == Word.WdProtectionType.wdNoProtection)
        {
            oWordDoc.Protect(Word.WdProtectionType.wdAllowOnlyFormFields, ref missing, ref password, ref missing, ref isVisible);
        }

        //unprotect
        //oWordDoc.Unprotect(ref password);

        oWordApp.DocumentBeforePrint += new Word.ApplicationEvents4_DocumentBeforePrintEventHandler(oWordApp_DocumentBeforePrint);
        oWordApp.DocumentBeforeClose += new ApplicationEvents4_DocumentBeforeCloseEventHandler(oWordApp_DocumentBeforeClose);
        oWordApp.DocumentBeforeSave += new ApplicationEvents4_DocumentBeforeSaveEventHandler(oWordApp_DocumentBeforeSave); 
        oWordApp.DocumentChange += new ApplicationEvents4_DocumentChangeEventHandler(oWordApp_DocumentChange);

        //oWordDoc.ActiveWindow.Application.CommandBars["File"].Enabled = true; 
        //oWordDoc.ActiveWindow.Application.CommandBars["File"].FindControl(missing, 18, missing, missing, missing).Enabled = true;
        //oWordDoc.ActiveWindow.Application.CommandBars["File"].FindControl(missing, 4, missing, missing, missing).Enabled = true;
        //oWordDoc.ActiveWindow.Application.CommandBars["File"].FindControl(missing, 3, missing, missing, missing).Enabled = true;            
        ////oWordDoc.ActiveWindow.Application.CommandBars["File"].FindControl(missing, 5, missing, missing, missing).Enabled = false;
        //object i = 3;            
        //oWordDoc.ActiveWindow.Application.CommandBars["Standard"].FindControl(missing, i, missing, missing,missing).Visible = true;           
       // oWordDoc.CommandBars.ActiveMenuBar.FindControl(missing, 1, missing, missing, missing).OnAction.Remove(1); 

        string ac = oWordDoc.ActiveWindow.Application.CommandBars["File"].FindControl(missing, 3, missing, missing, missing).Id.ToString();// = Microsoft.Office.Core.MsoControlOLEUsage.msoControlOLEUsageNeither; 
        oWordDoc.Saved = true;
        oWordApp.Visible = true;
        oWordDoc.Activate();

    }
    private void documentSettings()
    {
       oWordDoc.PageSetup.BottomMargin = 0;
       oWordDoc.PageSetup.TopMargin = 40f;
       oWordDoc.PageSetup.FooterDistance = 0.4f;
       oWordDoc.PageSetup.FooterDistance = 0.4f;
    }


    void oWordApp_DocumentChange()
    {
        //throw new NotImplementedException();
       // string abc = oWordDoc.Path.ToString();
       //if(oWordDoc.Path.ToString() == @" C:\Documents and Settings\11608\My Documents\Visual Studio 2008\Projects\StandardOperatingProcedure\StandardOperatingProcedure\Documents\Annexures")
       //{

       //}
    }

    protected void oWordApp_DocumentBeforeClose(Word.Document Doc, ref bool Cancel)
    {
        oWordDoc.Close(ref missing, ref missing, ref missing);
        oWordApp.Quit(ref missing, ref missing, ref missing);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(oWordApp);
        System.Runtime.InteropServices.Marshal.ReleaseComObject(oWordDoc);                      
    }       

    protected void oWordApp_DocumentBeforePrint(Word.Document Doc, ref bool Cancel)
    {
        try
        {
            oWordDoc = oWordApp.ActiveDocument;

            oWordDoc.Unprotect(ref password);

            oWordApp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;
            oWordApp.ActiveWindow.Application.Selection.WholeStory();
            string strtext = "Printed By : " + Session["UserID"].ToString() + "  -  " + DateTime.Now.ToString("dd/MM/yyyy");
            string abc = oWordApp.ActiveWindow.Selection.Text;
            if (abc.Contains(strtext))
            {

            }
            else
            {
                // Remove WaterMark

                oWordApp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageHeader;
                Word.ShapeRange midRightText;
                object name = "PowerPlusWaterMarkObject2";
                midRightText = oWordApp.Selection.HeaderFooter.Shapes.Range(ref name);
                midRightText.Delete();
                oWordApp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;

                // Remove WaterMark  

                oWordApp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;
                //oWordDoc.PageSetup.BottomMargin = 0;
                ////oWordDoc.PageSetup.TopMargin = 0.10f;
                //oWordDoc.PageSetup.FooterDistance = 0.4f;
                documentSettings();


                oWordApp.Selection.TypeParagraph();

                oWordApp.Selection.MoveDown(ref missing, ref Count, ref missing);
                oWordDoc.ActiveWindow.Application.Selection.EndKey(ref missing, ref missing);
                oWordApp.ActiveWindow.Selection.TypeText("\n");
                oWordApp.ActiveWindow.Selection.TypeText("\n");
                oWordApp.ActiveWindow.Selection.Font.Name = "Arial";
                oWordApp.ActiveWindow.Selection.Font.Size = 12;
                if (Session["UserID"] != null)
                {
                    oWordApp.ActiveWindow.Selection.TypeText("Printed By : " + Session["UserID"].ToString() + "  -  " + DateTime.Now.ToString("dd/MM/yyyy"));
                    oWordApp.ActiveWindow.Selection.TypeText("\t");
                    oWordApp.ActiveWindow.Selection.TypeText("\t");
                    //oWordApp.ActiveWindow.Selection.TypeText("\t");
                    Word.InlineShape CustLogo;
                    //String logoPath = "D:\\Malyadri\\Refresh.gif";
                    string strSecurityLogoPath = Server.MapPath(string.Empty);

                    strSecurityLogoPath = strSecurityLogoPath + "\\Images\\Security_img4.gif";
                    //object fileName = strSeverPath
                    //String logoPath = 

                    CustLogo = oWordApp.ActiveWindow.Selection.InlineShapes.AddPicture(strSecurityLogoPath, ref missing, ref missing, ref missing);
                    string type = CustLogo.Type.ToString();
                    CustLogo.Select();
                    CustLogo.AlternativeText = "PowerPlusInlineObject2";
                    SqlConnection conn = new SqlConnection();
                    conn.ConnectionString = "server=APLU7-DSK-057; user id=sa; password=password123; database =DisplaySops";
                    conn.Open();
                    string date2 = DateTime.Now.ToString("dd/MM/yyyy");
                    string AnneID2 = ViewState["AnnexureID"].ToString();
                    SqlCommand cmd2 = new SqlCommand("UPDATE [DisplaySops].[dbo].[TBL_ANNEXURE] SET [PRINTEDBYDATE] = '" + DateTime.Now + "' where [ANNEXUREID] ='" + AnneID2 + "'", conn);
                    cmd2.ExecuteNonQuery();
                    //oWordDoc.PageSetup.FooterDistance = 0.2f;
                }
            }


            /* if (oWordApp.ActiveWindow.Selection.Text == "\r")
             {                
                 oWordApp.ActiveWindow.Selection.MoveDown(ref missing, ref Count, ref missing);
                 oWordDoc.ActiveWindow.Application.Selection.EndKey(ref missing, ref missing);

                 if (oWordApp.ActiveWindow.Selection.Text == "P")
                 {
                     string AnneID = ViewState["AnnexureID"].ToString();
                     string strPrientedByDate = string.Empty;
                     oWordDoc.PageSetup.BottomMargin = 0;
                     oWordDoc.PageSetup.TopMargin = 0;
                     SqlConnection conn = new SqlConnection();
                     conn.ConnectionString = "server=APLU7-DSK-057; user id=sa; password=password123; database =DisplaySops";
                     conn.Open();
                     SqlCommand cmd = new SqlCommand("select PRINTEDBYDATE from TBL_ANNEXURE where ANNEXUREID = '" + AnneID + "'", conn);
                     DateTime date1 = Convert.ToDateTime(cmd.ExecuteScalar());
                     strPrientedByDate = date1.ToString("dd/MM/yyyy");

                     foreach (Word.Range tmpRange in oWordDoc.StoryRanges)
                     {
                         // Set the text to find and replace
                         string strtext = "Printed By : " + Session["UserID"].ToString() + "  -  " + strPrientedByDate;
                         tmpRange.Find.Text = strtext;
                         //string date1 = DateTime.Now.ToString("dd/MM/yyyy");
                         string AnneID1 = ViewState["AnnexureID"].ToString();
                         try
                         {
                             SqlCommand cmd1 = new SqlCommand("UPDATE [DisplaySops].[dbo].[TBL_ANNEXURE] SET [PRINTEDBYDATE] = '" + DateTime.Now + "' where [ANNEXUREID] ='" + AnneID1 + "'", conn);
                             cmd1.ExecuteNonQuery();
                         }
                         catch (Exception ex)
                         {
                             continue;
                         }
                         string strReplaceText = "Printed By : " + Session["UserID"].ToString() + "  -  " + DateTime.Now.ToString("dd/MM/yyy");
                         tmpRange.Find.Replacement.Text = strReplaceText;

                         // Set the Find.Wrap property to continue (so it doesn't
                         // prompt the user or stop when it hits the end of
                         // the section)
                         tmpRange.Find.Wrap = Word.WdFindWrap.wdFindContinue;

                         // Declare an object to pass as a parameter that sets
                         // the Replace parameter to the "wdReplaceAll" enum
                         object replaceAll = Word.WdReplace.wdReplaceAll;

                         // Execute the Find and Replace -- notice that the
                         // 11th parameter is the "replaceAll" enum object
                         tmpRange.Find.Execute(ref missing, ref missing, ref missing,
                             ref missing, ref missing, ref missing, ref missing,
                             ref missing, ref missing, ref missing, ref replaceAll,
                             ref missing, ref missing, ref missing, ref missing);
                     }              
                 }
                 else
                 {
                     // Remove WaterMark

                     oWordApp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageHeader;
                     Word.ShapeRange midRightText;
                     object name = "PowerPlusWaterMarkObject2";
                     midRightText = oWordApp.Selection.HeaderFooter.Shapes.Range(ref name);
                     midRightText.Delete();
                     oWordApp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;

                     // Remove WaterMark  

                     oWordApp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekCurrentPageFooter;
                     oWordDoc.PageSetup.BottomMargin = 0;
                     oWordDoc.PageSetup.TopMargin = 0;  

                     oWordApp.Selection.TypeParagraph();
                     int i = oWordApp.Selection.Paragraphs.Count;

                     oWordApp.Selection.MoveDown(ref missing, ref Count, ref missing);
                     oWordDoc.ActiveWindow.Application.Selection.EndKey(ref missing, ref missing);
                     oWordApp.ActiveWindow.Selection.TypeText("\n");
                     oWordApp.ActiveWindow.Selection.Font.Name = "Arial";
                     oWordApp.ActiveWindow.Selection.Font.Size = 12;

                     if (Session["UserID"] != null)
                     {
                         oWordApp.ActiveWindow.Selection.TypeText("Printed By : " + Session["UserID"].ToString() + "  -  " + DateTime.Now.ToString("dd/MM/yyyy"));
                         oWordApp.ActiveWindow.Selection.TypeText("\t");
                         oWordApp.ActiveWindow.Selection.TypeText("\t");                        
                         Word.InlineShape CustLogo;
                         String logoPath = "D:\\Malyadri\\Refresh.gif";                        
                         CustLogo = oWordApp.ActiveWindow.Selection.InlineShapes.AddPicture(logoPath, ref missing, ref missing, ref missing);
                         string type = CustLogo.Type.ToString();
                         CustLogo.Select();
                         CustLogo.AlternativeText = "PowerPlusInlineObject2";                        

                         SqlConnection conn = new SqlConnection();
                         conn.ConnectionString = "server=APLU7-DSK-057; user id=sa; password=password123; database =DisplaySops";
                         conn.Open();
                         string date2 = DateTime.Now.ToString("dd/MM/yyyy");
                         string AnneID2 = ViewState["AnnexureID"].ToString();
                         SqlCommand cmd2 = new SqlCommand("UPDATE [DisplaySops].[dbo].[TBL_ANNEXURE] SET [PRINTEDBYDATE] = '" + DateTime.Now + "' where [ANNEXUREID] ='" + AnneID2 + "'", conn);
                         cmd2.ExecuteNonQuery();                   

                     }                                      
                 }                
             } */

            oWordDoc.PrintRevisions = true;
            oWordApp.ActiveWindow.ActivePane.View.SeekView = Word.WdSeekView.wdSeekMainDocument;
            if (oWordDoc.ProtectionType == Word.WdProtectionType.wdNoProtection)
            {
                oWordDoc.Protect(Word.WdProtectionType.wdAllowOnlyFormFields, ref missing, ref password, ref missing, ref isVisible);
            }
            oWordDoc.Saved = true;
            oWordDoc.Activate();

        }
        catch (Exception ex)
        {

        }                     

    }

please give solution

Cheers

Malyadri.

comments:

1 : At least you could have cut out that massive section of code which is commented out.

2 : Is this the same as http://stackoverflow.com/questions/1305363? Or different?


---------------------------------------------------------------------------------------------------------------
Id: 2441031
title: What kind of events should be created for a CRUD application?
tags: events, repository-pattern, crud
view_count: 84
body:

I have an application that is centered around a database (ORM is LINQ-SQL) that has a table called Assignment. I am using the repository pattern to manipulate the database. My application is basically going to perform CRUD operations. I am new to delegates and events and I am asking you what events I should create (like maybe AssignmentCreating, AssignmentCreated) and what kind of delegate to use (like maybe a custom delegate or just an EventHandler)? UPDATE: My application has a ListView with some columns that show some data. On the right side, I have a panel with textboxes binded to the values of the currently selected assignment. Like a textbox for Score, one for title, etc. and they are all editable. That deals with the Read and Update. Then I have a custom dialog box that has the same kinds of textboxes, and the dialog Creates new assignments. Then users can just select an assignment and Delete it via the Delete button, or a context menu.

comments:

1 : Can you talk a bit about in which ways the application will react to the events from the CRUD operations on Assignment?

2 : Check the update. I talk about my application and the CRUD operations it performs.


---------------------------------------------------------------------------------------------------------------
Id: 1795803
title: uiview flip from top
tags: iphone, objective-c, xcode
view_count: 411
body:

how to flip a uiview from top/bottom using uiviewanimation ? Does anyone have any ideas how this can be accomplished?

comments:

1 : This appears to be a duplicate of this question: http://stackoverflow.com/questions/632480/flipping-uiviews-from-top-bottom

2 : i need uiviewanimation not catransition or layer animations.


---------------------------------------------------------------------------------------------------------------
Id: 1611233
title: Does X509Certificate2 functionality exist in VBA?
tags: vba, x509certificate2
view_count: 187
body:

I have a VBA application that returns an HTTPS file but it stops to ask for the Certificate.

C# has this code:

Dim wr As HttpWebRequest = CType(WebRequest.Create("https://www.xxx.net?RunDate=2009-09-29"), HttpWebRequest)
wr.ClientCertificates.Add(New System.Security.Cryptography.X509Certificates.X509Certificate2(myCert, myCertPW))

Is there a function call that exists in VBA that has the above X509Certificate2 functionality? Thank you. gerard

comments:

1 : If your office is 2007 you might be able to use .NET.

2 : Unfortunately we are Office 2003. We are exploring shell out to call a .NET application from which I copied the above two lines. That application will return the file and then we can process it. I was hoping to stay within the Office 2003 environment. Thank you for your excellent idea.


---------------------------------------------------------------------------------------------------------------
Id: 2963237
title: Selecting row in SSMS causes Entity Framework 4 to Fail
tags: sql-server-2008, entity-framework-4
view_count: 49
body:

I have a simple Entity Framework 4 unit test that creates a new record, saves it, attempts to find it, then deletes it. All works great, unless...

... I open up SQL Server Management Studio while stopped at a breakpoint in the unit test and execute a SELECT statement that returns the row I just created (not SELECT FOR UPDATE, not WITH (updlock), no transaction, just a plain SELECT).

If I do that before attempting to find the row I just created, I don't find the row. If I instead do that after finding the row but before deleting the row, I do find the row but get an OptimisticConcurrencyException.

This is consistently repeatable.

Unit Test:

[TestMethod()]
public void CreateFindDeleteActiveParticipantsTest()
{
    // Setup this test
    Participant utPart = CreateUTParticipant();

    ctx.Participants.AddObject(utPart);
    ctx.SaveChanges();

    // External SELECT Point #1:
    // part is null

    // Find participant
    Participant part = ParticipantRepository.Find(UT_SURVEY_ID, UT_TOKEN);
    Assert.IsNotNull(part, "Expected to find a participant");

    // External SELECT Point #2: 
    // SaveChanges throws OptimisticConcurrencyException

    // Cleanup this test
    ctx.Participants.DeleteObject(utPart);
    ctx.SaveChanges();
}
comments:

1 : Out of curiosity, why do you have a test like this? It mostly tests the Entity Framework itself, which Microsoft will thoroughly test for you. And it also has a database dependency, which is bad in many ways.

2 : @Matt: First off, the test failed so probably good that I had it. But mostly that was the setup and tear down of a more complex test. I distilled down the full test for SO.

3 : @Eric: Fair enough. I was being honest with the question, not sarcastic.

4 : IMHO: This sounds like a SQL Server issue, not an EF issue. Profile what the EF is doing, and reproduce it with two copies of SSMS.

5 : @Matt: Didn't mean to imply you were being sarcastic :-) My intent with the test is really to prove that EF works as I expect it to, especially since I have encountered a lot of weirdness with it since starting to dig in for the past week.

6 : @Craig: Could be SQL Server. I'll add that tag in case a SQL Server guru has seen that behavior. Will profile but won't have a chance to do that until tonight. Still, if this type of behavior happened with non-EF CRUD patterns it would probably have been noticed as a glaring issue long ago.

7 : I *do* see some of these issues in SQL Server when not using RLV: http://msdn.microsoft.com/en-us/library/ms179599.aspx


---------------------------------------------------------------------------------------------------------------
Id: 3258595
title: Connect android to local Lan via Phone (Over wifi OR via USB connection)
tags: android, networking, video-streaming, lan, rtsp
view_count: 1122
body:

I am playing about with RTSP in Android, getting it to stream using Media Player. Now I am wanting to test them locally, but finding it incredibly difficult.

What I have done is run a local Wowza server and published the RTSP url and I am then entering that URL into the android api demos MediaPlayerDemo.java. However, because it will not work on the emulator I have to debug this on my phone (HTC Hero 1.5) BUT I can not get my Hero to see my network in anyway.

Of course I can not use the 10.0.2.2 because that is for the emulator. I have also used the IP address of my computer and my other computer on the network but that doesn't either.

How do I get my Hero to see my network so I can test the RTSP streaming ? I've tried connecting via USB and also connecting to my wifi router, but neither work.

Regards Anthoni

comments:

1 : Is your phone on the same wifi segment as the Wowza server?

2 : try posting this question on superuser Q&A website (also by Stack Exchange). Your question is not related to software development... you wanna setup your network and then you can test your app.

3 : Are you sure there's no firewall on your computer preventing the connection?


---------------------------------------------------------------------------------------------------------------
Id: 2330717
title: How do I some basic file I/O and run a quick XML query in PHP?
tags: php, shell
view_count: 45
body:

I need to run a complex series of commands in PHP, and I'm not sure about exactly how to do it. We have two executables we need to work with:

There are basically 5 steps:

  1. First, system("generate ... > fruits.xml", $returnValue);.

  2. Next, load the resulting XML from fruits.xml file.

  3. Run the XPath query '//fruits/fruit/@id' on this file.

  4. For each identifier in the results of this query, call system("peel --fruit-id=$fruit_id > $fruit_id.txt").

  5. Concatenate all of the $fruit_id files into one large file, where each entry is separated with ***.

I assume SimpleXMLElement is the way to go here for the XML querying in step 3, but I'm a little stumped about how to pull off the tasks in the other points. Any thoughts?

comments:

1 : Okay, I'll bite. WHY do you *need* to run this in PHP?

2 : @Ignacio: Sorry, it was 9 PM my time when you sent this so I didn't see it till just now. I'm writing it in PHP because of environment restrictions: the PHP executable has full permissions, but arbitrary `cmd` processes don't. It's silly, but I don't have organizational control over the box where this runs. Such is the enterprise.


---------------------------------------------------------------------------------------------------------------
Id: 2719198
title: WCF identity when moving from dev to prod. environment
tags: java, .net, wcf, web-services
view_count: 137
body:

I have a web service developed with WCF. In the development environment the endpoint has the following identity section under the endpoint configuration.

<identity>
    <dns value="myservice.devdomain.local" />
</identity>

myservice.devdomain.local is the dns name used to reach the development version of the service.

The binding used is:

<basicHttpBinding>
    <binding name ="myBinding">
        <security mode ="TransportCredentialOnly">
            <transport clientCredentialType="Windows"/>
        </security>
    </binding>
</basicHttpBinding>

I am about to put this into production. The binding will be the same, but the address will be a new production address myservice.proddomain.local. I have planned to change the dns value in the configuration to myservice.proddomain.local in the production environment. However this MSDN article on WCF Identity makes me worried about the impact on the clients when I change the identity.

There are two clients - one .NET and one Java using this service. Both of those have been developed against the dev instance of the service. The idea is to just reconfigure the endpoint used by the clients, without reloading the WSDL. But if the identity is somehow part of the WSDL and the identity changes when deploying to prod that might not work.

Will the new identity in the prod version cause issues for the clients that were developed using the dev wsdl? Do the Java and the .NET clients handle this differently?

comments:

1 : Java clients are running on windows environment right? Make sure the users have rights on the new Domain, by default they all must be on the same Domain. You can override that by: > client.ClientCredentials.Windows.ClientCredential.Domain > = domain; client.ClientCredentials.Windows.ClientCredential.UserName > = userName; client.ClientCredentials.Windows.ClientCredential.Password > = pswd; Thanks, Sebastian

2 : For the Service side: that will depend if you are hosting a Windows Service, IIS or Custom Services The most useful is WAS (IIS7). If you enable Windows security, by default anyone that has rights on the Domain where the service resides it will have rights to run the Services. You can lock down security by creating groups and assigning the groups to the Service in IIS Thanks, Sebastian


---------------------------------------------------------------------------------------------------------------
Id: 2183661
title: Programmatically retrieve requested protocol with c# from web farm load balanced with ISA
tags: c#, iis7, ssl, webfarm, isa
view_count: 152
body:

Scenario: The infrastructure that a website is built on consists of a web farm fronted with ISA servers, these ISA servers terminate the SSL of any given website and the requests between the ISA server and the IIS7 servers are always over port 80 (http).

Therefore: Customer > [https] > ISA > [http] > WebFarm(IIS)

Question: Is it possible to retrieve the protocol information from the original request (from customer to ISA) in C# because IIS will always think that the request is being made over http (as it is).

I could obviously do this using javascript but for various reasons (when the information is required in the page lifecycle etc.) I want to be able to do it prior to rendering/presentation.

My thoughts: It feels to me like some information might have to be added to the header information while being passed through ISA to IIS.

comments:

1 : Please ask sysadmin related questions on serverfault.com, as stackoverflow.com is reserved for programming related questions.

2 : Well at this stage it is a programming question. If it is concluded that this cannot be achieved with programming alone then I'll ping it over there for stage two.


---------------------------------------------------------------------------------------------------------------
Id: 1567627
title: How to create annotation on filtered data in Django ORM?
tags: django, django-orm, django-aggregation
view_count: 136
body:

I have the following models:

class ApiUser(models.Model):
    apikey = models.CharField(max_length=32, unique=True)


class ExtMethodCall(models.Model):
    apiuser = models.ForeignKey(ApiUser)
    method  = models.CharField(max_length=100) #method name
    units   = models.PositiveIntegerField()    #how many units method call cost
    created_dt = models.DateField(auto_now_add=True)

For report, i need to get all users who made any call today and total cost of all calls for each user.

In SQL, that would be something like:

SELECT apiuser.*, q1.total_cost
FROM apiuser INNER JOIN (
    SELECT apiuser_id, sum(units) as total_cost
    FROM extmethodcall
    WHERE create_dt = curdate()
    GROUP by apiuser_id
) USING apiuser_id

So far, i have found the following solution:

models.ExtMethodCall.objects.filter(created_dt=datetime.date.today()).values('apiuser').annotate(Sum('units'))

which returns me apiuser_id and units__sum.

Is there any more intelligent solution?

comments:

1 : What's wrong with the solution you've given?

2 : it is not obvious as for me. actually i googled it.


---------------------------------------------------------------------------------------------------------------
Id: 2502139
title: Problem with date_select when using :discard option. (Rails)
tags: ruby-on-rails, forms, select, date, multi-model-forms
view_count: 399
body:

I'm using a date_select with the option :discard_year => true

If a user selects a date in the date select, and then he comes back and returns the select to the prompt values of Month and Day, Rails automatically sets the select values to January 1.

I know this is the intended functionality if a month is selected and a day is left blank, but that's not the case here. In my example, the user sets both the month and day back to the prompt. By Rails forcing January 1, I'm getting bad results.

I've tried every parameter available in the api. :default => nil, :include_blank => true. None of those change the behavior I'm describing.

I've isolated the root of the problem, which is this:

Because I'm discarding the :year parameter, when the user tries to return the month and day to the prompt values, Rails doesn't see an empty prompt select. It perhaps sees a year selected with empty month and day, which it then sets to January 1. This is the case because the :discard_year parameter does in fact set a date in the database, it just removes it from the view.

How can I code around this problem?

comments:

1 : Do you want the date to be saved as nil when the user returns "the month and day to the prompt values"?

2 : Thanks for the question. Yes. If the user returns the select to the prompt value, then the fields should go back to nil.


---------------------------------------------------------------------------------------------------------------
Id: 3275011
title: Visual Studio 2010 crashed, after loading it again it opened the conversion wizard then some bad things happened
tags: visual-studio-2010, crash
view_count: 88
body:

I was using Visual Studio 2010 and tried to go to a files definition, after about three minutes I found the application had crashed so I end-tasked it. Running the project again I was presented with the conversion wizard (the project was already in 2010 so that was a bit wierd), after going through all its steps it said the conversion had ocmpleted. But I found most of my program directories had vanished and some of the src/include files were not included under the source files/header files sections of the project.

After fixing up all the errors and compiling and running successfully I discovered something new: When it crashed the callstack would not take me to the function but rather the Disassembly of it, but only in some cases.

So for some classes which have a destructor I'm taken to the disassembly location of the destructor even though the function is actually defined and exists, for others it takes me to the source files destructor.

How can I make it so only the source version of the destructor is displayed on the callstack?

comments:

1 : Are you compiling in Debug mode?

2 : Yes, definitely. I also checked the debug build settings to make sure there was no optimizations going on which would break debugging.


---------------------------------------------------------------------------------------------------------------
Id: 2785806
title: SubSonic missing stored procedures in StoredProcedures.cs when generated with SubCommander sonic.exe
tags: sql-server, stored-procedures, subsonic, method-missing
view_count: 159
body:

We have been using SubSonic to generate our DAL with a lot of success on VS2005 and SubSonic Tools 2.0.3.

SubSonic Tools do not work on VS2008 (as far as we can work out) so we have tried to use SubCommander\sonic.exe and are now hitting some problems.

When we regenerate the project using SubCommander\sonic.exe and try to compile we get some errors reporting missing members (which should have been automatically generated based on the stored procedures we have).

On closer inspection it looks like my StoredProcedures.cs file is missing some (not all) automatically generated methods for my classes.

As an example, I have 2 procs: [dbo]._ClassA_Func1 [dbo]._ClassA_Func2

Only one of these is being generated in the StoredProcedures.cs file.

These methods generate fine using the SubSonic Tools plugin. We have tried now with versions 2.1 and 2.2 of SubSonic with the same issue. We are still on .NET 2.0 so cannot use SubSonic 3.0.

I have checked the permissions of both procs using fn_my_permissions and they seem identical.

Does anyone have any ideas on what I can check?

Thanks -- Mark

comments:

1 : Mark I use Subsonic 2 on VS2008 and now on VS2010 with dotnet 4 after I compiled for net 4, and have not problems with store procedures. And I never move on 3 because is too slowwww... I suggest to attact the source code of subsonic on your project and compile it by your self, learn it a but, and debug to see why this store procedure is not readed when they make the generation.

2 : Thanks Aristos. I think compiling it and stepping through it is a great idea. I will try that. If I find anything interesting I will post a follow-up here. Cheers - Mark


---------------------------------------------------------------------------------------------------------------
Id: 1815543
title: Is there a CPAN module that allows me to manage errors ids and i18n error messages and integrates with Exception::Class or Error?
tags: perl, exception-handling, cpan
view_count: 68
body:

I am looking for a CPAN module that will allow me to store possible exceptions/errors in a database and internationalize my error messages. Currently I have subclassed Exception::Class but its a bit of a hack and I would like to use something that is production quality. It would be great if it integrates with Exception::Class or even Error.

comments:

1 : I don't know of one, but seems like you wouldn't have that much work to do to clean up and publish your "hack".

2 : More context might be useful are these cgi scripts running under Apache? A perl daemon with stderr redirected to syslog? A catalyst script? Do you have control of all the cases where you're throwing exceptions to use something like Log4perl? You might consider checking out Log::Log4perl::Appender::DBI .

3 : @EvanCarroll These are plain CGI scripts that use CGI::Application. Eventually they will be hosted under mod_perl. Our development as well as the eventual deployment will happen on CentOS5.5. I am looking at Log4perl and will evaluate it for what I need. Thanks


---------------------------------------------------------------------------------------------------------------
Id: 1452635
title: Browser Word Document Editor
tags: ms-word, webbrowser-control, word, inline-editing
view_count: 354
body:

I've been looking at Adobe Buzzword and Zoho Writer and the functionality their editor controls provide is something that I need to incorporate into an application I'm working on.

To be clear, I'm not looking for a WYSIWYG HTML editor like FCKEditor or the Telerik R.A.D controls editor.

What I'm looking for is an editor that can create, edit and save word documents to the server within the browser.

Does anyone know of any controls (commercial or open source) that are available that might be able to provide this functionality? I'd prefer DHTML based, but Flash or Silverlight would be ok too, it just needs to live inside the browser.

comments:

1 : Did you ever find one?

2 : unfortunately no


---------------------------------------------------------------------------------------------------------------
Id: 2906227
title: My.Settings not saving after install
tags: vb.net, winforms, configuration-files
view_count: 298
body:

My application is not saving users settings after I install it. When I test my app in debug or release mode it works fine. However after compiling, linking and installing the My.Settings.Save() does not seem to be working.

I can manually change a setting in the config file and the app runs accordingly. So I know it?s reading the config file on application startup.

What am I doing wrong?

Thanks

comments:

1 : Can you post the code that change the Settings value, from what you're telling, it seems ok to me...

2 : What kind of application is this? A windows service?

3 : After some testing, I?ve confirmed the User.config is being re-written every time my app opens. The My.Settings.Save() code is working fine. What would cause my app to ignore the existing User.config file and to overwrite it every time? -Thanks


---------------------------------------------------------------------------------------------------------------
Id: 3014312
title: How Viewstate crashes in the browser in asp.net
tags: asp.net
view_count: 97
body:

What is ViewState in the Asp.net.How Viewstate crashes in the browser.what is the solution when Viewstate crash?in my code when i peak pk_id from view state then it's for some time and not work sometime also.

comments:

1 : What exactly the problem is? Post error message here.

2 : What you mean that your Viewstate crash ?


---------------------------------------------------------------------------------------------------------------
Id: 2187150
title: Exploring IronPython using dir() doesn't always yield results
tags: .net, ironpython
view_count: 83
body:

I'm playing around with IronPython and dir() does not always seem to work as I would expect. For instance:

import clr
clr.AddReference("IronPython")
clr.AddReference("Microsoft.Scripting")
from IronPython.Hosting import Python
py = Python.CreateEngine()
print dir(py.Operations)

Returns:

Traceback (most recent call last):
TypeError: __dir__() takes exactly 1 argument (0 given)

Ideas? Or is this some sort of bug?

comments:

1 : help(py.Operations) does something useful....but that does not answer your question :(

2 : That looks like a bug - we manufacture a __dir__ method for certain types but I don't know why we would manufacture one for ObjectOperations.


---------------------------------------------------------------------------------------------------------------