Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a ctypes wrapper for a library. Unfortunately, this library is not 100% reliable (occasional segfaults, etc.). Because of how it's used, I want the wrapper to be reasonably resilient to the library crashing.
The best way to do this seems to be forking a process and sending the results back from the child. I'd like to do something along these lines:
```
r, w = os.pipe()
pid = os.fork()
if pid == 0:
# child
result = ctypes_fn()
os.write(w, pickle.dumps(result))
os.close(w)
else:
# parent
os.waitpid(pid, 0)
result = os.read(r, 524288) # can be this big
os.close(r)
return pickle.loads(result)
```
This doesn't quite work, though. The forked process hangs on the write. Am I trying to send too much at once? Is there a simpler solution to this problem? | Probably you are trying to write more data than can fit into the pipe, so it is blocking until someone comes along and reads some of that info out of there. That will never happen, because the only reader is the parent process, which you appear to have written to wait until the child terminates before it reads anything. This is what we call a *deadlock*.
You might consider taking out that os.waitpid call and see what happens. Another option would be to see if os.pipe has any methods that give it a bigger buffer (I don't know your environment enough to say). | The basic problem is that there's a 64kB limit on the pipe. A few possible solutions, from the simple to the complex:
1. Send less data. zlib.compress could help in getting under the limit.
2. Store the actual data somewhere else (file, mmap, memcache), only using the pipe to send control information.
3. Continue using the pipe, but chunk the output. Use two sets of pipes so the processes can talk to each other and synchronize their communication. The code is more complex, but is otherwise very effective. | How do I send large amounts of data from a forked process? | [
"",
"python",
"fork",
"pipe",
""
] |
The question tells it all.
For the experts, is there a reason the SUN java 5 compiler accepts recursive annotations (contrary to the langspec), while the later compilers do not? I mean, what could be an argument *against* recursive annotations.
Edit: a *recursive annotation* is something like:
```
@Panel(layout=BorderLayout.class,
nested={
@Panel(region=NORTH, layout=FlowLayout.class, ...)
@Panel(region=SOUTH, layout=FlowLayout.class, ...)
}
)
``` | First -- I'm not sure what you mean by recursive annotations.
Do you mean annotations that can contain references to other annotations of the same type? Something like
```
@Panel(layout=BorderLayout.class,
nested={
@Panel(region=NORTH, layout=FlowLayout.class, ...)
@Panel(region=SOUTH, layout=FlowLayout.class, ...)
}
)
```
(which would be an example of where I'd like to use it if it were possible...)
As for my use of custom annotations (and processors): code generation.
See <http://code.google.com/p/javadude/wiki/Annotations>
For example, JavaBean properties:
```
@Bean(
properties={
@Property(name="name"),
@Property(name="phone", bound=true),
@Property(name="friend", type=Person.class, kind=PropertyKind.LIST)
}
)
public class Person extends PersonGen {
// generated superclass PersonGen will contain getters/setters
// field definitions, property change support...
}
```
or a mix-in example
```
package sample;
import java.util.List;
public interface IFlightAgent {
List<IFlight> getFlight();
void reserve(IFlight flight);
}
public interface ICarAgent {
List<ICar> getCars();
void reserve(ICar car);
}
public interface IHotelAgent {
List<IHotel> getHotels();
void reserve(IHotel hotel);
}
package sample;
import com.javadude.annotation.Bean;
import com.javadude.annotation.Delegate;
@Bean(delegates = {
@Delegate(type = IHotelAgent.class,
property = "hotelAgent",
instantiateAs = HotelAgentImpl.class),
@Delegate(type = ICarAgent.class,
property = "carAgent",
instantiateAs = CarAgentImpl.class),
@Delegate(type = IFlightAgent.class,
property = "flightAgent",
instantiateAs = FlightAgentImpl.class)
}
)
public class TravelAgent extends TravelAgentGen
implements IHotelAgent, ICarAgent, IFlightAgent
{
// generated superclass TravelAgentGen will create instances
// of the "instantiateAs" classes and delegate the interface
// methods to them
}
```
See [The drawbacks of annotation processing in Java?](https://stackoverflow.com/questions/687553/the-drawbacks-of-annotation-processing-in-java) and my answer to it for some potential issues with their usage. | I do use non-standard annotations, most usually to mark class fields as targets for a reflexive process, like caching in RPC calls, or specific initializations procedures.
I never had a need for recursive annotations, however... And I think there is a potential problem with that, as annotations need to be processed at class-definition time, before standard initializers are ready... which was I think the main reason to limit Annotation contents to base types... | Do you use (or define) non standard annotations, and for what reason. How about recursive annotations? | [
"",
"java",
"annotations",
"javac",
""
] |
Is there a way to display the lines in the stack trace for the .NET assembly build/deployed in Release mode?
**UPDATE:**
My application is divided into three class library projects and one ASP.NET "website" project. The error I am trying to track down is in one of the three class library projects. I only deployed the pdb file for the class library project that is generating the "Object reference not set to an instance of an object" error.
The line numbers are still not showing up in the stack trace. Do I need to deploy the pdb files for all projects to get the line numbers in the stack trace?
**Working solution**
Deploying the pdb file for each application fixed the line number issue. | * Go into the Properties window for the project where you want to see stack trace line numbers.
* Click on the Build "vertical tab".
* Select "Release" configuration. Check the DEBUG constant parameter.
* Uncheck the "Optimize code" parameter to avoid the occasional trace issue with inlined code (this step is not essential).
* Press the Advanced... button and choose Output -> Debug Info -> pdb-only.
* Deploy the generated .pdb file with the assembly.
# Implemented with the comment below:
* One other thing to check is in the "Package/Publish Web" section that the "Exclude generated debug symbols" checkbox is also unchecked | My solution
Copy pdb file in same folder that executable file.
now i can view the line number when run the exe file.
this is reason
<http://msdn.microsoft.com/en-us/library/ee416588%28v=vs.85%29.aspx> | Display lines number in Stack Trace for .NET assembly in Release mode | [
"",
"c#",
".net",
"visual-studio",
"stack-trace",
"line-numbers",
""
] |
I need to embed an excel sheet portion (not the whole sheet) in a user control in C# language. And I want to manipulate the data on it and save it in a collection.
What is the best way to go about it? | I would open the spreadsheet with the Excel COM Library. If you add a reference to the Microsoft Excel Object Library, you can get to the Com interface.
Add these using statements:
```
using Microsoft.Office.Interop;
using Microsoft.Office.Interop.Excel;
```
Then you can read from the spreadsheet by doing something like this:
```
private void GetData(string fileName, string tabName)
{
Workbook theWorkbook;
Application ExcelObj = null;
ExcelObj = new Application();
theWorkbook = ExcelObj.Workbooks.Open(fileName,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing, Type.Missing, Type.Missing,
Type.Missing, Type.Missing);
Sheets sheets = theWorkbook.Worksheets;
Worksheet worksheet = (Worksheet)sheets[tabName];
Range range = worksheet.get_Range("A1:A1", Type.Missing);
string data = range.Text as string;
//
// TODO : store the data
//
theWorkbook.Close(false, fileName, null);
}
```
This code would read the contents of the A1 cell into a string.
One of the quirks of working with the Excel COM interface is that you have to access data in a Range, even if you just want one cell. You can set the range to be a group of cells, then you can iterate over the collection that it returns to get the contents of each cell.
You would also want to add some error checking/handling on the file name and tab name.
There is also a way to use ODBC to read from Excel, but the spreadsheet has to be formatted in a certain way. There has to be a header data in row 1. I've found it easier to use the COM interface.
Once you have acquired the data you need, you could put it into a typed DataSet. Then you could bind that dataset to a DataGridView if you're using WinForms or a ListBox in WPF. If you just want to save the data in an XML format, you could use the DataSet WriteXml function to store the data to a file. | Why not use a [DataGridView](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.aspx) populated with the data you want to alter?
Once any alterations are complete, save the data from the DataGridView over the portion of the Excel file you pulled it from to begin with.
You may also find [these](http://social.msdn.microsoft.com/Forums/en-US/vbgeneral/thread/27a9002e-9d53-440d-9750-e6c64406fdd6) [links](http://social.msdn.microsoft.com/forums/en-US/winformsdatacontrols/thread/22d01539-2a0b-4a67-bf2e-abed631ea5b5/) [useful](http://www.google.com/search?q=datagridview+excel&rls=com.microsoft:en-us&ie=UTF-8&oe=UTF-8&startIndex=&startPage=1)! | Embed excel sheet in C# user control | [
"",
"c#",
"excel",
""
] |
How could I send additional view parameters after I have done a redirect (e.g. $this->\_redirect->gotoSimple();)?
For example, let's say I have an Edit action which will redirect the user to an Error action handler and I would like to be able to send custom, detailed error messages to its view. To illustrate it clearer, the flow would be:
1. At the Edit view (say, <http://localhost/product/edit>), the user submits something nasty
2. At editAction(), a fail check triggers a redirect to my Error view/action handler (so that my URL would read like <http://localhost/error/index>)
3. The Error/index.phtml takes a "errorMessage" view variable to display the custom error message, and editAction() needs a means to pass in some value to that "errorMessage" view variable
A quick code snippet would probably look like:
```
public function editAction() {
//DO THINGS...
// Upon failure
if($fail) {
$this->_redirector->gotoUrl('/error/index');
//TODO: I need to be able to do something like
// $errorView->errorMessage = "Generic error";
}
}
```
Any solutions, or even other better ways of achieving this, is greatly appreciated. | I have not seen anywhere that an action (editAction) accesses another action's view (errorView). for the special case of error handling, my idea is using Exceptions. you throw different exceptions for different bad situations, and in your error handler action, you can decide what to show to user based on the exception type:
```
// file: ProductContorller.php
public function editAction() {
// some code
if ($badThing) {
throw new Exception('describe the bad thing',$errorCode);
}
if ($badThing2) {
throw new Exception('describe the other bad thing',$errorCode2);
}
}
// file: ErrorController.php
public function errorAction() {
$error = $this->_getParam('error_handler');
$exception = $error->exception; // the original Exception object thrown by some code
$code = $exception->getCode();
switch ($code ) {
// decide different things for different errors
}
}
```
for more information about error handling, the [Zend Framework quick start](http://framework.zend.com/docs/quickstart/create-an-error-controller-and-view) is a great tutorial.
for other situations, you can use some messaging mechanism to communicate between these 2 actions. using flashMessenger action helper is the first thing comes into my mind:
```
// file: ProductContorller.php
public function editAction() {
// some code
if ($badThing) {
$this->_helper->flashMessenger->addMessage('error1');
$this->_redirect('error');
}
if ($badThing2) {
$this->_helper->flashMessenger->addMessage('error2');
$this->_redirect('error');
}
}
// file: ErrorController.php
public function errorAction() {
$errors = $this->_helper->flashmessenger->getMessages();
if ( in_array('error1',$errors) ) {
// do something
} // elseif ( ...
}
```
although remember that flashMessenger uses sessions, so sessions and most likely cookies are going to be involved in this messaging process. | Don't use `gotoURL()` for internal redirects. Use `gotoSimple()`. I takes up to 4 parameters:
```
gotoSimple($action,
$controller = null,
$module = null,
array $params = array())
```
In your case it's going to be:
```
$this->_redirector->gotoSimple('index',
'error',
null,
array('errorMessage'=>$errMsg));
```
See [`Redirector Zend_Controller_Action_Helper`](http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelpers.redirector) for details. | Zend: Is it possible to send view variables after a redirect? | [
"",
"php",
"zend-framework",
""
] |
I have a small SQL Server database that I need to copy on command -- I need to be able to take the mfd and ldf files at any given moment, copy them, zip them, and make them available to an end user.
Right now this is possible by manually:
1) Logging onto the SQL server via Remote Desktop
2) Detaching the database via SQL Management Studio. I have to fiddle around with a combination of setting the database to single\_user and/or restarting the service so I can get it to detach since the app server is normally logged into it.
3) While detached I go through the file system and copy the mdf and ldf files.
4) I re-attach the database via SQL Management Studio
5) I zip the copied files, and I move them to an FTP server so the people who need them can get them.
It's a horrible, inefficient process. It's not just a matter of needing the schema, but rather a need for people to work with snapshots of real, production data on their own local machines for the purpose of destructive experimentation. Luckily the zipped database is very small -- maybe 30 megs with the log.
So ideally, I'd like to create a page in the ASP .NET web application that has a button the user can press to initiate the packaging of the current database into a zip file, and then I'd just provide the link to the file download. | Why not make a ordinary backup (easy to do with sqlcommand) and add a feature for the users to easy restore that backupfile with a click on a button?
* You can backup the database with sql-commands
* You can shell out and zip the backupfile with sql-commands
* You can also shell out and ftp the backupfile automagically to an webserver if you want.
What are the end users using to consume your db? A winform-program? Then it easy done to do everything with a button click for the user.
Here are some example code for that:
```
Declare @CustomerID int
declare @FileName nvarchar(40)
declare @ZipFileName nvarchar(40)
declare @ZipComand nvarchar(255)
set @CustomerID=20 --Get from database instead in real life application
SET @FileName='c:\backups\myback'+ cast(@customerID as nvarchar(10))+'.bak'
SET @ZipFileName='c:\backups\myback'+ cast(@customerID as nvarchar(10))+'.zip'
--Backup database northwind
backup database northwind to DISK=@FileName
--Zip the file, I got a commanddriven zip.exe from the net somewhere.
set @ZipComand= 'zip.exe -r '+@ZipFileName+' '+@FileName
EXEC xp_cmdshell @zipcomand,NO_output
--Execute the batfile that ftp:s the file to the server
exec xp_cmdshell 'c:\movetoftp.bat',no_output
--Done!
```
You have to have a movetoftp.bat that contains this (change ftp-server to your):
ftp -s:ftpcommands.txt ftp.myftp.net
And you have to have a ftpcommands.txt that contains this (You can have this file created dnamically with just the right zip-file by sqlcommands too, but I let you do that yourself):
ftpusername
ftppassword
binary
prompt n
mput c:\backups\\*.zip
quit | Look at the dialogues you use in SQL Management Studio, near the top of each is a button which will generate a scrip to perform the action. This is a quick way to discover how to do this in SQL which can be executed from a database connection.
E.g. to detach database db1:
```
EXEC master.dbo.sp_detach_db @dbname = N'db1'
``` | Programmatically detach SQL Server database to copy mdf file | [
"",
"c#",
".net",
"asp.net",
"sql-server",
"sql-server-2005",
""
] |
I've been working on an economy simulator in Java and ran into a roadblock. I have an *Economy* class that owns a vector of *Traders*. Every iteration, the Economy class calls each *Trader* to update() and decide what trades it would like to place. The update() function returns the desired transactions to be added to the queue in the parent *Economy* class. I was able to implement all of the above correctly, but I still need each *Trader* to be able to see how many trades he currently has open. Since the trades are stored in the parent *Economy* class, how should I design the code so that the *Traders* do have access to *Economy* functions and variables? | Since the Trader class needs access to the methods of the Economy class, the correct way is to "inject" an instance of an Economy to the Trader class. You can do that either with the constructor:
```
public Trader(Economy economy) {
this.economy = economy;
}
```
or with a setter:
```
public void setEconomy(Economy economy) {
this.economy = economy;
}
```
Be careful however to design the Economy class properly. Access to the variables of the Economy class should be restricted to the class's methods only. Define getters and setters if you want to access them externally. As I understand it, Traders should only extract information from an Economy. They shouldn't be able to call methods that modify the state of the Economy. This should be reflected on your design.
You may also consider defining an interface:
```
interface IEconomy {
List<Trade> getTrades(Trader trader);
}
```
and implement it by the Economy class. Then inject an IEconomy to the Trader. This makes quite evident what parts of the Economy a Trader should use. | ```
public class Trader {
private Economy parent;
...
public Trader(Economy parent, ...) {
this.parent = parent;
}
}
```
Now Trader should have access to the parent Economy.
Or:
```
public onUpdate(Economy parent) { ... }
```
if you wish. | Sticky situation where accessing parent functions is necessary in Java | [
"",
"java",
"inheritance",
"permissions",
"parent-child",
"parent",
""
] |
I want to do some coding in my spare time, but the thing is, I don't want to spend the money on this.
Would the following set of development tools be The Right Thing, or is there something I'm forgetting?
* Eclipse for C++
* SVN for source control
* Qt for UI development (since it's C++, and I believe it's now opened by Nokia)
* hudson for continuous integration
I'd like to write a little image processing application that can run on any platform, but the main platform at the moment will be Windows with a possible movement to the Mac-- hence all the cross-platform tools.
Is there anything really obvious I'm forgetting? Like something like fxcop for style checking in C++?
If I use any libraries, I'd like to avoid GPL libraries; if things go south with my current employer, I'll want to monetize this. | Microsoft Visual C++ Express is free and easily the best IDE for Windows. Furthermore, you can use it to work on cross-platform code - it more depends on writing standards-adhering code and using portable libraries.
If you want to write cross-platform code, I recommend a cross-platform build tool. I use CMake, which generates Visual Studio solutions on Windows, but there are others too, such as SCons.
As for libraries, it depends on what exactly you need to do. Qt is an excellent GUI library. libpng/libjpeg and others are good for loading/saving images at a low level, but there are probably other higher-level image libraries as well.
**[edit]** A response to the comment about MSVC and Qt:
A quick search brings up Trolltech's Qt Visual Studio Integration page:
[Qt Visual Studio .NET Integration](http://doc.trolltech.com/vs-integration-1.4/index.html)
A comment points out that this is actually not free (a free addon is available at [this link](http://www.qtsoftware.com/downloads/visual-studio-add-in), but this runs Qt designer outside of Visual Studio. Also, the Express version of Visual Studio does not support plugins.
For coding specifically in Qt there is another new IDE created by Qt: [Qt Creator](http://www.qtsoftware.com/products/developer-tools). I've heard good things about it, and it is also portable across Windows, Linux, and Mac. | I detect procrastination (something I'm often guilty of) - just write some code - you can always add tools as you go along. | open source dev environment for C++: what's better? | [
"",
"c++",
"open-source",
""
] |
I am starting an open source cross platform project in C++. My development environment is Linux. There may be other developers who develop from different platforms as well. So I need some help in getting started with the configuration and development environment setup, so that all developers from multiple platforms can develop easily.
Following are my questions
1. Compiler : I plan to use g++ and heard that it is cross platform. Is that a good choice?
2. Make files : I have seen *Code::Blocks* editor and it generates make files on fly and you don't have to write one manually. Is this the best practice or do I need to create make files?
3. What are the other settings to be taken care when developing cross-platform applications?
Any thoughts?
**Edit**
Thanks for the answers. One more question.
Do you create makefiles by hand? Or is there any tool which can generate it? | The most important thing for your project to catch up is portability. It should be easy to build & run for everybody.
GCC (g++) is indeed the compiler of choice. It comes from the opensource world and is therefore most widely adopted by it.
However, **a simple Makefile won't cut it**. Generating it using CodeBlocks or any other IDE has a problem: Due to their platform, other developers will probably have to generate their own, but won't necessarily have CodeBlocks at hand, or just don't want to use it.
There exist several different cross-platform build systems, which are IDE-agnostic. Some of them create Makefiles, others don't use make but build on their own.
* The most widely adopted build system is [Autotools](http://en.wikipedia.org/wiki/GNU_build_system). However, it is hard to learn, cluttered, and an overall pain in the ass.
* Out of many other choices, **I recommend [Waf](http://code.google.com/p/waf/)**. It is proven by several larger open source projects already, XMMS2 being a good example (while not a very popular project, it has a large build with a lot of plugins and builds on a lot of platforms including OS X and Windows). While waf is not very broadly adopted, it is meant to be shipped with the source and easy to set-up. My recommendation for you.
**Edit:** to get started with your Open Source project, I also recommending [this book](http://producingoss.com/) by Karl Fogel (available for reading online). Have fun! | The GNU C++ compiler is a relatively good choice for crossplatform work, except that on Windows only a relatively old version (3.4) is natively supported. Work is underway to port a 4.x-series to Windows, but so far it's not ready for prime time.
Rather than focus on what compiler to use, I'd instead focus on which language to use. Writing ANSI standard C++ will go a long way towards making your code crossplatform. As far as possible, hide platform-specific behavior behind a good toolkit, such as Qt.
For cross-platform build environments, this may depend on what toolkit you use. Qt has QMake, which is relatively good. CMake is another compelling choice. I would avoid Autotools, since it has very poor portability outside of UNIX -- using Autotools on Win32 is very often the torment of the damned.
Finally, start working on multiple platforms *now.* VMware is invaluable for something like this. Get your code to compile on Linux, on FreeBSD and on Windows. If you can hit those three targets, moving to other platforms will be enormously easier in the future. | Best practices for a C++ portable opensource application | [
"",
"c++",
"open-source",
"compiler-construction",
"makefile",
""
] |
Running into an issue where JSF is filling up our sessions. We had a system crash the other day. Sent the Heap to IBM for review and found that we had some sessions as large as 50M. They found JSF components in the session and some very large.
So, is there any tuning that can be done? Configuration items to look at? Or other direction.
Our system is build using JSF and Spring for the presentation layer, the back end is EJB, Spring and Hibernate all running on WebSphere 6.1. | JSF is a useful technology, but you can certainly hang yourself with it.
It sounds like, either you're inflating the size of the view state (by setting large values on components) or you're leaking references to components into other session state (which would be bad). Another potential culprit would be an excessively large view (I've seen the ease with which people can build UI trees lead to very big control graphs with data tables everywhere). I know that IBM provides rich text and spreadsheet controls - I can't comment on what effect the use of these will have on state size.
The low hanging fruit is to check the managed beans configured for session scope in *faces-config.xml*.
JSF saves two things between requests:
* the view (all the controls on the page)
* the view state (the state of the controls)
These are separated because some controls, such as children of a data table, can have multiple states (one for each row). State can be saved to either a hidden field on the form (which, if unencrypted, can be a big security hazard) or in the session. In order to accommodate multiple browser windows sharing the same session (and, in some implementations, back button support), multiple views are stored.
* There should be a configuration option to set the number of view states the app will keep in the session for a given user at any given time.
* You can measure the size of view state by providing a [StateManager](http://java.sun.com/javaee/5/docs/api/javax/faces/application/StateManagerWrapper.html) that measures the size of the saved view/state (configure a StateManager in faces-config.xml with a public constructor that takes a StateManager - see the [JSF spec](http://java.sun.com/javaee/javaserverfaces/reference/api/index.html) PDFs for more details; the state is serializable and you can check its size by dumping it to a stream).
Most IDE-built JSF apps have backing beans. It would be possible, via session bean scope to hold onto state longer than you want, placing a strain on the session. Since there tends to be one backing bean per page, the more pages you have, the bigger the problem will be. Check your *faces-config.xml* to see if this is a potential source of problems.
Something else you could do would be to configure a [HttpSessionAttributeListener](http://java.sun.com/javaee/5/docs/api/javax/servlet/http/HttpSessionAttributeListener.html) in your *web.xml*. You can get a [stack trace](http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#getStackTrace()) to help identify problem areas in your app. | I was working on a JSF project and found that we had a bug where we were adding multiple JSF h:form elements. Resulting in a copy of the entire viewstate being included with every form. Cutting down to 1 form per page shaved the pages from ~2M down to ~300K. | JSF Tuning | [
"",
"java",
"jsf",
"websphere",
"performance",
""
] |
If I have some files I want to copy from my project into the `.\bin\debug\` folder on compilation, then it seems I have to put them into the root of the project. Putting them into a subfolder seems to copy them into the `.\bin\debug\` folder in the same structure they're stored in.
Is there any way to avoid this?
Just to be clear: if I have a `MyFirstConfigFile.txt` and `MySecondConfigFile.txt` in a `ConfigFiles` folder and I set their *Copy to Output* to be *Copy...*, then they appear in the `.\bin\debug\ConfigFiles\` folder. I want them to appear in the `.\bin\debug\` folder. | You could do this with a post build event. Set the files to no action on compile, then in the macro copy the files to the directory you want.
Here's a post build Macro that I think will work by copying all files in a directory called Configuration to the root build folder:
```
copy $(ProjectDir)Configuration\* $(ProjectDir)$(OutDir)
``` | You can use a MSBuild task on your csproj, like that.
Edit your csproj file
```
<Target Name="AfterBuild">
<Copy SourceFiles="$(OutputPath)yourfiles" DestinationFolder="$(YourVariable)" ContinueOnError="true" />
</Target>
``` | Copying files into the application folder at compile time | [
"",
"c#",
"visual-studio",
""
] |
I have a pool of threads which are fed tasks from a queue. Generally, a small number of threads are able to keep the queue empty. Occasionally, a particularly large burst of events will keep the queue size above zero for some time, but not for long.
My concern is regarding events that are duplicates or carry data that obsoletes previous events. During times of high volume, such events can coexists in the queue for a short period of time. I would like to be able to conflate these so that I can reduce time spent doing wasted work.
What is a good way to conflate such a queue? I could conflate at insertion time by iterating from back to head and searching for a candidate to replace, however this seems too brute-force. If you have code or library recommendations, please keep in mind that I am using Java. | Why not just implement hashCode() and equals() based on your tasks. Then just remove the task. For example.
```
queue.remove(task);
queue.offer(task);
```
Then you will not have duplicates. Or alternatively.
```
if(!queue.contains(task)) {
queue.offer(task);
}
```
This will avoid enqueuing the task if its already in the queue. | If you use [`LinkedHashMap`](http://java.sun.com/javase/6/docs/api/java/util/LinkedHashMap.html), you can preserve the ordering in which the entries were added to the queue.
When a matching entry arrives, I gather that you want to append some of its data to the original queue entry. In this case, you can either update the hashed object in place, or use [`HashMap.put(key, value)`](http://java.sun.com/j2se/1.4.2/docs/api/java/util/HashMap.html#put(java.lang.Object,%20java.lang.Object)) to replace the queued item with a new object. (I **think** that this preserves the order of the original item, but I have not tested this.)
Note that your code will need to explicitly synchronize read and write access to the `LinkedHashMap` and the data inside it. You don't want to be updating an item in the queue at the same time that another thread is grabbing it for processing. The easiest way to synchronize is probably by accessing the `LinkedHashMap` through `Collections.synchronizedMap()`. | A good method for conflating queue entries | [
"",
"java",
"performance",
"queue",
""
] |
.NET signed assemblies contain public key, but the public key is used for encryption in RSA, then how does .NET uses the public key for decryption of signed assemblies?
Ok, the signed assemblies contain the hash, but the hash is encrypted using the private key and not the public key. So, why and how in .NET private keys are used for encryption and public keys for decryption. I mean, that all software like RSACryptoPad uses the public key for encryption and not for decryption. | The public-private key pair is not used to encrypt the whole assembly. Instead it is used to **sign** the assembly.
Simplifying a little, to sign a file - such as an assembly - you take a hash of the file and then ecrypt that hash with your private key. Someone using the file verifies your signature by making a hash of the file themselves and then decrypting your encrypted hash using your public key and confirming these two hashes are the same. This proves two things:
1. The assembly is from who is claims to be from - i.e you - as it has been produced with your private key.
2. The assembly hasn't been altered by someone else as the hash you made when you released the assembly is the same as the current one. No-one can alter the signed assembly since they would also have to make corresponding changes to the encrypted hash which requires your private key.
There is a lot more detail about Digital Signatures in [this Wikipedia article](http://en.wikipedia.org/wiki/Digital_signature).
The great thing about public-private key pairs is that they work either way around. So something encrypted with your private key can be only decrypted with your public key but also something encrypted with your public key can be decrypted with your private key. This latter use means that if someone wants to send something to you and only you then then can encrypt it with your freely available public key but they know only you with your private key can decrypt it.
As the keys only work as a pair - making the [encryption asymmetric](http://en.wikipedia.org/wiki/Asymmetric_encryption) - someone else can't simply reverse the encryption they've done with the public key to get the message to you. | The idea is that a signature can only be *created* using the *private* key, but after that anyone with a copy of the *public* key can *validate* the signature. **No decryption is required for a signature**--the signature is simply added on to the plain text assembly. | How is public key used to decrypt in .NET assemblies? | [
"",
"c#",
"rsa",
""
] |
```
Switch(some case) {
case 1:
// compute something ...
return something;
break;
case 2:
// compute something ...
return something;
break;
/* some more cases ... */
case X:
// compute something ...
return something;
break;
default:
// do something
return something;
break;
}
```
In my opinion:
> Assuming this switch statement is justifiable, the return and break just doesnt look right or feel right.
The break is obviously redundant, but is omission poor style (or is this poor style to begin with?) ?
---
I personally dont do this, but there is some of this in the codebase at work. And no, im not going to be self-righteous and correct the codebase. | The C# Compiler gives a warning if you do this saying that the break is unreachable code. So in my book it is bad form to have both return and break. | No, omission is not poor style - *inclusion* is poor style. Those are unreachable statements. Get rid of them.
I like the fact that the cases return directly instead of setting a local variable and then returning just at the bottom - it means that it's incredibly clear when you're reading the code that it *does* just need to return, and that's all.
Side-note in terms of switching in the first place:
As for whether using a switch statement is the right thing to do here, it really depends on other things. Would it make sense to use a polymorphic type instead? If you're in Java, could you use a smart enum? (You can mimic these in C#, but there isn't as much support.)
I'd say this should at least prompt *considering* different designs - but it may well be the simplest way to do what you want. | does this switch statement smell bad? | [
"",
"c#",
"switch-statement",
""
] |
What is the Auto-Close option when creating a new database in SQL Server 2008?
**EDIT**: and how do you decide whether to turn it on or off? | From MSDN:
> If True, the database is closed, and its resources are freed when no user connection accesses the database. If False (default), the server maintains the database in an open and ready state regardless of user activity..
Edit to answer edited in question: It all depends on whether the server needs the extra memory, and if the time cost to open and close the database is worth the extra memory gained. If you are unsure, then false is probably the way to go. | In short, don't enable it on production ever
Only enable if the database is accessed infrequently (such as Dev/QA) | What is the Auto-Close option when creating a new database in SQL Server 2008? | [
"",
"sql",
"sql-server",
"sql-server-2008",
""
] |
The problem:
Let's say there is an XML file that contains both the data and the hierarchy of certain elements of interest to the application:
```
<root>
<node title="lvl1Node">
<node title="lvl2Node">
<node title="lvl3Node"></node>
</node>
</node>
<node title="lvl1Node2"></node>
<node title="lvl1Node3">
<node title="lvl2Node2">
<node title="lvl3Node2">
<node title="lvl4Node"></node>
</node>
</node>
</node>
</root>
```
Now let's say your application needs to provide an API to retrieve these nodes. You need to write a method that returns the nodes without losing information about their hierarchy.
My question is how would you go about it ? What kind of data type would you use.
A tree data type is the obvious answer but it not provided in the standard Collections API and writing it yourself is always a last resort (programmers are lazy, reinventing the wheel etc).
I also thought of an ArrayList where each item is either an Object (for node without subnodes) or an Arraylist (for node with subnodes) but I like generics and this feels too much like a hack.
Is there a cleverer way to do it ? | The first question you should be asking yourself is how do you need to access the data? Depth-first iterations? Search for specific values?
At first glance, this is a tree of nodes where each node can have zero or more children.
So it goes something like this:
```
class Node {
Node parent;
List<Node> children;
}
```
It's like a linked list, but each node can branch out into an arbitrary number of children. If you need to find items directly by id the best bet is to keep a seperate hashmap index. | Err. What exactly do you need that isn't covered by DOM? | Hierarchy & data structure in Java (or XML to Object conversion: best practices) | [
"",
"java",
"data-structures",
"oop",
""
] |
Craigslist has a nice feature where when you respond to a poster you respond to an email such as *job-fepsd-1120347193@craigslist.org*. The email is then in turn directed to the real email.
I am looking for a couple pointers on how to do this with PHP.
Thanks,
Levi | This is usually done by piping an e-mail address (often, a catch-all address) to PHP. [Here's a tutorial on doing it](http://evolt.org/incoming_mail_and_php) that should get you started in the right direction. | The most probable solution is by doing what they called as **Email Piping**.
They insert the ad with an identifier like this:
```
*job-fepsd-1120347193*
```
alongside with the real email.
Then they receive the email by piping it to a PHP script.
You can check Google for PHP and Piping where you will find good resources on the subject.
The script then searches for this Unique Identifier and associates it with a real email.
Then it forwards the email received to the real person.
There is also another possible solution (but less possible), they might be using POP3.
Then they would just make a check every **X** minutes on a catch-all address and then forward the message to the right person. | Best way to send anonymous email like craigslist | [
"",
"php",
"email",
"anonymous",
""
] |
I'm writing a background application to copy files in a loop to a USB stick with the "Optimize for quick removal" policy set. However, if the stick is removed part way through this process (specifically in the WriteFile() call below, which returns ERROR FILE NOT FOUND) the application hangs, the drive is then permanently inaccessible from any other application and the PC cannot be shutdown/logged off/restarted etc. All running instances of Windows Explorer also hang as a result.
I have traced the issue to the CloseHandle() call made after the stick is removed and the above error occurs. Its almost as if CloseHandle() is blocking indefinitely in the driver somewhere because the stick is no longer there? Anyway, I have managed to get past this issue by simply skipping the CloseHandle() call if WriteFile() returns ERROR FILE NOT FOUND. However, this leads to another problem where, every so often, a file gets irrecoverably corrupted and the only way to fix it is using chkdsk, or reformat the stick.
Note that this only happens on XP (SP2 and 3), Vista does not seem to suffer from the issue. A snippet of the code follows:
```
HANDLE hFile = CreateFile(szFile,
GENERIC_WRITE,
FILE_SHARE_WRITE | FILE_SHARE_READ | FILE_SHARE_DELETE,
NULL,
CREATE_ALWAYS,
FILE_FLAG_WRITE_THROUGH,
NULL);
if (hFile != INVALID_HANDLE_VALUE)
{
if (!WriteFile(hFile, pBuffer, dwBufferSize, &dwWritten))
{
int nLastError = GetLastError();
}
// If usb stick is removed during WriteFile(), ERROR_FILE_NOT_FOUND usually results.
// If handle is closed at this point then drive is inaccessible.
// If CloseHandle() is skipped, then file corruption occurs instead
if (nLastError != ERROR_FILE_NOT_FOUND)
{
CloseHandle(hFile);
}
}
```
I've tried pretty much every combination of flags for CreateFile() all to no avail. Has anybody seen this before or have any good ideas how to avoid either of the two problems occuring. Is what I'm seeing a driver problem which has been silently fixed under vista?
Thanks for any help. | > Its almost as if CloseHandle() is blocking indefinitely in the driver somewhere because
> the stick is no longer there?
Sounds reasonable. CloseHandle() will ultimately emit a file system IRP and you're not using non-blocking I/O, so that IRP will be synchronous, but it looks like where the actual file system has abruptly disappeared from underneath the file system driver, that IRP is never completed. Which means you're stuffed - the user-mode function call which lead to the file system IRP being issued will never return.
Try using non-blocking I/O - that will prolly get you around this problem, at least from the point of view of not hanging. You will still be experiencing resource loss and the like, since the IRP will still be passed down and almost certainly still won't be coming back up, but at least you won't be blocking on it.
BTW, "optimize for quick removal" is I would say designed to reduce the amount of caching that goes on and perhaps influence the order of writes to the file system to reduce the chance of corruption; I extremely doubt it is intended to preserve the file system in the event of file system departure *during* a write!
You should not be surprised that this kills the file system. | This seems to be a driver problem.
You must free all handles to a driver, to let it cleanup itself, and windows to unload it. When you don't do that, the driver thinks it is still responsible for the device, even though it changed.
You cannot escape this problem in User-Mode.
Abandoning the handle just transfers the problem to a later stage (e.g. Quitting your program, so that windows tries to close all your abandoned open handles.) | Writing files to USB stick causes file corruption/lockup on surprise removal | [
"",
"c++",
"winapi",
"usb",
"writefile",
""
] |
I wrote a small app that allows me to compare two database schemas to check for differences in structure. It goes all the way down to column details, which is nice. When I was comparing very small databases, I had no trouble but when I start to compare databases with hundreds of tables, it is annoying to scroll up and down to find where the errors are. Originally, I was using KeyedCollection to hold the table's list, but since it doesn't allow any kind of sort, I have since changed to SortedList. SortedList does sort the indexes, which gives me the tables in alphabetical order, but this is less than what I need. What I need is a class that allows me to sort based on object properties, not only on the index values. I want to push the tables with errors to the beggining of the list for easy-of-use's sake. Anyone has an idea of which class I could use to accomplish this?
EDIT1: The List class doesn't have an index, which is kind of vital for my class. I tried using Dictionary, which does have an index, but doesn't have a sort method. Implementing IComparer doesn't work because the constructor only accepts IComparer of the index type. And since the IComparer is another class that doesn't have access to the inner value list of my list class, I can't compare based on the object properties.
EDIT2: I need a class that sorts the index by the object properties, not by the index values, but I am starting to believe such class does not exist. | There is no easy way to do that. Maybe not even a hard way. Since it was meant to be used to make output, I decided to instead make multiple loops of partial output to reach the results I wanted. | Then you need create an class to **implement** : *System.Collections.Generic.IComparer*, Then you can put all your object into a collection which support sorting based on IComparer, for example:
System.Collections.Generic.List will allow you to sort based on your own implementation.
Here is a [link](http://www.java2s.com/Tutorial/CSharp/0380__Generic/UsegenericIComparerT.htm) to a good example to help you understand this. | Seeking class that allows a custom sort method | [
"",
"c#",
".net",
"sorting",
".net-2.0",
""
] |
I am using reportlab toolkit in Python to generate some reports in PDF format. I want to use some predefined parts of documents already published in PDF format to be included in generated PDF file. Is it possible (and how) to accomplish this in reportlab or in python library?
I know I can use some other tools like PDF Toolkit (pdftk) but I am looking for Python-based solution. | I'm currently using [PyPDF](http://pybrary.net/pyPdf/ "PyPDF") to read, write, and combine existing PDF's and ReportLab to generate new content. Using the two package seemed to work better than any single package I was able to find. | If you want to place existing PDF pages in your Reportlab documents I recommend [pdfrw](http://code.google.com/p/pdfrw/). Unlike PageCatcher it is free.
I've used it for several projects where I need to add barcodes etc to existing documents and it works very well. There are a couple of [examples](http://code.google.com/p/pdfrw/wiki/ExampleTools) on the project page of how to use it with Reportlab.
A couple of things to note though:
If the source PDF contains errors (due to the originating program following the PDF spec imperfectly for example), pdfrw may fail even though something like Adobe Reader has no apparent problems reading the PDF. pdfrw is currently not very fault tolerant.
Also, pdfrw works by being completely agnostic to the actual content of the PDF page you are placing. So for example, you wouldn't be able to use pdfrw inspect a page to see if it contains a certain string of text in the lower right-hand corner. However if you *don't* need to do anything like that you should be fine. | How to include page in PDF in PDF document in Python | [
"",
"python",
"pdf",
"pdf-generation",
"reportlab",
""
] |
```
$split_point = ' - ';
$string = 'this is my - string - and more';
```
How can I make a split using the second instance of `$split_point` and not the first one. Can I specify somehow a right to left search?
Basically how do I explode from right to left. I want to pick up only the last instance of " - ".
Result I need:
```
$item[0]='this is my - string';
$item[1]='and more';
```
and not:
```
$item[0]='this is my';
$item[1]='string - and more';
``` | You may use [strrev](http://us.php.net/strrev) to reverse the string, and then reverse the results back:
```
$split_point = ' - ';
$string = 'this is my - string - and more';
$result = array_map('strrev', explode($split_point, strrev($string)));
```
Not sure if this is the best solution though. | How about this:
```
$parts = explode($split_point, $string);
$last = array_pop($parts);
$item = array(implode($split_point, $parts), $last);
```
Not going to win any golf awards, but it shows intent and works well, I think. | How to explode only on the last occurring delimiter? | [
"",
"php",
"arrays",
"string",
""
] |
I just got burned by a bug that is partially due to my lack of understanding, and partially due to what I think is suboptimal design in our codebase. I'm curious as to how my 5-minute solution can be improved.
We're using ref-counted objects, where we have AddRef() and Release() on objects of these classes. One particular object is derived from the ref-count object, but a common function to get an instance of these objects (GetExisting) hides an AddRef() within itself without advertising that it is doing so. This necessitates doing a Release at the end of the functional block to free the hidden ref, but a developer who didn't inspect the implementation of GetExisting() wouldn't know that, and someone who forgets to add a Release at the end of the function (say, during a mad dash of bug-fixing crunch time) leaks objects. This, of course, was my burn.
```
void SomeFunction(ProgramStateInfo *P)
{
ThreadClass *thread = ThreadClass::GetExisting( P );
// some code goes here
bool result = UseThreadSomehow(thread);
// some code goes here
thread->Release(); // Need to do this because GetExisting() calls AddRef()
}
```
So I wrote up a little class to avoid the need for the Release() at the end of these functions.
```
class ThreadContainer
{
private:
ThreadClass *m_T;
public:
ThreadContainer(Thread *T){ m_T = T; }
~ThreadContainer() { if(m_T) m_T->Release(); }
ThreadClass * Thread() const { return m_T; }
};
```
So that now I can just do this:
```
void SomeFunction(ProgramStateInfo *P)
{
ThreadContainer ThreadC(ThreadClass::GetExisting( P ));
// some code goes here
bool result = UseThreadSomehow(ThreadC.Thread());
// some code goes here
// Automagic Release() in ThreadC Destructor!!!
}
```
What I don't like is that to access the thread pointer, I have to call a member function of ThreadContainer, Thread(). Is there some clever way that I can clean that up so that it's syntactically prettier, or would anything like that obscure the meaning of the container and introduce new problems for developers unfamiliar with the code?
Thanks. | use boost::shared\_ptr
it is possible to define your own destructor function, such us in next example: <http://www.boost.org/doc/libs/1_38_0/libs/smart_ptr/sp_techniques.html#com> | Yes, you can implement `operator ->()` for the class, which will recursively call `operator ->()` on whatever you return:
```
class ThreadContainer
{
private:
ThreadClass *m_T;
public:
ThreadContainer(Thread *T){ m_T = T; }
~ThreadContainer() { if(m_T) m_T->Release(); }
ThreadClass * operator -> () const { return m_T; }
};
```
It's effectively using smart pointer semantics for your wrapper class:
```
Thread *t = new Thread();
...
ThreadContainer tc(t);
...
tc->SomeThreadFunction(); // invokes tc->t->SomeThreadFunction() behind the scenes...
```
You could also write a conversion function to enable your `UseThreadSomehow(ThreadContainer tc)` type calls in a similar way.
If Boost is an option, I think you can set up a `shared_ptr` to act as a smart reference as well. | Best Practice for Scoped Reference Idiom? | [
"",
"c++",
"pointers",
""
] |
I am looking for an efficient way to determine the position of the least significant bit that is set in an integer, e.g. for 0x0FF0 it would be 4.
A trivial implementation is this:
```
unsigned GetLowestBitPos(unsigned value)
{
assert(value != 0); // handled separately
unsigned pos = 0;
while (!(value & 1))
{
value >>= 1;
++pos;
}
return pos;
}
```
Any ideas how to squeeze some cycles out of it?
(Note: this question is for people that enjoy such things, not for people to tell me xyzoptimization is evil.)
**[edit]** Thanks everyone for the ideas! I've learnt a few other things, too. Cool! | [Bit Twiddling Hacks](http://graphics.stanford.edu/%7Eseander/bithacks.html) offers an excellent collection of, er, bit twiddling hacks, with performance/optimisation discussion attached. My favourite solution for your problem (from that site) is «multiply and lookup»:
```
unsigned int v; // find the number of trailing zeros in 32-bit v
int r; // result goes here
static const int MultiplyDeBruijnBitPosition[32] =
{
0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
};
r = MultiplyDeBruijnBitPosition[((uint32_t)((v & -v) * 0x077CB531U)) >> 27];
```
Helpful references:
* "[Using de Bruijn Sequences to Index a 1 in a Computer Word](http://supertech.csail.mit.edu/papers/debruijn.pdf)" - Explanation about why the above code works.
* "[Board Representation > Bitboards > BitScan](https://www.chessprogramming.org/BitScan)" - Detailed analysis of this problem, with a particular focus on chess programming | Why not use the built-in [ffs](http://linux.die.net/man/3/ffs)? (I grabbed a man page from Linux, but it's more widely available than that.)
> ## ffs(3) - Linux man page
>
> ### Name
>
> ffs - find first bit set in a word
>
> ### Synopsis
>
> ```
> #include <strings.h>
> int ffs(int i);
> #define _GNU_SOURCE
> #include <string.h>
> int ffsl(long int i);
> int ffsll(long long int i);
> ```
>
> ### Description
>
> The ffs() function returns the position of the first (least significant) bit set in the word i. The least significant bit is position 1 and the most significant position e.g. 32 or 64. The functions ffsll() and ffsl() do the same but take arguments of possibly different size.
>
> ### Return Value
>
> These functions return the position of the first bit set, or 0 if no bits are set in i.
>
> ### Conforming to
>
> 4.3BSD, POSIX.1-2001.
>
> ### Notes
>
> BSD systems have a prototype in `<string.h>`. | Position of least significant bit that is set | [
"",
"c++",
"c",
"optimization",
"bit-manipulation",
""
] |
Using C#, I want to format a decimal to only display two decimal places and then I will take that decimal and subtract it to another decimal. I would like to be able to do this without having to turn it into a string first to format and then convert it back to a decimal. I'm sorry I forget to specify this but I don't want to round, I just want to chop off the last decimal point. Is there a way to do this? | If you don't want to round the decimal, you can use Decimal.Truncate. Unfortunately, it can only truncate ALL of the decimals. To solve this, you could multiply by 100, truncate and divide by 100, like this:
```
decimal d = ...;
d = Decimal.Truncate(d * 100) / 100;
```
And you could create an extension method if you are doing it enough times
```
public static class DecimalExtensions
{
public static decimal TruncateDecimal(this decimal @this, int places)
{
int multipler = (int)Math.Pow(10, places);
return Decimal.Truncate(@this * multipler) / multipler;
}
}
``` | You can use: `Math.Round(number,2);` to round a number to two decimal places.
See [this specific overload of Math.Round](http://msdn.microsoft.com/en-us/library/zy06z30k.aspx) for examples. | How to round a decimal for output? | [
"",
"c#",
"decimal-point",
""
] |
Several months ago, I wrote a [blog post](http://igotgenes.blogspot.com/2009/01/tab-completion-and-history-in-python.html) detailing how to achieve tab-completion in the standard Python interactive interpreter--a feature I once thought only available in IPython. I've found it tremendously handy given that I sometimes have to switch to the standard interpreter due to IPython unicode issues.
Recently I've done some work in OS X. To my discontent, the script doesn't seem to work for OS X's Terminal application. I'm hoping some of you with experience in OS X might be able to help me trouble-shoot it so it can work in Terminal, as well.
I am reproducing the code below
```
import atexit
import os.path
try:
import readline
except ImportError:
pass
else:
import rlcompleter
class IrlCompleter(rlcompleter.Completer):
"""
This class enables a "tab" insertion if there's no text for
completion.
The default "tab" is four spaces. You can initialize with '\t' as
the tab if you wish to use a genuine tab.
"""
def __init__(self, tab=' '):
self.tab = tab
rlcompleter.Completer.__init__(self)
def complete(self, text, state):
if text == '':
readline.insert_text(self.tab)
return None
else:
return rlcompleter.Completer.complete(self,text,state)
#you could change this line to bind another key instead tab.
readline.parse_and_bind('tab: complete')
readline.set_completer(IrlCompleter('\t').complete)
# Restore our command-line history, and save it when Python exits.
history_path = os.path.expanduser('~/.pyhistory')
if os.path.isfile(history_path):
readline.read_history_file(history_path)
atexit.register(lambda x=history_path: readline.write_history_file(x))
```
Note that I have slightly edited it from the version on my blog post so that the `IrlCompleter` is initialized with a true tab, which seems to be what is output by the Tab key in Terminal. | To avoid having to use more GPL code, Apple doesn't include a real readline. Instead it uses the BSD-licensed [libedit](http://www.thrysoee.dk/editline/), which is only mostly-readline-compatible. Build your own Python (or use Fink or MacPorts) if you want completion. | This should work under Leopard's python:
```
import rlcompleter
import readline
readline.parse_and_bind ("bind ^I rl_complete")
```
Whereas this one does not:
```
import readline, rlcompleter
readline.parse_and_bind("tab: complete")
```
Save it in ~/.pythonrc.py and execute in .bash\_profile
```
export PYTHONSTARTUP=$HOME/.pythonrc.py
``` | Tab-completion in Python interpreter in OS X Terminal | [
"",
"python",
"macos",
"configuration",
"interpreter",
"tab-completion",
""
] |
I have the following code:
```
function showAccessRequests_click() {
var buttonValue = $("#showAccessRequests").val();
if (buttonValue == "Show") {
$(".hideAccessRequest").removeClass("hideAccessRequest");
$("#showAccessRequests").val("Hide");
}
else {
$(".hideAccessRequest").addClass("hideAccessRequest");
$("#showAccessRequests").val("Show");
}
}
```
This script removes a class fine but it does not want to add the class. Can you see any issues with this code? | When you add hideAccessRequest class to the element, you search for it by the existence of that class.. if you are adding it, that class won't already be applied and thus you won't match any elements. | `$(".hideAccessRequest")` doesn't exist. you need to use id, I guess. And you might want to look at [`toggleClass`](http://docs.jquery.com/Attributes/toggleClass#class). | addClass function not worked using JQuery | [
"",
"javascript",
"jquery",
""
] |
I am really confused about why an update is not taking place. This is very simple:
```
int goodID = 100;
DataContext db = new DataContext();
Schedule schedule = db.Schedules.Single(s => s.ID == goodID);
// this wont persist - WHY NOT?!
schedule.Email = txtEmail.Text;
// this does persist
schedule.NumberCourses = 5;
db.SubmitChanges();
```
I can't understand why the field, Email, isn't getting the value from the textbox. What can I check?
# EDIT
I have set a breakpoint and checked the value after assignment. It assigns the textbox value but still no update. | I am an idiot. It's fixed. Votes for everyone.
Instead of checking in the database, like a normal person would, I was just looking on the webform after refreshing the page. I wasn't initializing the textbox with the value from the db. So the update was happening. See? I told you I was an idiot. | Check what changes will be submitted to the datacontext.
Add a breakpoint just before the `db.SubmitChanges()` line gets executed and add the following Watch:
```
db.GetChangeSet();
```
In the Watch (or Quick Watch) window you'll be able to see which changes are being submitted. | Linq To Sql - Update not being persisted | [
"",
"c#",
".net",
"sql-server",
"linq",
"linq-to-sql",
""
] |
I have a table which has a header row, but also a header column and a total column with several columns in between.
Something like this:
```
Name Score 1 Score 2 ... Total
--------------------------------------
John 5 6 86
Will 3 7 82
Nick 7 1 74
```
The entire table is defined inside a fixed-width scrollable div because there are likely to be a large number of "Score" rows and I have a fixed-width page layout.
```
<div id="tableWrapper" style="overflow-x: auto; width: 500px;">
<table id="scoreTable">
...
</table>
</div>
```
What I would like is for the first (`Name`) and last (`Total`) columns to remain visible while the inner columns scroll.
Can anyone help me with this?
**Edit:** I mean horizontal scrolling only - changed to specify that.
---
**Update:** I've solved this problem for myself and have posted the answer below. Let me know if you need any more information - this was a bit of a pain to do and I'd hate for someone else to have to rewrite everything. | I've experimented with a few methods (thanks to everyone who helped) and here's what I've come up with using jQuery. It seems to work well in all browsers I tested. Feel free to take it and use it however you wish. Next step for me will be turning it into a reusable jQuery plugin.
## Summary:
I started with a normal table with everything in it (*Id="ladderTable"*), and I wrote **Three methods** - one to strip the first column, one to strip the last column, and one to fix the row heights.
The *stripFirstColumn* method creates a new table (*Id="nameTable"*), traverses the original table and takes out the first column, and adds those cells to the nameTable.
The *stripLastColumn* method does basically the same thing, except it takes out the last column and adds the cells to a new table called *totalTable*.
The *fixHeights* method looks at each row in each table, calculates the maximum height, and applies it to the related tables.
In the document ready event, I called all three methods in order. Note that all three tables float left so they'll just stack horizontally.
## The HTML Structure:
```
<h1>Current Ladder</h1>
<div id="nameTableSpan" style="float:left;width:100px;border-right:2px solid gray;"></div>
<div id="ladderDiv" style="float:left;width:423px;overflow:auto;border:1px solid gray;margin-top:-1px;">
<table id="ladderTable" class="ladderTable">
<thead>
<tr><td>Name</td><td>Round 1</td> ... <td>Round 50</td><td class="scoreTotal">Total</td></tr>
</thead>
<tr><td>Bob</td><td>11</td> ... <td>75</td><td>421</td></tr>
... (more scores)
</table>
</div>
<div id="totalTableSpan" style="float:left;width:70px;border-left:2px solid gray;"></div>
```
## The jQuery:
```
function stripFirstColumn() {
// pull out first column:
var nt = $('<table id="nameTable" cellpadding="3" cellspacing="0" style="width:100px;"></table>');
$('#ladderTable tr').each(function(i)
{
nt.append('<tr><td style="color:'+$(this).children('td:first').css('color')+'">'+$(this).children('td:first').html()+'</td></tr>');
});
nt.appendTo('#nameTableSpan');
// remove original first column
$('#ladderTable tr').each(function(i)
{
$(this).children('td:first').remove();
});
$('#nameTable td:first').css('background-color','#8DB4B7');
}
function stripLastColumn() {
// pull out last column:
var nt = $('<table id="totalTable" cellpadding="3" cellspacing="0" style="width:70px;"></table>');
$('#ladderTable tr').each(function(i)
{
nt.append('<tr><td style="color:'+$(this).children('td:last').css('color')+'">'+$(this).children('td:last').html()+'</td></tr>');
});
nt.appendTo('#totalTableSpan');
// remove original last column
$('#ladderTable tr').each(function(i)
{
$(this).children('td:last').remove();
});
$('#totalTable td:first').css('background-color','#8DB4B7');
}
function fixHeights() {
// change heights:
var curRow = 1;
$('#ladderTable tr').each(function(i){
// get heights
var c1 = $('#nameTable tr:nth-child('+curRow+')').height(); // column 1
var c2 = $(this).height(); // column 2
var c3 = $('#totalTable tr:nth-child('+curRow+')').height(); // column 3
var maxHeight = Math.max(c1, Math.max(c2, c3));
//$('#log').append('Row '+curRow+' c1=' + c1 +' c2=' + c2 +' c3=' + c3 +' max height = '+maxHeight+'<br/>');
// set heights
//$('#nameTable tr:nth-child('+curRow+')').height(maxHeight);
$('#nameTable tr:nth-child('+curRow+') td:first').height(maxHeight);
//$('#log').append('NameTable: '+$('#nameTable tr:nth-child('+curRow+')').height()+'<br/>');
//$(this).height(maxHeight);
$(this).children('td:first').height(maxHeight);
//$('#log').append('MainTable: '+$(this).height()+'<br/>');
//$('#totalTable tr:nth-child('+curRow+')').height(maxHeight);
$('#totalTable tr:nth-child('+curRow+') td:first').height(maxHeight);
//$('#log').append('TotalTable: '+$('#totalTable tr:nth-child('+curRow+')').height()+'<br/>');
curRow++;
});
if ($.browser.msie)
$('#ladderDiv').height($('#ladderDiv').height()+18);
}
$(document).ready(function() {
stripFirstColumn();
stripLastColumn();
fixHeights();
$("#ladderDiv").attr('scrollLeft', $("#ladderDiv").attr('scrollWidth')); // scroll to the last round
});
```
If you have any questions or if there's anything that wasn't clear, I'm more than happy to help.
It took me quite a while to work out that there was nothing that I could really reuse and it took a bit longer to write this. I'd hate for someone to go to the same trouble. | Can I propose a somewhat unorthodox solution?
What would you think about placing the 'total' column after the 'name' column, rather than at the very end? Wouldn't this avoid the requirement for only a portion of the table to scroll?
It's not exactly what you're asking for, but perhaps it is a sufficient solution, given that the alternative would be pretty messy. (Placing the 'total' and 'name' columns outside of the table, for instance, would create alignment problems when not all rows are of equal height. You could correct this with javascript but then you'd be entering a whole new world of pain).
Also from a UI perspective, it may be that 'name' and 'total' are the most important data, in which case it would make sense to put them together, followed by a sort of 'breakdown' of the total. Of course, we seem to have an intuition that a 'total' should come after its constituent parts, but I don't think it would cause too much confusion to the user if the order were reversed like this (though this is a question for you, based on your product and your users).
Anyway, something to consider.
EDIT:
Here are some more unorthodox solutions, now that I think I understand your intentions a bit better:
1. Paginate the scores. Give the most recent ten, say, and the total, and
a link to older scores, which are provided 10 at a time
2. Only give names, totals, and some other meaningful measures
such as mean and sd, then provide
a link for each name that shows
all results corresponding to that
name. You could then also provide
a link showing all results for a
given score set, so that comparisons between different users
can be made. The point is that you'd
only have to give 1 dimension of
data for each view, rather than
having an unwieldy 2D data set
3. Make the rows sortable (easy with jQuery UI) so that if I want to
compare Mary to Jane, I can drag and
place one after the other, so I wont
need to keep scrolling left and
right to see which scores correspond
to which names
4. Highlight a row when it is clicked, by changing the background
color or similar, again so I don't need to keep scrolling left and right.
Anyway you get the idea. Perhaps it is better to look for a UI solution than a contorted markup solution. Ultimately I would be questioning how important it is to present so much data to the user at once, that a portion of it needs to scroll in a particular fashion for the data to be readable. Perhaps you're building a spreadsheet app, and you really do need to display a 100x100 matrix in a single view. If not, you could surely come up with more creative ways than I have to split up the results. | How do I freeze the first and last columns of an html table in a scrollable div? | [
"",
"javascript",
"html",
"layout",
"html-table",
""
] |
I make the following reasoning, please tell me what's wrong (or right) about it:
"If inlining a function duplicates the code in the place the function is called, then the static and local variables are duplicated for each function calling it and if there is only one thread running the function that calls the inlined one at the same time, then the code is thread-safe".
"And, if it doesn't help with static and global variables, does it with code that is creating temporary variables?"
Thanks | When you declare a function as inline, it is merely a hint to the compiler. Static variables have a clear definition in the language. If the compiler does inline the function, it is still obligated to keep the static variables shared between all instances of the function. Therefore, they will remain global and have to be protected in a MT environment.
As to the local variables, unless they are used outside of the function, they are thread safe regardless of the function being inlined or not. | Nope, you are wrong. For a static variable, whether it is inlined or not, there is only actually one instance. Inlined functions have no effect on thread safety, one way or the other. | Are inline functions in C/C++ a way to make them thread-safe? | [
"",
"c++",
"c",
"multithreading",
"thread-safety",
""
] |
We are running an web application that is using Java 64bit 5 gigs of -Xmx of maximum heap size. We have no control over the java code. We can only tweak configuration parameters. The situation that we are facing is that the java processes after it takes the full heap allocated at start up, it starts acting very responding very slow to web site requests. My guess is that is waiting for the GC to collect unused memory objects.
The image below will show you a image of top in linux that shows the critical situation of the processes.
[top image of java process http://cp.images.s3.amazonaws.com/ForumImages/java-gc-issue.jpg](http://cp.images.s3.amazonaws.com/ForumImages/java-gc-issue.jpg)
Is there any way, we can help java regain the used memory inside the allocated space.
EDIT 1:
I used some of the answers below to be able to get to the answer of my question. Since my question was too difficult to answer, and it turned out to be a discussion. I will post how I was able to monitor the GC cycles and I will pick the answer with more votes. I used jconsole through real vnc viewer to be able to hook from my windows machine to my linux machine running tomcat.
I used this parameters to start the java processes:
```
-Djava.awt.headless=true -server -Xms512m -Xmx5120m -Dbuild.compiler.emacs=true -Dcom.sun.management.jmxremote -Dcom.sun.management.jmxremote.port=4999 -Dcom.sun.management.jmxremote.authenticate=false -Dcom.sun.management.jmxremote.ssl=false
```
This is the type of output I got, from jconsole through vnc viewer.
[GC Sample Image http://cp.images.s3.amazonaws.com/ForumImages/Sample\_GC\_Image.jpg](http://cp.images.s3.amazonaws.com/ForumImages/Sample_GC_Image.jpg "Sample GC Image") | I'd recommend that you not guess. Get some data to see exactly what's going on. You can use [visual gc](http://java.sun.com/performance/jvmstat/visualgc.html) to see what's happening.
If it's the perm space that's being filled up, there won't be much you can do.
Which JVM? If it's 5 or higher there are additional parameters besides just max heap size you can adjust. Check out <http://blog.springsource.com/2008/10/14/optimising-and-tuning-apache-tomcat-part-2/> | It sounds like you have a memory leak if your application is getting progressively slower. The GC will always start to clean up unused objects as soon as it needs to. If you add -verbosegc you will be able to see how often a GC is performed and much memory is free after a GC. If the heap is more than 80% used you either have to increase the max memory or fix the program so it doesn't use so much.
Can you do a `numactl --hardware` ? I suggest you not use more than 80% of one memory bank or your GC times will increases dramatically. | How to help java tomcat processes to regain used memory? | [
"",
"java",
"memory",
"tomcat",
"memory-management",
""
] |
I have this code:
```
public void replay() {
long previous = DateTime.Now.Ticks;
for (int i = 0; i < 1000; i++) {
Thread.Sleep(300);
long cur = DateTime.Now.Ticks;
Console.WriteLine(cur - previous);
previous = cur;
}
}
```
Which is invoked as a separate thread like this:
```
MethodInvoker replayer = new MethodInvoker(replay);
replayer.BeginInvoke(null, null);
```
However, if I watch the output, it acts strangely. It outputs `i` in pairs. For example, it'll wait a full wait, then output `i`, then quickly output the next `i` too, then wait again. Why is it doing that and how can I correct it?
It outputs this:
```
3125040
2968788
2968788
2968788
3125040
2968788
2968788
2968788
3125040
2968788
2968788
2968788
3125040
```
If I increase the sleep to more than a second this doesn't happen. | Change the code to eliminate display latency in your analysis:
```
public void replay()
{
Thread.Sleep(5000);
DateTime start = DateTime.Now;
for (int i = 0; i < 1000; i++)
{
Console.WriteLine(string.Format("Exec:{0} - {1} ms",
i, DateTime.Now - start));
start = DateTime.Now;
Thread.Sleep(300);
}
}
```
Looking at your modified output, there is less than 5% variance (15ms out of the 300) in the loop delay. This is normal, due to the uncertainties involved in when the OS actually assigns timeslices to the thread... (If I recall correctly, in a windows OS, this is normally only every 20 ms !)
The larger discrepancy you perceive in the console output is almost certainly due to display latencys. | Cannot reproduce. I wonder if it is something local to your machine; buffering, perhaps. | Why is this code executing faster than expected? | [
"",
"c#",
".net",
"multithreading",
"execution",
""
] |
I am attempting to stop the music inside of my flash swf that I have loaded in the page
```
<object id="FlashControl1" type="application/x-shockwave-flash"
data="Flash/Preloader%20-%20Splash.swf" width="980px" height="316px">
<param name="movie" value="Flash/Preloader%20-%20Splash.swf" />
<param name="wmode" value="Transparent" />
<param name="quality" value="High" />
<param name="play" value="True" />
<param name="loop" value="False" />
<param name="menu" value="False" />
<param name="scale" value="Exactfit" />
<param name="flashvars" value="name="FlashControl1"" />
<img src="Images/Banner/Main_Banner.jpg" alt="" width="980px" height="316px" />
</object>
```
I have a button that loads a modal popup with a silverlight video and I would like the audio to stop by execuding the SoundMixer.stop(); command.
I have yet to find a solution on google | In your Flash file, you must have the following function:
```
function stopSound():void {
SoundMixer.stop();
}
```
Then, you must make it available for JavaScript calls
```
ExternalInterface.addCallback('stopSound', stopSound);
```
In your JavaScript code you must have this simple function that selects your swf:
```
function getFlashMovie(movieName)
{
var isIE = navigator.appName.indexOf("Microsoft") != -1;
return (isIE) ? window[movieName] : document[movieName];
}
```
And when you want to stop the sounds in your movie, you just call the function you've previously made available in the swf, from JavaScript:
```
movie = getFlashMovie('your-movie-name');
movie.stopSound();
```
That should do it. For more info on ExternalInterface.addCallback, check out [the Adobe AS3 Language Refrence page](http://livedocs.adobe.com/flash/9.0/ActionScriptLangRefV3/flash/external/ExternalInterface.html#addCallback()). | ```
function test() {
movie = document.getElementById('FlashControl1');
movie.stopSound();}
```
this worked :) | Stop music from in flash from javascript event | [
"",
"javascript",
"flash",
""
] |
I have a simple table in mysql with the following fields:
* id -- Primary key, int, autoincrement
* name -- varchar(50)
* description -- varchar(256)
Using MySQLdb, a python module, I want to insert a name and description into the table, and get back the id.
In pseudocode:
```
db = MySQLdb.connection(...)
queryString = "INSERT into tablename (name, description) VALUES" % (a_name, a_desc);"
db.execute(queryString);
newID = ???
``` | I think it might be
```
newID = db.insert_id()
```
---
**Edit by Original Poster**
Turns out, in the version of MySQLdb that I am using (1.2.2)
You would do the following:
```
conn = MySQLdb(host...)
c = conn.cursor()
c.execute("INSERT INTO...")
newID = c.lastrowid
```
I am leaving this as the correct answer, since it got me pointed in the right direction. | I don't know if there's a MySQLdb specific API for this, but in general you can obtain the last inserted id by [SELECTing LAST\_INSERT\_ID()](http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html)
It is on a per-connection basis, so you don't risk race conditions if some other client performs an insert as well. | How do you safely and efficiently get the row id after an insert with mysql using MySQLdb in python? | [
"",
"python",
"mysql",
""
] |
Coming from a `Java` background, I'm used to the common practice of dealing with collections: obviously there would be exceptions but usually code would look like:
```
public class MyClass {
private Set<String> mySet;
public void init() {
Set<String> s = new LinkedHashSet<String>();
s.add("Hello");
s.add("World");
mySet = Collections.unmodifiableSet(s);
}
}
```
I have to confess that I'm a bit befuddled by the plethora of options in Scala. There is:
* `scala.List` (and `Seq`)
* `scala.collections.Set` (and `Map`)
* `scala.collection.immutable.Set` (and `Map`, `Stack` but not `List`)
* `scala.collection.mutable.Set` (and `Map`, `Buffer` but not `List`)
* `scala.collection.jcl`
So questions!
1. Why are `List` and `Seq` defined in package `scala` and not `scala.collection` (even though implementations of `Seq` are in the collection sub-packages)?
2. What is the standard mechanism for *initializing* a collection and then *freezing* it (which in Java is achieved by wrapping in an `unmodifiable`)?
3. Why are some collection types (e.g. `MultiMap`) only defined as mutable? (There is no immutable `MultiMap`)?
I've read Daniel Spiewak's [excellent series on scala collections](http://www.codecommit.com/blog/scala/scala-collections-for-the-easily-bored-part-1) and am still puzzled by how one would actually use them in practice. The following seems slightly unwieldy due to the enforced full package declarations:
```
class MyScala {
var mySet: scala.collection.Set[String] = null
def init(): Unit = {
val s = scala.collection.mutable.Set.empty[String]
s + "Hello"
s + "World"
mySet = scala.collection.immutable.Set(s : _ *)
}
}
```
Although arguably this is *more correct* than the Java version as the immutable collection cannot change (as in the Java case, where the underlying collection could be altered underneath the `unmodifiable` wrapper) | > Why are List and Seq defined in package scala and not scala.collection (even though implementations of Seq are in the collection sub-packages)?
Because they are deemed so generally useful that they are automatically imported into all programs via synonyms in scala.Predef.
> What is the standard mechanism for initializing a collection and then freezing it (which in Java is achieved by wrapping in an unmodifiable)?
Java doesn't have a mechanism for freezing a collection. It only has an idiom for wrapping the (still modifiable) collection in a wrapper that throws an exception. The proper idiom in Scala is to copy a mutable collection into an immutable one - probably using :\_\*
> Why are some collection types (e.g. MultiMap) only defined as mutable? (There is no immutable MultiMap)?
The team/community just hasn't gotten there yet. The 2.7 branch saw a bunch of additions and 2.8 is expected to have a bunch more.
> The following seems slightly unwieldy due to the enforced full package declarations:
Scala allows import aliases so it's always less verbose than Java in this regard (see for example java.util.Date and java.sql.Date - using both forces one to be fully qualified)
```
import scala.collection.{Set => ISet}
import scala.collection.mutable.{Set => MSet}
class MyScala {
var mySet: ISet[String] = null
def init(): Unit = {
val s = MSet.empty[String]
s + "Hello"
s + "World"
mySet = Set(s : _ *)
}
}
```
Of course, you'd really just write init as `def init() { mySet = Set("Hello", "World")}` and save all the trouble or better yet just put it in the constructor `var mySet : ISet[String] = Set("Hello", "World")` | Mutable collections are useful occasionally (though I agree that you should always look at the immutable ones first). If using them, I tend to write
```
import scala.collection.mutable
```
at the top of the file, and (for example):
```
val cache = new mutable.HashMap[String, Int]
```
in my code. It means you only have to write “mutable.HashMap”, not scala.collection.mutable.HashMap”. As the commentator above mentioned, you could remap the name in the import (e.g., “import scala.collection.mutable.{HashMap => MMap}”), but:
1. I prefer not to mangle the names, so that it’s clearer what classes I’m using, and
2. I use ‘mutable’ rarely enough that having “mutable.ClassName” in my source is not an
undue burden.
(Also, can I echo the ‘avoid nulls’ comment too. It makes code so much more robust and comprehensible. I find that I don’t even have to use Option as much as you’d expect either.) | Scala collection standard practice | [
"",
"java",
"scala",
"scala-collections",
""
] |
I use `nosetests` to run my unittests and it works well. I want to get a list of all the tests `nostests` finds without actually running them. Is there a way to do that? | Version 0.11.1 is currently available. You can get a list of tests without running them as follows:
```
nosetests -v --collect-only
``` | I recommend using:
```
nosetests -vv --collect-only
```
While the `-vv` option is not described in `man nosetests`, ["An Extended Introduction to the nose Unit Testing Framework"](http://ivory.idyll.org/articles/nose-intro.html) states that:
> Using the -vv flag gives you verbose output from nose's test discovery algorithm. This will tell you whether or not nose is even looking in the right place(s) to find your tests.
The `-vv` option can save time when trying to determine why nosetests is only finding some of your tests. (In my case, it was because nosetests skipped certain tests because the `.py` scripts were executable.)
Bottom line is that the `-vv` option is incredibly handy, and I almost always use it instead of the `-v` option. | List all Tests Found by Nosetest | [
"",
"python",
"unit-testing",
"nose",
"nosetests",
""
] |
Suppose I have a number of related classes that all have a method like this:
```
protected override OnExecute()
{
this.constructorParm.BoolProperty = !this.constructorParm.BoolProperty;
}
```
The type of `constructorParm` may change (it may also be a `static` `Setting`), and the specific property will certainly change, but the type of the property will always be `bool`.
Suppose further that I've decided it's silly to have 8 different classes that all do the exact same thing on an implementation level- toggle a bool value. Especially when they're all related on a semantic level also (they all derive from the same `Command` abstract base class, which is where `OnExecute()` comes from).
How to I parameterize the property that I want to toggle without parameterizing the actual toggle operation itself? For example, I know I can do something like this (uncompiled):
```
internal class CommandX
{
Action doExecute = null;
public CommandX(Action executeAction) { this.doExecute = executeAction; }
protected override OnExecute() { this.doExecute(); }
}
// elsewhere
var b = new CommandX(() => {target.BoolProperty = !target.BoolProperty;});
```
but how I can I capture the toggling behavior in the class, while still accepting the writable property as a parameter? (If I pass the toggling in as a parameter, then I'm just making an over-complicated delegate.)
(I can't just pass the property in b/c `bool` is a value type, so I'd just be toggling a copy. I can't pass it in by ref, of course, b/c properties can't be passed by ref. I feel like there's got to be something stupid and obvious that I'm just really missing here. :) )
## **Context**
The reason I'm doing such a simple thing in an indirect manner is actually due to the use of the GoF Command pattern in winforms. The core functionality `Command`s are more complex, but this small subset of `Command`s essentially just toggles a property that will raise PropertyChanged events elsewhere. Instead of having all these commands in separate classes, I wanted to fold them into one because they're so simple. | You could use Reflection to select which property to toggle by using the [PropertyInfo](http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx) class:
```
string propertyName = "BoolProperty";
Foo myFoo = new Foo();
Type myFooType = myFoo.GetType();
PropertyInfo prop = myFooType.GetProperty(propertyName);
prop.SetValue(myFoo, !((bool)prop.GetValue(myFoo, null)), null);
```
You'd only have to keep the name of the property that you'd like to toggle.
However, this would only make sense if "toggling a property" makes explicit part of your design. Otherwise, it would definately be overkill for something this basic when the "easy" solution is to just toggle the property normally. | You could probably make use of reflection to specify what property to change, but if there are a limited number of options (you mention there are 8 classes), I would recommend that you use a switch statement, and have an enumeration in the class constructor.
```
internal enum PropertyOption { Prop1, Prop2 }
internal class Bar {
PropertyOptiion prop;
public Bar(PropertyOption prop) {
this.prop = prop;
}
public override OnFoo() {
switch (prop) {
case PropertyOption.Prop1:
this.prop1 = !this.prop1;
break;
case PropertyOption.Prop2:
this.prop2 = !this.prop2;
break;
}
}
}
``` | How do I refactor multiple similar methods of this sort into a single method? | [
"",
"c#",
"refactoring",
"properties",
""
] |
I have PHP application that is completely procedural (No PHP Classes). In my case, is there any formal diagrams I can draw to show how my web application that is equivalent to a UML class diagram for OOP based applications.
Thanks all | [doxygen](http://www.doxygen.org/) can generate call- and caller graphs automatically - if that suits your needs. | You could make some Hatley-Pirbhai models:
<http://en.wikipedia.org/wiki/Hatley-Pirbhai_modeling> | Class Diagram for classless PHP application | [
"",
"php",
"oop",
"uml",
""
] |
i'm completely confused by what i've read about character sets. I'm developing an interface to store french text formatted in html inside a mysql database.
What i understood was that the safe way to have all french special characters displayed properly would be to store them as utf8. so i've created a mysql database with utf8 specified for the database and each table.
I can see through phpmyadmin that the characters are stored exactly the way it is supposed to. But outputting these characters via php gives me erratic results: accented characters are replaced by meaningless characters. Why is that ?
do i have to utf8\_encode or utf8\_decode them? note: the html page character encodign is set to utf8.
more generally, what is the safe way to store this data? Should i combine htmlentities, addslashes, and utf8\_encode when saving, and stripslashes,html\_entity\_decode and utf8\_decode when i output? | MySQL performs character set conversions on the fly to something called the [connection charset](http://dev.mysql.com/doc/refman/5.1/en/charset-connection.html). You can specify this charset using the sql statement
```
SET NAMES utf8
```
or use a specific API function such as [mysql\_set\_charset()](http://se.php.net/mysql_set_charset):
```
mysql_set_charset("utf8", $conn);
```
If this is done correctly there's no need to use functions such as utf8\_encode() and utf8\_decode().
You also have to make sure that the browser uses the same encoding. This is usually done using a simple header:
```
header('Content-type: text/html;charset=utf-8');
```
(Note that the charset is called *utf-8* in the browser but *utf8* in MySQL.)
In most cases the connection charset and web charset are the only things that you need to keep track of, so if it still doesn't work there's probably something else your doing wrong. Try experimenting with it a bit, it usually takes a while to fully understand. | I strongly recomend to read this article ["**The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)**"](http://www.joelonsoftware.com/articles/Unicode.html) by Joel Spolsky, to understand what are you doing and why. | php mysql character set: storing html of international content | [
"",
"php",
"mysql",
"character-encoding",
""
] |
i am using iframes in html.loading different html pages into iframes.in that html pages i have image. whenever i load the image into iframes i getting flickering.
can we stop that flickering by using Iframes
How to do ? | There are a few things you can do to help with this.
Firstly, make sure you specify the width and height of the image. The browser will then reserve space for the image, rather than resizing the reserved space when the size of the image is known.
If you wan supply an example, we can talk about pre-loading if it seems necessary. | Hmm, I'm not entirely sure what sort of an flicker you want to get rid of, but I'd imagine it's related to the browser loading and then showing your new page with the image.
Well I can not think of any good ways, other than loading the next image into another iframe on background and then switching between the currently visible and the newly loaded iframe.
The bigger question is, why do you need to use the iframes? Are you loading something from a site that you do not own? If not, consider ajax and other such techniques. | IFrames in HTML | [
"",
"javascript",
"html",
""
] |
There is a process that seems to be running all the time in SQL Server 2005 activity monitor. Double clicking on it produces the following query:
`CREATE TABLE #tmpDBCCinputbuffer ([EVENT TYPE] NVARCHAR(512),
[PARAMETERS] INT, [EVENT Info] NVARCHAR(512))
INSERT INTO #tmpDBCCinputbuffer EXEC ('DBCC INPUTBUFFER(58)')
SELECT [EVENT Info] FROM #tmpDBCCinputbuffer`
Any idea what it is? Is it dangerous? | Ironically, its the query you use to see the last query run on a connection, which is what you are doing to see what all the connections' last queries were. Including the connection you use to look at all those connections.
where's the dizzy emoticon when you need it? | <http://msdn.microsoft.com/en-us/library/ms187730.aspx>
Quote from SQL Server Developer Center
> "DBCC INPUTBUFFER permissions default
> to members of the sysadmin fixed
> server role only, who can see any
> SPID. Other users can see any SPID
> they own. Permissions are not
> transferable."
> (<http://msdn.microsoft.com/en-us/library/aa258826(SQL.80).aspx>) | What is this process in Sql Server Activity monitor? | [
"",
"sql",
"sql-server",
"sql-server-2005",
"process",
"ssms",
""
] |
I'm writing a client-server pair in C++ using Linux sockets. I want the server to listen for a connection, and while one client is connected the server should reject any other clients that try to connect.
I tried implementing this by setting the backlog parameter in the [listen](http://linux.die.net/man/3/listen) function to 0 and to 1 and neither one of those values seems to work. The first client connects as expected, but any subsequent clients just block while the first client finishes. What's really confusing to me is that they don't block on connecting to the server, they block on the first read.
I used [the code here](http://tldp.org/LDP/LG/issue74/tougher.html) to get started writing my client and server. Does anyone know what I need to change to get the server to accept only one client connection, and drop any subsequent connection attempts? | When you accept a connection, a new socket gets created. The old one is still used to listen for future connections.
Since you want to only allow 1 connection at a time, you could just accept the connections, and then close the new accepted socket if you detect you are already processing another.
Is there a net difference that you are looking for compared to closing the new accepted socket right after the accept? The client will know as soon as it tries to use its socket (or right away if it is already waiting on the server with a read call) with a last error of: server actively closed the connection. | Just don't `fork()` after `accept()`.
This pseudo-C-code will only accept one client at once.
```
while(1) {
listen()
accept()
*do something with the connection*
close()
}
``` | How do I create a TCP server that will accept only one connection at a time? | [
"",
"c++",
"linux",
"sockets",
""
] |
This is probably trivial, but I can't think of a better way to do it. I have a COM object that returns a variant which becomes an object in C#. The only way I can get this into an int is
```
int test = int.Parse(string.Format("{0}", myobject))
```
Is there a cleaner way to do this? Thanks | You have several options:
* `(int)` — Cast operator. Works if the object *already is* an integer at some level in the inheritance hierarchy or if there is an implicit conversion defined.
* `int.Parse()/int.TryParse()` — For converting from a string of unknown format.
* `int.ParseExact()/int.TryParseExact()` — For converting from a string in a specific format
* `Convert.ToInt32()` — For converting an object of unknown type. It will use an explicit and implicit conversion or IConvertible implementation if any are defined.
* `as int?` — Note the "?". The `as` operator is only for reference types, and so I used "?" to signify a `Nullable<int>`. The "`as`" operator works like `Convert.To____()`, but think `TryParse()` rather than `Parse()`: it returns `null` rather than throwing an exception if the conversion fails.
Of these, I would prefer `(int)` if the object really is just a boxed integer. Otherwise use [`Convert.ToInt32()`](http://msdn.microsoft.com/en-us/library/system.convert.toint32.aspx) in this case.
Note that this is a very *general* answer: I want to throw some attention to Darren Clark's response because I think it does a good job addressing the *specifics* here, but came in late and wasn't voted as well yet. He gets my vote for "accepted answer", anyway, for also recommending (int), for pointing out that if it fails `(int)(short)` might work instead, and for recommending you check your debugger to find out the actual runtime type. | The cast `(int) myobject` *should* just work.
If that gives you an invalid cast exception then it is probably because the variant type isn't VT\_I4. My bet is that a variant with VT\_I4 is converted into a boxed int, VT\_I2 into a boxed short, etc.
When doing a cast on a boxed value type it is only valid to cast it to the type boxed.
Foe example, if the returned variant is actually a VT\_I2 then `(int) (short) myObject` should work.
Easiest way to find out is to inspect the returned object and take a look at its type in the debugger. Also make sure that in the interop assembly you have the return value marked with `MarshalAs(UnmanagedType.Struct)` | Better way to cast object to int | [
"",
"c#",
"interop",
""
] |
I have an image upload for a slideshow, and the users are continuously uploading files that are 2MB plus. Files under this size work fine, but files over the size cause what looks like a browser timeout.
Here are my php ini settings:
* Max memory allocation: 12M
* Max file upload size: 10M
* Max HTTP Post size: 10M
* Max execution time: 60
* Max input parsing time: 120
These settings are in the configuration file itself, and I can change them directly. Changes show up when using phpinfo().
I am running on an apache server and php 4.3.9(client's choice, not mine). The apache server's request limit is set to default, which I believe is somewhere around 2GB?
When I use the firebug network monitor, it does look like I am not receiving a full response from the server, though I am not too experienced at using this tool. Things seem to be timing out at around 43 seconds.
All the help I can find on the net points to the above settings as the culprits, but all of those settings are much higher than this 2MB file and the 43 second time out.
Any suggestions at where I can go from here to solve this issue?
Here are relevant php ini settings from phpinfo(). Let me know if I need to post any more.
* file\_uploads On On
* max\_execution\_time 60 60
* max\_input\_nesting\_level 64 64
* max\_input\_time 120 120
* memory\_limit 12M 12M
* post\_max\_size 10M 10M
* safe\_mode Off Off
* upload\_max\_filesize 10M 10M
* upload\_tmp\_dir no value no value | Make sure you have error reporting activated in php.ini: **display\_errors = On**; this might give you a clue about what's going on. Production servers usually (should) have error reporting disabled.
I recently had a similar problem, and increasing the memory\_limit setting worked for me. If you read files ***content*** into variables, each variable will take about as much memory as the file size, increasing the scripts memory requirements. | Where are those settings? If you're using `.htaccess` then your Apache configuration might not be allowing you to override those settings.
I'd suggest checking with a phpinfo() call if those settings are indeed being applied or not:
```
<?php
phpinfo();
?>
``` | Large File Upload Errors with PHP | [
"",
"php",
"apache",
"file-upload",
""
] |
Here's my situation. I've noticed that code gets harder to maintain when you keep embedding queries in every function that will use them. Some queries tend to grow very fast and tend to lose readability after concatenating every line. Another issue that comes with all of the concatenation is when you must test a specific query and paste it. You are forced to remove all of the " that held your query string together.
So my question is, what methods are being used to separate queries from the code? I have tried searching but it doesn't look like it's the right thing because i'm not finding anything relevant.
I'd like to note that views and stored procedure are not possible since my queries fetch data from a production database.
Thank you. | I avoid this problem by wrapping queries in classes that represent the entities stored in the table. So the accounts table has an Account object. It'll have an insert/update/delete query.
I've seen places where the query is stored in a file and templates are used to replace parts of the query.
Java had something called SQLJ - don't know if it ever took off.
LINQ might provide some way around this as an issue too. | If you follow an [MVC pattern](http://en.wikipedia.org/wiki/Model-view-controller), then your queries should be all in the model - i.e. the objects representing actual data.
If not, then you could just put all your repetitive queries in script files, including only those needed in each request.
However, concatenating and that kind of stuff is hard to get rid of; that's why programmers exist :) | Where do you store long/complete queries used in code? | [
"",
"sql",
""
] |
i like to make very simple 3d/2d game for pc/mac/linux
what is the best free 3d/2d engine for this ?
i have no experience in game programming so i guess it have to be easy to learn
please in c++
thanks | While 'best' can very much depend on your situation, one I have used in the past to great success is [OGRE 3D](http://www.ogre3d.org).
It's cross-platform, very nicely written (C++), and runs well. However the one thing that set it apart for me was the great community - you can always get help no matter how simple your question, and there are plenty of guides/tutorials around on their forum/wiki. The documentation is also very good.
It's well worth checking out.
Hrmm, upon reading that it almost sounds like I have a vested interest - I don't! I just really like it from past experience! | Try searching [DevMaster's Game and Graphics Engines Database](http://www.devmaster.net/engines/) for 3D engines. This question has also been asked and answered [MANY](http://www.devmaster.net/forums/showthread.php?t=13873&highlight=2d+engine) [MANY](http://www.devmaster.net/forums/showthread.php?t=13627&highlight=C+game+engine) times in their [forums](http://www.devmaster.net/forums/).
[C4 Engine](http://www.terathon.com/c4engine/index.php), [irrLicht](http://irrlicht.sourceforge.net/) and [Torque](http://www.garagegames.com/) are often recommended for 3D in C++, but it really depends on your individual requirements or if you really need an engine at all. | What is the best free portable 3d/2d engine? | [
"",
"c++",
"game-engine",
""
] |
**UPDATED** I've updated the example to better illustrate my problem. I realised it was missing one specific point - namely the fact that the `CreateLabel()` method always takes a label type so the factory can decide what type of label to create. Thing is, it might need to obtain more or less information depending on what type of label it wants to return.
I have a factory class that returns objects representing labels to be sent to a printer.
The factory class looks like this:
```
public class LargeLabel : ILabel
{
public string TrackingReference { get; private set; }
public LargeLabel(string trackingReference)
{
TrackingReference = trackingReference;
}
}
public class SmallLabel : ILabel
{
public string TrackingReference { get; private set; }
public SmallLabel(string trackingReference)
{
TrackingReference = trackingReference;
}
}
public class LabelFactory
{
public ILabel CreateLabel(LabelType labelType, string trackingReference)
{
switch (labelType)
{
case LabelType.Small:
return new SmallLabel(trackingReference);
case LabelType.Large:
return new LargeLabel(trackingReference);
}
}
}
```
Say that I create a new label type, called CustomLabel. I want to return this from the factory, but it needs some additional data:
```
public class CustomLabel : ILabel
{
public string TrackingReference { get; private set; }
public string CustomText { get; private set; }
public CustomLabel(string trackingReference, string customText)
{
TrackingReference = trackingReference;
CustomText = customText;
}
}
```
This means my factory method has to change:
```
public class LabelFactory
{
public ILabel CreateLabel(LabelType labelType, string trackingReference, string customText)
{
switch (labelType)
{
case LabelType.Small:
return new SmallLabel(trackingReference);
case LabelType.Large:
return new LargeLabel(trackingReference);
case LabelType.Custom:
return new CustomLabel(trackingReference, customText);
}
}
}
```
I don't like this because the factory now needs to cater for the lowest common denominator, but at the same time the CustomLabel class *needs* to get a custom text value. I could provide the additional factory method as an override, but I want to enforce the fact that the CustomLabel needs the value, otherwise it'll only ever be given empty strings.
What is the correct way to implement this scenario? | Well, how do you want to *call* the factory method?
Concentrate on how you want to be able to use your API, and the implementation will usually make itself fairly clear. This is made even easier if you write the desired results of your API as unit tests.
An overload may well be the right thing to do here, but it really depends on how you want to use the factory. | How about just using the Factory method to decide what label you need?
```
public class LabelFactory {
public ILabel CreateLabel(string trackingReference, string customText) {
return new CustomLabel(trackingReference, customText);
}
public ILabel CreateLabel(String trackingReference) {
return new BasicLabel(trackingReference);
}
}
```
Your factory still needs to know about each type (although with an interface you can implement dynamic loading) but there is very little that the client needs to know - according to what data is provided, the factory generates the correct implementation.
This is a simplistic solution to the simple problem you described. I assume the question is an oversimplification of a more complex problem but without knowing what your real problem is, I'd rather not design an over complex solution. | Factory class knows too much | [
"",
"c#",
"design-patterns",
"refactoring",
"factory",
""
] |
I have created a program that prints results on command line.
(It is server and it prints log on command line.)
Now, I want to see the same result to GUI .
**How can I redirect command line results to GUI?**
Please, suggest a trick to easily transform console application to simple GUI.
Note that it should work on Linux and Windows. | You could create a script wrapper that runs your command line program as a sub process, then add the output to something like a text widget.
```
from tkinter import *
import subprocess as sub
p = sub.Popen('./script',stdout=sub.PIPE,stderr=sub.PIPE)
output, errors = p.communicate()
root = Tk()
text = Text(root)
text.pack()
text.insert(END, output)
root.mainloop()
```
where script is your program. You can obviously print the errors in a different colour, or something like that. | To display subprocess' output in a GUI *while it is still running*, a portable stdlib-only solution that works on both Python 2 and 3 has to use a background thread:
```
#!/usr/bin/python
"""
- read output from a subprocess in a background thread
- show the output in the GUI
"""
import sys
from itertools import islice
from subprocess import Popen, PIPE
from textwrap import dedent
from threading import Thread
try:
import Tkinter as tk
from Queue import Queue, Empty
except ImportError:
import tkinter as tk # Python 3
from queue import Queue, Empty # Python 3
def iter_except(function, exception):
"""Works like builtin 2-argument `iter()`, but stops on `exception`."""
try:
while True:
yield function()
except exception:
return
class DisplaySubprocessOutputDemo:
def __init__(self, root):
self.root = root
# start dummy subprocess to generate some output
self.process = Popen([sys.executable, "-u", "-c", dedent("""
import itertools, time
for i in itertools.count():
print("%d.%d" % divmod(i, 10))
time.sleep(0.1)
""")], stdout=PIPE)
# launch thread to read the subprocess output
# (put the subprocess output into the queue in a background thread,
# get output from the queue in the GUI thread.
# Output chain: process.readline -> queue -> label)
q = Queue(maxsize=1024) # limit output buffering (may stall subprocess)
t = Thread(target=self.reader_thread, args=[q])
t.daemon = True # close pipe if GUI process exits
t.start()
# show subprocess' stdout in GUI
self.label = tk.Label(root, text=" ", font=(None, 200))
self.label.pack(ipadx=4, padx=4, ipady=4, pady=4, fill='both')
self.update(q) # start update loop
def reader_thread(self, q):
"""Read subprocess output and put it into the queue."""
try:
with self.process.stdout as pipe:
for line in iter(pipe.readline, b''):
q.put(line)
finally:
q.put(None)
def update(self, q):
"""Update GUI with items from the queue."""
for line in iter_except(q.get_nowait, Empty): # display all content
if line is None:
self.quit()
return
else:
self.label['text'] = line # update GUI
break # display no more than one line per 40 milliseconds
self.root.after(40, self.update, q) # schedule next update
def quit(self):
self.process.kill() # exit subprocess if GUI is closed (zombie!)
self.root.destroy()
root = tk.Tk()
app = DisplaySubprocessOutputDemo(root)
root.protocol("WM_DELETE_WINDOW", app.quit)
# center window
root.eval('tk::PlaceWindow %s center' % root.winfo_pathname(root.winfo_id()))
root.mainloop()
```
The essence of the solution is:
* put the subprocess output into the queue in a background thread
* get the output from the queue in the GUI thread.
i.e., call `process.readline()` in the background thread -> queue -> update GUI label in the main thread. Related [`kill-process.py`](https://gist.github.com/zed/42324397516310c86288) (no polling -- a less portable solution that uses `event_generate` in a background thread). | Redirect command line results to a tkinter GUI | [
"",
"python",
"user-interface",
"tkinter",
""
] |
After reading a question on [the difference between pointers and references](https://stackoverflow.com/questions/57483/difference-between-pointer-variable-and-reference-variable-in-c), I decided that I'd like to use references instead of pointers for my class fields. However it seems that this is not possible, because they cannot be declared uninitialized (right?).
In the particular scenario I'm working on right now, I don't want to use normal variables (what's the correct term for them by the way?) because they're automatically initialized when I declare them.
In my snippet, bar1 is automatically instantiated with the default constructor (which isn't what I want), &bar2 causes a compiler error because you can't use uninitialized references (correct?), and \*bar3 is happy as larry because pointers can be declared uninitialized (by the way, is it best practice to set this to NULL?).
```
class Foo
{
public:
Bar bar1;
Bar &bar2;
Bar *bar3;
}
```
It looks like I have to use pointers in this scenario, is this true? Also, what's the best way of using the variable? The -> syntax is a bit cumbersome... Tough luck? What about [smart pointers](https://stackoverflow.com/questions/417481/pointers-smart-pointers-or-shared-pointers), etc? Is this relevant?
### Update 1:
After attempting to implement a reference variable field in my class and initializing it in the constructor, why might I receive the following error?
```
../src/textures/VTexture.cpp: In constructor ‘vimrid::textures::VTexture::VTexture()’:
../src/textures/VTexture.cpp:19: error: uninitialized reference member ‘vimrid::textures::VTexture::image’
```
Here's the real code:
```
// VTexture.h
class VTexture
{
public:
VTexture(vimrid::imaging::ImageMatrix &rImage);
private:
vimrid::imaging::ImageMatrix ℑ
}
// VTexture.cpp
VTexture::VTexture(ImageMatrix &rImage)
: image(rImage)
{
}
```
I've also tried doing this in the header, but no luck (I get the same error).
```
// VTexture.h
class VTexture
{
public:
VTexture(vimrid::imaging::ImageMatrix &rimage) : image(rImage) { }
}
```
### Update 2:
**Fred Larson** - Yes! There is a default constructor; I neglected it because I thought it wasn't relevant to the problem (how foolish of me). After removing the default constructor I caused a compiler error because the class is used with a std::vector which requires there to be a default constructor. So it looks like I must use a default constructor, and therefore must use a pointer. Shame... or is it? :) | **Answer to Question 1:**
> However it seems that this is not possible, because they [references] cannot be declared uninitialized (right?).
Right.
---
**Answer to Question 2:**
> In my snippet, bar1 is automatically
> instantiated with the default
> constructor (which isn't what I want),
> &bar2 causes a compiler error because
> you can't use uninitialized references
> (correct?),
You initialize references of your class in your constructor's initializer list:
```
class Foo
{
public:
Foo(Bar &rBar) : bar2(rBar), bar3(NULL)
{
}
Bar bar1;
Bar &bar2;
Bar *bar3;
}
```
---
**Answer to Question 3:**
> In the particular scenario I'm working
> on right now, I don't want to use
> normal variables (what's the correct
> term for them by the way?)
There is no correct name for them, typically you can just say pointers for most discussions (except this one) and everything you need to discuss will also apply to references. You initialize non pointer, non reference members in the same way via the initailizer list.
```
class Foo
{
public:
Foo() : x(0), y(4)
{
}
int x, y;
};
```
---
**Answer to Question 4:**
> pointers can be declared uninitialized
> (by the way, is it best practice to
> set this to NULL?).
They can be declared uninitialized yes. It is better to initialize them to NULL because then you can check if they are valid.
```
int *p = NULL;
//...
//Later in code
if(p)
{
//Do something with p
}
```
---
**Answer to Question 5:**
> It looks like I have to use pointers
> in this scenario, is this true? Also,
> what's the best way of using the
> variable?
You can use either pointers or references, but references cannot be re-assigned and references cannot be NULL. A pointer is just like any other variable, like an int, but it holds a memory address. An array is an aliased name for another variable.
A pointer has its own memory address, whereas an array should be seen as sharing the address of the variable it references.
With a reference, after it is initialized and declared, you use it just like you would have used the variable it references. There is no special syntax.
With a pointer, to access the value at the address it holds, you have to `dereference` the pointer. You do this by putting a \* before it.
```
int x=0;
int *p = &x;//p holds the address of x
int &r(x);//r is a reference to x
//From this point *p == r == x
*p = 3;//change x to 3
r = 4;//change x to 4
//Up until now
int y=0;
p = &y;//p now holds the address of y instead.
```
---
**Answer to Question 6:**
> What about smart pointers, etc? Is
> this relevant?
Smart pointers (See boost::shared\_ptr) are used so that when you allocate on the heap, you do not need to manually free your memory. None of the examples I gave above allocated on the heap. Here is an example where the use of smart pointers would have helped.
```
void createANewFooAndCallOneOfItsMethods(Bar &bar)
{
Foo *p = new Foo(bar);
p->f();
//The memory for p is never freed here, but if you would have used a smart pointer then it would have been freed here.
}
```
---
**Answer to Question 7:**
> Update 1:
>
> After attempting to implement a
> reference variable field in my class
> and initializing it in the
> constructor, why might I receive the
> following error?
The problem is that you didn't specify an initializer list. See my answer to question 2 above. Everything after the colon :
```
class VTexture
{
public:
VTexture(vimrid::imaging::ImageMatrix &rImage)
: image(rImage)
{
}
private:
vimrid::imaging::ImageMatrix ℑ
}
``` | They can be initialized. You just have to use the member initializer list.
```
Foo::Foo(...) : bar1(...), bar2(...), bar3(...)
{
// Whatever
}
```
It's a good idea to initialize all of your member variables this way. Otherwise, for other than primitive types, C++ will initialize them with a default constructor anyway. Assigning them within the braces is actually reassigning them, not initializing them.
Also, keep in mind that the member initializer list specifies HOW to initialize the member variables, NOT THE ORDER. Members are initialized in the order in which they are declared, not in the order of the initializers. | Must I use pointers for my C++ class fields? | [
"",
"c++",
"pointers",
"reference",
""
] |
I am using the ExtJS framework and I have the following handler that is used solely as a handler for a button:
```
var myButtonHandler = function(button, event){
//code goes here
};
```
My button definition looks like this:
```
var myButton = new Ext.Button({
id : 'myButton',
renderTo : 'mybutton',
text : 'Save',
handler : myButtonHandler,
scope : this
});
```
As you can see, the handler receives the expected "button" and "event". However, I'd like to pass some additional information into my handler. How would I do that? | I would actually use Exts createDelegate prototype.
```
var appendBooleanOrInsertionIndex = 0; // Inserts the variables into the front of the function.
appendBooleanOrInsertionIndex = true; // Appends the variables to the end of the arguments
var myButton = new Ext.Button({
id : 'myButton',
renderTo : 'mybutton',
text : 'Save',
handler : myButtonHandler.createDelegate(this, [param1, param2], appendBooleanOrInsertionIndex),
scope : this
});
``` | In Ext JS 4:
```
Ext.bind(myButtonHandler, this, [params array], true);
``` | How do I add additional parameters to an ExtJS handler? | [
"",
"javascript",
"extjs",
"handler",
""
] |
Why does the following code throw an exception?
```
for (int i = 0; i <= Items.Length-1; i++)
{
Console.WriteLine(Items[i,1]);
}
```
Exception:
```
System.IndexOutOfRangeException was unhandled
Message="Index was outside the bounds of the array."
Source="Es"
StackTrace:
at Es.Program.Main(String[] args) in C:\Users\Fero\Documents\Visual Studio 2005\Projects\Es\Es\Program.cs:line 19
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
```
Declaration of Items:
Function which gets the array of strings:
```
static string[,] ReadFromFile(string filename, int rowsF)
{
StreamReader SR;
string S;
string[] S_split;
SR = File.OpenText(filename);
S = SR.ReadLine();
string[,] myItems = new String[rowsF, 2];
int row_number = 0;
while (S != null)
{
S_split = S.Split('"');
//temp_items[row_number,0] =
myItems[row_number,0] = S_split[1];
myItems[row_number,1] = S_split[2];
row_number++;
S = SR.ReadLine();
}
SR.Close();
return myItems;
}
string[,] Items = ReadFromFile(myFile, rowsF);
``` | You have a straight two-dimensional array. Length gives you the [total number of elements](http://msdn.microsoft.com/en-us/library/system.array.length.aspx) in the array, but you're using it to calculate the index for a single dimension. What you want is:
```
for (int i = 0; i < Items.GetLength(0); i++)
{
Console.WriteLine(Items[i,1]);
}
``` | Check the length of Items[i]. It appears to be a 2D array, and it's apparently not null, because you'd get a different exception for that, so it probably is just an empty array at Items[i], or only contains one item.
Check for:
```
Items[i] == null
Items[i].Length > 0
```
**EDIT**: Your additional code helped. When you split the string to initialize Items, for the item that's giving you trouble, check what you're storing at index 1. Other than that, I can't see a problem with it. | Why is my array throwing Out of Range Exception Error? | [
"",
"c#",
"arrays",
""
] |
Hy all,
I believe that the following piece of code is generating memory leak?
```
/* External function to dynamically allocate a vector */
template <class T>
T *dvector(int n){
T *v;
v = (T *)malloc(n*sizeof(T));
return v;
}
/* Function that calls DVECTOR and, after computation, frees it */
void DiscontinuousGalerkin_Domain::computeFaceInviscidFluxes(){
int e,f,n,p;
double *Left_Conserved;
Left_Conserved = dvector<double>(NumberOfProperties);
//do stuff with Left_Conserved
//
free(Left_Conserved);
return;
}
```
I thought that, by passing the pointer to DVECTOR, it would allocate it and return the correct address, so that *free(Left\_Conserved)* would successfully deallocate. However, it does not seem to be the case.
**NOTE:** I have also tested with *new/delete* replacing *malloc/free* without success either.
I have a similar piece of code for allocating a 2-D array. I decided to manage vectors/arrays like that because I am using them a lot, and I also would like to understand a bit deeper memory management with C++.
So, I would pretty much like to keep an external function to allocate vectors and arrays for me. What's the catch here to avoid the memory leak?
**EDIT**
I have been using the DVECTOR function to allocate user-defined types as well, so that is potentially a problem, I guess, since I don't have constructors being called.
Even though in the piece of code before I free the Left\_Conserved vector, I also would like to otherwise allocate a vector and left it "open" to be assessed through its pointer by other functions. If using BOOST, it will automatically clean the allocation upon the end of the function, so, I won't get a "public" array with BOOST, right? I suppose that's easily fixed with NEW, but what would be the better way for a matrix?
It has just occurred me that I pass the pointer as an argument to other functions. Now, BOOST seems not to be enjoying it that much and compilation exits with errors.
So, I stand still with the need for a pointer to a vector or a matrix, that accepts user-defined types, that will be passed as an argument to other functions. The vector (or matrix) would most likely be allocated in an external function, and freed in another suitable function. (I just wouldn't like to be copying the loop and new stuff for allocating the matrix everywhere in the code!)
Here is what I'd like to do:
```
template <class T>
T **dmatrix(int m, int n){
T **A;
A = (T **)malloc(m*sizeof(T *));
A[0] = (T *)malloc(m*n*sizeof(T));
for(int i=1;i<m;i++){
A[i] = A[i-1]+n;
}
return A;
}
void Element::setElement(int Ptot, int Qtot){
double **MassMatrix;
MassMatrix = dmatrix<myT>(Ptot,Qtot);
FillInTheMatrix(MassMatrix);
return;
}
``` | So, some important concepts discussed here helped me to solve the memory leaking out in my code. There were two main bugs:
* The allocation with *malloc* of my user-defined types was buggy. However, when I changed it to *new*, leaking got even worse, and that's because one my user-defined types had a constructor calling an external function with no parameters and no correct memory management. Since I called that function after the constructor, there was no bug in the processing itself, but only on memory allocation. So *new* **and** a correct constructor solved one of the main memory leaks.
* The other leaking was related to a buggy memory-deallocation command, which I was able to isolate with Valgrind (and a bit a patience to get its output correctly). So, here's the bug (and, please, don't call me a moron!):
```
if (something){
//do stuff
return; //and here it is!!! =P
}
free();
return;
```
And that's where an RAII, as I understood, would avoid misprogramming just like that. I haven't actually changed it to a std::vector or a boost::scoped\_array coding yet because it is still not clear to me if a can pass them as parameter to other functions. So, I still must be careful with *delete[]*.
Anyway, memory leaking is gone (by now...) =D | There is no memory leak there, but you should use new/delete[] instead of malloc/free. Especially since your function is templated.
If you ever want to to use a type which has a non-trivial constructor, your malloc based function is broken since it doesn't call any constructors.
I'd replace "dvector" with simply doing this:
```
void DiscontinuousGalerkin_Domain::computeFaceInviscidFluxes(){
double *Left_Conserved = new double[NumberOfProperties];
//do stuff with Left_Conserved
//
delete[] Left_Conserved;
}
```
It is functionally equivalent (except it can call constructors for other types). It is simpler and requires less code. Plus every c++ programmer will instantly know what is going on since it doesn't involve an extra function.
Better yet, use smart pointers to completely avoid memory leaks:
```
void DiscontinuousGalerkin_Domain::computeFaceInviscidFluxes(){
boost::scoped_array<double> Left_Conserved(new double[NumberOfProperties]);
//do stuff with Left_Conserved
//
}
```
As many smart programmers like to say "the best code is the code you **don't** have to write"
**EDIT:** Why do you believe that the code you posted leaks memory?
**EDIT:** I saw your comment to another post saying
> At code execution command top shows
> allocated memory growing
> indefinitely!
This may be completely normal (or may not be) depending on your allocation pattern. Usually the way heaps work is that they often grow, but don't often shrink (this is to favor subsequent allocations). Completely symmetric allocations and frees should allow the application to stabilize at a certain amount of usage.
For example:
```
while(1) {
free(malloc(100));
}
```
shouldn't result in continuous growth because the heap is highly likely to give the same block for each malloc.
So my question to you is. Does it grow "indefinitely" or does it simply not shrink?
**EDIT:**
You have asked what to do about a 2D array. Personally, I would use a class to wrap the details. I'd either use a library (I believe boost has a n-dimmentional array class), or rolling your own shouldn't be too hard. Something like this may be sufficient:
<http://www.codef00.com/code/matrix.h>
Usage goes like this:
```
Matrix<int> m(2, 3);
m[1][2] = 10;
```
It is technically more efficient to use something like operator() for indexing a matrix wrapper class, but in this case I chose to simulate native array syntax. If efficiency is *really* important, it can be made as efficient as native arrays.
**EDIT:** another question. What platform are you developing on? If it is \*nix, then I would recommend valgrind to help pinpoint your memory leak. Since the code you've provided is clearly not the problem.
I don't know of any, but I am sure that windows also has memory profiling tools.
**EDIT:** for a matrix if you insist on using plain old arrays, why not just allocate it as a single contiguous block and do simple math on indexing like this:
```
T *const p = new T[width * height];
```
then to access an element, just do this:
```
p[y * width + x] = whatever;
```
this way you do a `delete[]` on the pointer whether it is a 1D or 2D array. | Dedicated function for memory allocation causes memory leak? | [
"",
"c++",
"memory-leaks",
""
] |
I have a class X, which I provide a snippet of here:
```
class X {
public:
template <typename Iter>
X(Iter begin, Iter end) : mVec(begin, end) {}
private:
vector<Y> const mVec;
};
```
I now want to add a new concatenating constructor to this class, something like:
```
template <typename Iter1, typename Iter2>
X(Iter1 begin1, Iter1 end1, Iter2 begin2, Iter2 end2) : mVec(???) { ??? }
```
Such a constructor would catenate the two ranges [begin1, end1) and [begin2, end2) into mVec. The challenges are
1) I would like to preserve the const on mVec, so that it is considered constant throughout the other methods of X.
2) I would like to avoid unnecessary copies if at all possible. That is, one solution is to have a static method that constructs a non-const temporary to range 1, inserts range 2 and returns it, and then define the concatenating constructor to
```
template <typename Iter1, typename Iter2>
X(Iter1 begin1, Iter1 end1, Iter2 begin2, Iter2 end2)
: mVec(concatenate(begin1, end1, begin2, end2)) { }
```
but that copies all the values at least one extra time, I believe. | Nice problem. I would try to implement a particular iterator wrapper type that turns the two ranges into a single range. Something in the lines of:
```
// compacted syntax for brevity...
template <typename T1, typename T2>
struct concat_iterator
{
public:
typedef std::forward_iterator_tag iterator_category;
typedef typename iterator_traits<T1>::value_type value_type;
typedef *value_type pointer;
typedef &value_type reference;
concat_iterator( T1 b1, T1 e1, T2 b2, T2 e2 )
: seq1( b1 ), seq1end( e1 ), seq2( b2 ), seq2end( e2 );
iterator& operator++() {
if ( seq1 != seq1end ) ++seq1;
else ++seq2;
return this;
}
reference operator*() {
if ( seq1 != seq1end ) return *seq1;
else return *seq2;
}
pointer operator->() {
if ( seq1 != seq1end ) return &(*seq1);
else return &(*seq2);
}
bool operator==( concat_iterator const & rhs ) {
return seq1==rhs.seq1 && seq1end==rhs.seq2
&& seq2==rhs.seq2 && seq2end==rhs.seq2end;
}
bool operator!=( contact_iterator const & rhs ) {
return !(*this == rhs);
}
private:
T1 seq1;
T1 seq1end;
T2 seq2;
T2 seq2end;
};
template <typename T1, typename T2>
concat_iterator<T1,T2> concat_begin( T1 b1, T1 e1, T2 b2, T2 e2 )
{
return concat_iterator<T1,T2>(b1,e1,b2,e2);
}
template <typename T1, typename T2>
concat_iterator<T1,T2> concat_end( T1 b1, T1 e1, T2 b2, T2 e2 )
{
return concat_iterator<T1,T2>(e1,e1,e2,e2);
}
```
Now you could use:
```
class X {
public:
template <typename Iter, typename Iter2>
X(Iter b1, Iter e1, Iter2 b2, Iter2 e2 )
: mVec( concat_begin(b1,e1,b2,e2), concat_end(b1,e1,b2,e2) )
{}
private:
vector<Y> const mVec;
};
```
or (I have just thought of it) you don't need to redeclare your constructor. Make your caller use the helper functions:
```
X x( concat_begin(b1,e1,b2,e2), concat_end(b1,e1,b2,e2) );
```
I have not checked the code, just typed it here off the top of my head. It could compile or it could not, it could work or not... but you can take this as a start point. | It would probably be best to drop `const` (why would you insist on it anyway?).
Otherwise, you have to build a concatenating iterator. It is quite a lot of code, see [this thread](http://groups.google.com/group/boost-list/browse_thread/thread/f9027afd9e97d815) for more. | Concatenating C++ iterator ranges into a const vector member variable at construction time | [
"",
"c++",
"stl",
"constructor",
"iterator",
"concatenation",
""
] |
I'm getting a "not well-formed" error in the error console of Firefox 3.0.7 when the JavaScript on my page loads a text file containing an object in JavaScript Object Notation format. If the file contains nothing but the JSON object, it produces the error. If I wrap the object in <document></document> tags it does not produce the error. The request succeeds either way, so I could just ignore it, but I don't want my error log filling up with these messages.
Here is some example code to illustrate the problem. First, the "not well-formed" file called "data.json":
```
{ a: 3 }
```
Now some code to load the file:
```
var req = new XMLHttpRequest();
req.open("GET", "data.json");
req.send(null);
```
Which produces the following error in the Firefox error console:
**not well-formed**
file://path/to/data.json Line: 1
{ a: 3 }
- ^
If data.json is modified to this:
```
<document>{ a: 3 }</document>
```
There is no error. I assumed that it is complaining because the plain JSON file is not a well formed XML document, so I tried overriding the MIME type before the "send" call to force it to load as plain text, but that didn't work.
```
var req = new XMLHttpRequest();
req.open("GET", "data.json");
req.overrideMimeType("text/plain");
req.send(null);
// Still produces an error!
```
I am going to continue with wrapping my JSON data in an XML document to get around whatever validation the XMLHttpRequest is performing, but I'd like to know if there is any way I can force it to just load plain text uncritically and not try to validate it. Alternatively, is there another method of loading data besides XMLHttpRequest that can be used with plain text? | Have you tried using the MIME type for JSON?
```
application/json
```
You could also configure your server to send this MIME type automatically for .json files. | Firstly, true JSON is much stricter than JavaScript, and to be valid JSON, you have to have your keys quoted.
```
{ "a": 3 }
```
Also, as you are using a bare XMLHttpRequest, which generally expects to receive an XML result unless MIME headers specify strictly otherwise.
You may however wish to make your own life easier by simply using a JavaScript framework such as jQuery which will abstract away all this problem for you and deal with all the nasty edge cases.
```
$.getJSON("data.json",{}, function( data ){
/* # do stuff here */
});
```
Additionally, if you use both strict JSON and use a library to abstract it for you, when browsers start having native JSON parsers the library will be able to transparently make use of these and get a significant speed improvement.
( This is slated to happen sooner than later, and when it happens, your users will get a silent upgrade with no effort required! ). | "not well-formed" error in Firefox when loading JSON file with XMLHttpRequest | [
"",
"javascript",
"firefox",
"xmlhttprequest",
"mime-types",
""
] |
I'm working in wx.Python and I want to get the columns of my wx.ListCtrl to auto-resize i.e. to be at minimum the width of the column name and otherwise as wide as the widest element or its column name. At first I thought the ListCtrlAutoWidthMixin might do this but it doesn't so it looks like I might have to do it myself (Please correct me if there's a built in way of doing this!!!)
How can I find out how wide the titles and elements of my list will be rendered? | Yes, you would have to make this yourself for wx.ListCtrl and I'm not sure it would be easy (or elegant) to do right.
Consider using a wx.Grid, here is a small example to get you going:
```
import wx, wx.grid
class GridData(wx.grid.PyGridTableBase):
_cols = "This is a long column name,b,c".split(",")
_data = [
"1 2 3".split(),
"4,5,And here is a long cell value".split(","),
"7 8 9".split()
]
def GetColLabelValue(self, col):
return self._cols[col]
def GetNumberRows(self):
return len(self._data)
def GetNumberCols(self):
return len(self._cols)
def GetValue(self, row, col):
return self._data[row][col]
class Test(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None)
grid = wx.grid.Grid(self)
grid.SetTable(GridData())
grid.EnableEditing(False)
grid.SetSelectionMode(wx.grid.Grid.SelectRows)
grid.SetRowLabelSize(0)
grid.AutoSizeColumns()
app = wx.PySimpleApp()
app.TopWindow = Test()
app.TopWindow.Show()
app.MainLoop()
``` | In Addition to jakepars answer: this should check, whether the header is bigger, or the item which takes the most space in the column. Not to elegant but working...
```
import wx
class Frame(wx.Frame):
def __init__(self, *args, **kw):
wx.Frame.__init__(self, *args, **kw)
self.list = wx.ListCtrl(self, style=wx.LC_REPORT)
items = ['A', 'b', 'something really REALLY long']
self.list.InsertColumn(0, "AAAAAAAAAAAAAAAAAAAAAAAA")
for item in items:
self.list.InsertStringItem(0, item)
self.list.SetColumnWidth(0, wx.LIST_AUTOSIZE)
a = self.list.GetColumnWidth(0)
print "a " + str(a)
self.list.SetColumnWidth(0,wx.LIST_AUTOSIZE_USEHEADER)
b = self.list.GetColumnWidth(0)
print "b " + str(b)
if a>b:
print "a is bigger"
self.list.SetColumnWidth(0, wx.LIST_AUTOSIZE)
app = wx.App(False)
frm = Frame(None, title="ListCtrl test")
frm.Show()
app.MainLoop()
``` | How can I get the width of a wx.ListCtrl and its column name? | [
"",
"python",
"wxpython",
"wxwidgets",
"width",
"listctrl",
""
] |
Recently I've been doing a lot of these
```
enum Thing {
/* etc etc */
static final Set<Thing> allThings = EnumSet.allOf(Thing.class);
}
```
I want something similar in pre 1.5 Java, i.e. I want something like:
```
final class Thing {
private Thing(); // control instances within class
static final Thing instance0 = new Thing();
static final Thing instance1 = new Thing();
static final Set allThings = // ?????
}
```
How should I do this? | What about that:
```
final class Thing {
static final Set allThings = new HashSet();
private Thing() {
allThings.add(this);
} // control instances within class
static final Thing instance0 = new Thing();
static final Thing instance1 = new Thing();
}
``` | There was no direct equivalent in pre-1.5 Java.
Before Java 1.5, there were two (syntactically quirky) options if you wanted to initialize immediately:
```
static final Set allThings = new HashSet(Arrays.asList(new Object[] {
instance0, instance1, // etc.
}));
```
or
```
static final Set allThings = new HashSet() {{
add(instance0);
add(instance1);
// etc.
}};
```
Both of these have their drawbacks, though. The simpler way is to simply make a static method
```
private static Set all() {
Set ret = new HashSet();
ret.add(instance0);
ret.add(instance1);
// etc.
}
```
You still have to remember to add any new members to the method, but it's easier to read (for most people). | EnumSet for pre-1.5 fake enums? | [
"",
"java",
"reflection",
""
] |
Using JSTL's `forEach` tag, is it possible to iterate in reverse order? | When you are using `forEach` to create an integer loop, you can go forward or backward, but it requires some work. It turns out you cannot do this, for example:
```
<c:forEach var="i" begin="10" end="0" step="-1">
....
</c:forEach>
```
because the spec requires the step is positive. But you can always loop in forward order and then use `<c:var` to convert the incrementing number into a decrementing number:
```
<c:forEach var="i" begin="0" end="10" step="1">
<c:var var="decr" value="${10-i}"/>
....
</c:forEach>
```
However, when you are doing a `forEach` over a Collection of any sort, I am not aware of any way to have the objects in reverse order. At least, not without first sorting the elements into reverse order and **then** using `forEach`.
I have successfully navigated a `forEach` loop in a desired order by doing something like the following in a JSP:
```
<%
List list = (List)session.getAttribute("list");
Comparator comp = ....
Collections.sort(list, comp);
%>
<c:forEach var="bean" items="<%=list%>">
...
</c:forEach>
```
With a suitable Comparator, you can loop over the items in any desired order. This works. But I am not aware of a way to say, very simply, iterate in reverse order the collection provided. | Building on the answer given by [Eddie](https://stackoverflow.com/a/712062/578821), I used the following code to iterate over a collection in reverse order.
Given a collection called "list", which stores a list of people.
```
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<%-- Keep a reference to the size of the collection --%>
<c:set var="num_people" value="${fn:length(list)}" />
<%-- Iterate through items. Start at 1 to avoid array index out of bounds --%>
<c:forEach var="i" begin="1" end="${num_people}" step="1">
<c:set var="person" value="${list[num_people-i]}" />
${person.name}<br />
</c:forEach>
``` | JSTL forEach reverse order | [
"",
"java",
"jsp",
"jstl",
""
] |
I was under the impression that an endpoint was defined in a config file as the list of possible clients but that makes no sense (in the sense that I assumed it said what computers could connet to the service) now I'm gathering that it's more of a definition, so would someone please explain what an end point is to me? I understand the concept of definining the contract interface and then implementing the contract but I get lost somewhere between there and actually having something useable.
What is an address in this context? the host address?
A binding is the communications method/protocol to use correct?
the contract is the "object being shared" essentially (yes i know that's so technically incorrect but work with me here) | An endpoint is what a service exposes, and in WCF terms, is made up of three things:
* Address
* Binding
* Contract
Address is the URL by which the endpoint can be reached.
Binding dictates transformations that are applied as well as the shape (to some degree) of the messages sent to the implementation of the Contract at the Address.
Contract dictates what operations are being exposed at the address. It's exactly what it says it is, it's a contract to indicate what calls are permissible.
Most of the time, people remember it as A B C.
Some things to note:
The binding is typically going to be a combination of channels with behaviors applied; channels being elements on the channel stack which modify the message and perform actions before they get to the service implementation.
While commonly represented by an interface in .NET, it is not a requirement that a Contract be represented in this manner. Some design-first advocates will define the schemas to the messages that are going to be sent for the request and the response first, which is what WCF transforms the .NET Contract interface into. | I'm going to cite Juval Lowy's *Programming WCF Services* here:
> Every service is associated with an address that defines where the
> service is, a binding that defines how to communicate with the
> service, and a contract that defines what the service does. This
> triumvirate governing the service is easy to remember as the ABC of
> the service.
>
> WCF formalizes this relationship in the form of an endpoint. The
> endpoint is the fusion of the address, contract, and binding.
>
> Every endpoint must have all three elements, and the host exposes the
> endpoint. | What is an "endpoint" in WCF? | [
"",
"c#",
"wcf",
"endpoints",
""
] |
Learning Java, so be gentle please. Ideally I need to create an array of bytes that will point to a portion of a bigger array:
```
byte[] big = new byte[1000];
// C-style code starts
load(file,big);
byte[100] sub = big + 200;
// C-style code ends
```
I know this is not possible in Java and there are two work-arounds that come to mind and would include:
1. Either copying portion of *big* into *sub* iterating through *big*.
2. Or writting own class that will take a reference to *big + offset + size* and implementing the "subarray" through accessor methods using *big* as the actual underlying data structure.
The task I am trying to solve is to load a file into memory an then gain read-only access to the records stored withing the file through a class. The speed is paramount, hence ideally I'd like to avoid copying or accessor methods. And since I'm learning Java, I'd like to stick with it.
Any other alternatives I've got? Please do ask questions if I didn't explain the task well enough. | Creating an array as a "view" of an other array is not possible in Java. But you could use [java.nio.ByteBuffer](http://java.sun.com/javase/6/docs/api/java/nio/ByteBuffer.html), which is basically the class you suggest in work-around #2. For instance:
```
ByteBuffer subBuf = ByteBuffer.wrap(big, 200, 100).slice().asReadOnlyBuffer();
```
No copying involved (some object creation, though). As a standard library class, I'd also assume that ByteBuffer is more likely to receive special treatment wrt. "JIT" optimizations by the JVM than a custom one. | If you want to read a file fast and with low-level access, check the java nio stuff. Here's an example from [java almanac](http://www.exampledepot.com/egs/java.nio/ReadChannel.html).
You can use a mapped byte buffer to navigate within the file content. | In Java: is where a way to create a subarray that will point to a portion of a bigger array? | [
"",
"java",
"performance",
""
] |
Or, "am I doing it wrong"?
I am writing a small function that will return a string, quoted (as quoted-printable) if necessary, otherwise it returns it as is. A character is input into the function; the result is a string.
What I tried to do at first was:
```
private string QuotedChar(char ch) {
if(ch < (char)128 && !char.IsWhiteSpace(ch))
return(new string(ch));
// ...
}
```
However, the compiler says CS0214, "Pointers and fixed size buffers may only be used in an unsafe context", when compiling that return statement. If I change the code to say instead:
```
private string QuotedChar(char ch) {
if(ch < (char)128 && !char.IsWhiteSpace(ch))
return(new string(new char[] { ch }));
// ...
}
```
... it works just fine. However that seems rather pointless. I don't understand why it thinks I am trying to use a pointer or a fixed size buffer, since it's just a char. Am I missing something seriously silly, or is this a problem/bug?
FYI, this is Mono 2.0, not the Microsoft .NET Framework. I don't run Windows, so I don't have Microsoft's C# compiler to see if it does the same thing or not, which is why I wonder if it is a bug. | Well, it's not a bug that it doesn't compile. There's no string constructor overload which takes a char. I suspect that Mono thought you meant the `string(char*)` constructor and tried that - leading to the error.
The simplest way of converting a `char` to a `string` is simply to call `ToString()` though:
```
private string QuotedChar(char ch) {
if(ch < (char)128 && !char.IsWhiteSpace(ch))
return ch.ToString()
// ...
}
```
The MS C# compiler guesses the same overload, but gives a different error message:
> Test.cs(8,20): error CS1502: The best
> overloaded method match for
> `'string.String(char*)'` has some
> invalid arguments
> Test.cs(8,31): error CS1503: Argument
> '1': cannot convert from `'char'` to `'char*'` | The same code compiled in .NET would give the error message that there was no overload for the string constructor that takes a char as parameter. The closest match is the one that takes a pointer to a char, so that may be why you get that error message in Mono.
You can use the overload that takes a char and a count:
```
return new String(ch, 1);
```
Or you can use the ToString method:
```
return ch.ToString();
```
Or the static ToString method:
```
return Char.ToString(ch);
``` | Why does the compiler require convoluted syntax for this? | [
"",
"c#",
".net",
"string",
"mono",
"char",
""
] |
I have a jQuery UI Dialog working great on my ASP.NET page:
```
jQuery(function() {
jQuery("#dialog").dialog({
draggable: true,
resizable: true,
show: 'Transfer',
hide: 'Transfer',
width: 320,
autoOpen: false,
minHeight: 10,
minwidth: 10
});
});
jQuery(document).ready(function() {
jQuery("#button_id").click(function(e) {
jQuery('#dialog').dialog('option', 'position', [e.pageX + 10, e.pageY + 10]);
jQuery('#dialog').dialog('open');
});
});
```
My div:
```
<div id="dialog" style="text-align: left;display: none;">
<asp:Button ID="btnButton" runat="server" Text="Button" onclick="btnButton_Click" />
</div>
```
But the btnButton\_Click is never called... How can I solve that?
More information: I added this code to move div to form:
```
jQuery("#dialog").parent().appendTo(jQuery("form:first"));
```
But still without success... | You are close to the solution, just getting the wrong object. It should be like this:
```
jQuery(function() {
var dlg = jQuery("#dialog").dialog({
draggable: true,
resizable: true,
show: 'Transfer',
hide: 'Transfer',
width: 320,
autoOpen: false,
minHeight: 10,
minwidth: 10
});
dlg.parent().appendTo(jQuery("form:first"));
});
``` | ```
$('#divname').parent().appendTo($("form:first"));
```
Using this code solved my problem and it worked in every browser, Internet Explorer 7, Firefox 3, and Google Chrome. I start to love jQuery... It's a cool framework.
I have tested with partial render too, exactly what I was looking for. ***Great!***
```
<script type="text/javascript">
function openModalDiv(divname) {
$('#' + divname).dialog({ autoOpen: false, bgiframe: true, modal: true });
$('#' + divname).dialog('open');
$('#' + divname).parent().appendTo($("form:first"));
}
function closeModalDiv(divname) {
$('#' + divname).dialog('close');
}
</script>
...
...
<input id="Button1" type="button" value="Open 1" onclick="javascript:openModalDiv('Div1');" />
...
...
<div id="Div1" title="Basic dialog" >
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
postback test<br />
<asp:Button ID="but_OK" runat="server" Text="Send request" /><br />
<asp:TextBox ID="tb_send" runat="server"></asp:TextBox><br />
<asp:Label ID="lbl_result" runat="server" Text="prova" BackColor="#ff0000></asp:Label>
</ContentTemplate>
<asp:UpdatePanel>
<input id="Button2" type="button" value="cancel" onclick="javascript:closeModalDiv('Div1');" />
</div>
``` | jQuery UI Dialog with ASP.NET button postback | [
"",
"c#",
"asp.net",
"jquery",
"jquery-ui",
"postback",
""
] |
I have created a small daemon (basically a console application that hides the console and runs).
I need to send it to a user and have tried renaming the executable with a different extension, emailing it to the user, and having them rename it to the correct name.
This seems to work when I email it to myself to test it. However, when the user tries to run the executable it produces the following error message:
> This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix the problem.
What am I doing wrong? | You are missing some dlls.
You can figure out exactly which ones using [dependency walker](http://www.dependencywalker.com/).
You could also install the [Visual Studio Re-distributable package (x86)](http://www.microsoft.com/downloads/details.aspx?FamilyID=9b2da534-3e03-4391-8a4d-074b9f2bc1bf&displaylang=en) or [Visual Studio Re-distributable package (x64)](http://www.microsoft.com/downloads/details.aspx?familyid=bd2a6171-e2d6-4230-b809-9a8d7548c1b6&displaylang=en) and that will probably fix your problem too. | This is kind of funny... I just hit this error for the first time a few minutes ago at work. In our case, we were using a C++ application and were trying to run the resultant executable on another computer on the network. You need the [Visual C++ Redistributable package](http://www.microsoft.com/downloads/details.aspx?FamilyID=9b2da534-3e03-4391-8a4d-074b9f2bc1bf&displaylang=en).
I'm assuming here that you're using Visual Studio 2008 -- if it's a different version you may need that. Alternatively, you can just copy the DLLs with the executable and it will run like that.
Let me know if this doesn't apply... | Renaming executable causes error when run | [
"",
"c++",
"email",
"executable",
""
] |
Say I got this C++ code:
```
class class1{
class2 *x;
}
class class2{
class1 *x;
}
```
The compiler would give an error in line 2 because it couldn't find class2, and the same if i switched the order of the classes. How do I solve this? | Two things - one, you need semicolons after class declarations:
```
class class1{
class2 *x;
};
class class2{
class1 *x;
};
```
Two, you can create a declaration in front of the definitions of the classes. That tells the compiler that this class exists, and you have yet to define it. In this case, put a `class2` declaration in front of the definition of `class1`:
```
class class2 ;
class class1{
class2 *x;
};
class class2{
class1 *x;
};
``` | Refer [Forward declarations](http://www.learncpp.com/cpp-tutorial/17-forward-declarations/) | In which order should classes be declared in C++? | [
"",
"c++",
"class",
""
] |
I have a list of elements with attrs: parent, level, is\_leaf\_node, is\_root\_node, is\_child\_node.
I want to convert this list to hierarchy dict.
Example of output dict:
```
{
'Technology':
{
'Gadgets':{},
'Gaming':{},
'Programming':
{
'Python':{},
'PHP':{},
'Ruby':{},
'C++':{}
},
'Enterprise':{},
'Mac':{},
'Mobile':{},
'Seo':{},
'Ui':{},
'Virtual Worlds':{},
'Windows':{},
},
'News':{
'Blogging':{},
'Economics':{},
'Journalism':{},
'Politics':{},
'News':{}
},}
```
I don't know algorithm. How to do it? | Here's a less sophisticated, recursive version like chmod 700 described. Completely untested of course:
```
def build_tree(nodes):
# create empty tree to fill
tree = {}
# fill in tree starting with roots (those with no parent)
build_tree_recursive(tree, None, nodes)
return tree
def build_tree_recursive(tree, parent, nodes):
# find children
children = [n for n in nodes if n.parent == parent]
# build a subtree for each child
for child in children:
# start new subtree
tree[child.name] = {}
# call recursively to build a subtree for current node
build_tree_recursive(tree[child.name], child, nodes)
``` | Everything without a parent is your top level, so make those dicts first. Then do a second pass through your array to find everything with a parent at that top level, etc... It could be written as a loop or a recursive function. You really don't need any of the provided info besides "parent". | Converting tree list to hierarchy dict | [
"",
"python",
"tree",
"hierarchical-trees",
""
] |
I'm working with a program that uses two-dimensional arrays of Strings (probably not that smart to begin with, but eh), and I'd like to write a function that takes one of these arrays (let's say array1), makes an independent copy, and returns it (let's say array2). However, when I then change a value in array2, it seems to be reflected in array1.
My function currently looks something like this:
```
public static String[][] copy(String[][] matrix, int n) {
String[][] out = new String[n+1][n+1];
for (int i = 0; i < n+1; i++)
for (int j = 0; j < n+1; j++) {
if(matrix[i][j] != null) {
String cp = new String(matrix[i][j]);
out[i][j] = cp;
}
}
return out;
}
```
I declare a new array of Strings, and then iterate through it, copying each value individually. When that didn't work, I even tried explicitly declaring a new string from each old string and putting that in the array instead.
Can anyone tell me where I'm going wrong? | Your method looks like it should work, though passing in n as a parameter makes it brittle, using the input array's length field would be better, and you could even handle jagged arrays that way.
Making a copy of the contents is not necessary, since Strings cannot be changed - which leads to the main question: What kind of changes are you making that seem to be reflected in the copy? Show us the code that does this. | I'm not sure what the `n` parameter is for, but if I needed such a function, I'd use something like this:
```
public static String[][] copy(String[][] matrix) {
String[][] copy = new String[matrix.length];
for (int idx = 0; idx < matrix.length; ++idx)
copy[idx] = matrix[idx].clone();
return copy;
}
```
You don't need to create a copy of the `String`, because they are immutable. As pointed out by Michael in the comments, the `String(String)` constructor might be useful if the original string was created as a substring of some very large string. Another use is when you are using `String` objects as locks (not recommended), and want a private instance to avoid deadlocks.
Also, your check to see whether an element is null before assigning is unnecessary; if you have your loops setup correctly, the element is guaranteed to be null. (And if it's not, what's the harm in overwriting it?) | How do I copy a two dimensional array of strings? | [
"",
"java",
"arrays",
"pointers",
"string",
""
] |
I'm writing a method to return an 'asset' row from the database. It contains strings, ints and a byte array (this could be an image/movie/document).
Now for most row access I use the following method which returns a NameValueCollection as it is a light weight object, easy to use and cast int and strings.
```
public static NameValueCollection ReturnNameValueCollection(Database db, DbCommand dbCommand)
{
var nvc = new NameValueCollection();
using (IDataReader dr = db.ExecuteReader(dbCommand))
{
if (dr != null)
{
while (dr.Read())
{
for (int count = 0; count < dr.FieldCount; count++)
{
nvc[dr.GetName(count)] = dr.GetValue(count).ToString();
}
}
}
}
dbCommand.Dispose();
return nvc.Count != 0 ? nvc : null;
}
```
Now my apporach for this kind of data access would normally be to get a method to return a datarow.
```
public static DataRow ReturnDataRow(Database db, DbCommand dbCommand)
{
var dt = new DataTable();
using (IDataReader dr = db.ExecuteReader(dbCommand))
if (dr != null) dt.Load(dr);
dbCommand.Dispose();
return dt.Rows.Count != 0 ? dt.Rows[0] : null;
}
```
It does seem kind of wastefull to create a DataTable and then return its first datarow.
Is there better way to do this?
I'm thinking maybe a Dictionary of objects which I then manually cast each member of.
Would be interesting to see how others have tackled this. I know this kinda falls into the field of micro optimisation and as long as I'm not returning DataSets for each row query (wish I had a pound for everytime I saw that in a line of code) it should be ok.
That said this method is likely to be called for allot of data access queries on allot of sites on one box.
Cheers
Steve | how's it going?
Is there a reason you don't have object containers that represent a row in your database? Creating a custom object is much easier to deal with in other tiers of your solution. So, going with this approach, there are two very viable solutions to your problems.
Say you have a custom object that represents a Product in your database. You'd define the object like this:
```
public class Product {
public int ProductID { get; set; }
public string Name { get; set; }
public byte[] Image { get; set; }
}
```
And you'd fill a collection of of Products (Collection) like this:
```
var collection = new Collection<Product>();
using (var reader = command.ExecuteReader()) {
while (reader.Read()) {
var product = new Product();
int ordinal = reader.GetOrdinal("ProductID");
if (!reader.IsDBNull(ordinal) {
product.ProductID = reader.GetInt32(ordinal);
}
ordinal = reader.GetOrdinal("Name");
if (!reader.IsDBNull(ordinal)) {
product.Name = reader.GetString(ordinal);
}
ordinal = reader.GetOrdinal("Image");
if (!reader.IsDBNull(ordinal)) {
var sqlBytes = reader.GetSqlBytes(ordinal);
product.Image = sqlBytes.Value;
}
collection.Add(product);
}
}
```
Notice that I'm retrieving a value via the reader's Get*x* where *x* is the type that I want to retrieve from the column. This is Microsoft's recommended way of retrieving data for a column per <http://msdn.microsoft.com/en-us/library/haa3afyz.aspx> (second paragraph) because the retrieved value doesn't have to be boxed into System.Object and unboxed into a primitive type.
Since you mentioned that this method will be called many, many times, in an ASP.NET application, you may want to reconsider such a generic approach as this. The method you use to return a *NameValueCollection* is very non-performant in this scenario (and arguably in many other scenarios). Not to mention that you convert each database column to a string without accounting for the current user's Culture, and Culture is an important consideration in an ASP.NET application. I'd argue that this *NameValueCollection* shouldn't be used in your other development efforts as well. I could go on and on about this, but I'll save you my rants.
Of course, if you're going to be creating objects that directly map to your tables, you might as well look into [LINQ to SQL](http://msdn.microsoft.com/en-us/library/bb386976.aspx) or the [ADO.NET Entity Framework](http://msdn.microsoft.com/en-us/data/aa937723.aspx). You'll be happy you did. | In terms of efficiency of code, you've probably done it in the least keystrokes, and while it seems wasteful, is probably the simplest to maintain. However, if you're all about efficiency of only doing what is strictly necessary you can create a lightweight struct/class to populate with the data and use something similar to:
```
public class MyAsset
{
public int ID;
public string Name;
public string Description;
}
public MyAsset GetAsset(IDBConnection con, Int AssetId)
{
using (var cmd = con.CreateCommand("sp_GetAsset"))
{
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(cmd.CreateParameter("AssetID"));
using(IDataReader dr = cmd.ExecuteReader())
{
if (!dr.Read()) return null;
return new MyAsset() {
ID = dr.GetInt32(0),
Name = dr.GetString(1),
Description = dr.GetString(2)
};
}
}
}
```
Likewise, you could dump the data in similar fashion right into your collection of KVPs...
It's not quite as clean looking as your original code, but it doesn't create the whole table just to get the single row...
As has been mentioned in another post regarding the code smell though, I probably wouldn't pass the command in as a parameter, I think I would be more likely to encapsulate the command inside this method, passing only the database connection and the id of the asset I wanted - assuming I didn't use caching of course, and passing back out the MyAsset instance. This keeps the method generic enough that it could be used on any database type - assuming the stored proc existed of course. This way the rest of my code is shielded from needing to know anything about the database other than what type of database it is... and throughout the rest of my app, I can reference asset info using MyAssetInstance.ID, MyAssetInstance.Name, MyAssetInstance.Description etc... | Most Efficient Way To Get A Row Of Data From DB In ASP.NET | [
"",
"c#",
"asp.net",
"optimization",
"data-access",
""
] |
I'm using TPTP to profile some slow running Java code an I came across something interesting. One of my private property getters has a large Base Time value in the Execution Time Analysis results. To be fair, this property is called many many times, but I never would have guessed a property like this would take very long:
```
public class MyClass{
private int m_myValue;
public int GetMyValue(){
return m_myValue;
}
}
```
Ok so there's obviously more stuff in the class, but as you can see there is nothing else happening when the getter is called (just return an int). Some numbers for you:
* About 30% of the Calls of the run are
on the getter (I'm working to reduce
this)
* About 25% of the base time of
the run is spent in this getter
* Average base time is 0.000175s
For comparison, I have another method in a different class that uses this getter:
```
private boolean FasterMethod(MyClass instance, int value){
return instance.GetMyValue() > m_localInt - value;
}
```
Which has a much lower average base time of 0.000018s (one order of magnitude lower).
What's the deal here? I assume there is something that I don't understand or something I'm missing:
1. Does returning a local primitive really take longer than returning a calculated value?
2. Should I look at metric other than Base Time?
3. Are these results misleading and I need to consider some other profiling tool?
**Edit 1:** Based on some suggestions below, I marked the method as final and re-ran the test, but I got the same results.
**Edit 2:** I installed a demo version of YourKit to re-run my performance tests, and the YourKit results look much closer to what I was expecting. I will continue to test YourKit and report back what I find.
**Edit 3:** Changing to YourKit seems to have resolved my issue. I was able to use YourKit to determine the *actual* slow points in my code. There are some excellent comments and posts below (upvoted appropriately), but I'm accepting the first person to suggest YourKit as "correct." (I am not affiliated with YourKit in any way / YMMV) | That sounds very peculiar. You're not calling an overriding method by mistake, are you ?
I would be tempted to download [a demo version of YourKit](http://www.yourkit.com/). It's trivial to set up, and it should give an indication as to what's really occurring. If both TPTP and YourKit agree, then something peculiar is happening (and I know that's not a lot of help!) | If possible try using another profiler (the Netbeans one works well). This may be hard to do depending on how your code is setup.
It is possible that, just like many other tools, a different profiler will result in different information.
> Does returning a local primitive really take longer than returning a
> calculated value?
Returning an instance variable takes longer than returning an local variable (VM dependent). The getter that you have is simple so it should be inlined, so it becomes as fast as accessing a public instance variable (which, again, is slower than accessing a local variable).
But you don't have a local value (local meaning in the method as opposed to in the class).
What exactly do you mean by "local"?
> Should I look at metric other than Base Time?
I have not used the Eclipse tools, so I am not sure how it works... it might make a difference if it is a tracing or a sampling profiler (the two can give different results for things like this).
> Are these results misleading and I need to consider some other
> profiling tool?
I would consider another tool, just to see if the result is the same.
Edit based on comments:
If it is a sampling profiler what happens, essentially, that every "n-time units" the program is sampled to see where the program is. If you are calling the one method way more than the other it will show up as being in the method that is called more (it is simply more likely that that method is being run).
A tracing profiler adds code to your program (a process known as instrumentation) to essentially log what is going on.
Tracing profilers are slower but more accurate, they also require that the program be changed (the instrumentation process) which could potentially introduce bugs (not that I have heard of it happening... but I am sure it does at least while they are developing the profiler).
Sampling profilers are faster but less accurate (they just guess at how often a line of code is executed).
So, if Eclipse uses a sampling profiler you could see what you consider to be strange behaviour. Changing to a tracing profiler would show more accurate results.
If Eclipse uses a tracing profiler then chaning profilers should show the same result (however they new profiler may make it more obvious to you as to what is going on). | Java Profiling: Private Property Getter has Large Base Time | [
"",
"java",
"performance",
"profiling",
"eclipse-tptp",
""
] |
I need to pass javascript date value to vb.net function.
Method iam using now:
convert javascript date to string
store it in hiddenfield
retrieve string from hidden field in server code and parse it using date.parse
the trouble is that the Javascript dateformats
toString() - Sat Apr 4 22:19:00 UTC+0530 2009
toDateString() - Sat Apr 4 2009
toLocaleString() - Saturday, April 04, 2009 10:19:00 PM
doesnt match vb date format. I am getting error that its unparseable.
Thanks in advance for the help | The problem with using ToLocaleString is that you lose timezone info and its obviously locale specific which means you need to parse it with the right culture.
I was thinking:-
DateTime d = DateTime.ParseExact(sInput, "ddd MMM d HH:mm:ss UTCzzzz yyyy" , CultureInfo.InvariantCulture);
But that isn't cross browser compliant (the ECMA spec does not define what toString should actually do).
However we do know that the value of a Javascript Date object is the number of milliseconds from midnight Jan 1, 1970. Hence you could instead store the .valueOf of a date object in your hidden field. Use Int32.Parse on the string first, create a TimeSpan from the that value and add it to a DateTime of Jan 1, 1970 00:00:00 UTC+0000.
```
int milliseconds = Int32.Parse(inputString);
TimeSpan t = TimeSpan.FromMilliseconds(milliseconds);
DateTime base = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
DateTime result = base + t;
``` | Why not instead pass the Javascript date as a string and then convert it to a date type in VB.net.
```
Public Function ConvertJavaScriptDate(ByVal d as String) As Date
Return Date.Parse(d)
End Function
```
Another option is to use CType(d,Date). CType is a lexical cast that will try a variety of ways to convert the string value to a Date.
I'm not terribly familiar with the difference between a JavaScript Date and a VB.Net Date in terms of format, but if you post an example I'm sure we can get a basic conversion going. | sending javascript date to vb.net date variable | [
"",
"javascript",
"vb.net",
"asp.net-2.0",
""
] |
I have two arrays. For example:
```
int[] Array1 = new[] {1, 2, 3, 4, 5, 6, 7, 8, 9};
int[] Array2 = new[] {9, 1, 4, 5, 2, 3, 6, 7, 8};
```
What is the best way to determine if they have the same elements? | Assuming that the values in the array are unique, you can implement a performant solution using LINQ:
```
// create a LINQ query that matches each item in ar1 with
// its counterpart in ar2. we select "1" because we're only
// interested in the count of pairs, not the values.
var q = from a in ar1
join b in ar2 on a equals b
select 1;
// if lengths of the arrays are equal and the count of matching pairs
// is equal to the array length, then they must be equivalent.
bool equals = ar1.Length == ar2.Length && q.Count() == ar1.Length;
// when q.Count() is called, the join in the query gets translated
// to a hash-based lookup code which can run faster than nested
// for loops.
``` | You could also use [`SequenceEqual`](https://msdn.microsoft.com/en-us/library/bb348567(v=vs.110).aspx), provided the IEnumerable objects are sorted first.
```
int[] a1 = new[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] a2 = new[] { 9, 1, 4, 5, 2, 3, 6, 7, 8 };
bool equals = a1.OrderBy(a => a).SequenceEqual(a2.OrderBy(a => a));
``` | Testing equality of arrays in C# | [
"",
"c#",
"arrays",
""
] |
In my C++ header files I try to use forward declarations (class MyClass;) instead of #including the class header, as recommended in many C++ coding standards (the Google C++ Style Guide is one).
Unfortunately, when I introduce enumerations, I can't do the forward declaration any more. Like this:
```
//// myclass1.hpp ////
class MyClass1
{
enum MyEnum1
{
Enum_A, Enum_B, Enum_C
};
};
//// myclass2.hpp ////
// I want to avoid this
#include "myclass1.hpp"
// I'd prefer to do this (forward declaration)
class MyClass1;
class MyClass2
{
// This is o.k.: I only need to forward declare MyClass1
MyClass1* ptr;
// This forces me to #include, but I don't want to!
void func( MyClass1::MyEnum1 e );
};
```
The best solution I can think of so far is to replace enums with member constants:
```
//// myclass1.hpp ////
MyClass1
{
static const int Enum_A;
static const int Enum_B;
static const int Enum_C;
};
//// myclass1.cpp ////
const int Enum_A = 1;
const int Enum_B = 2;
const int Enum_C = 3;
```
In this case, though, the solution seems worse than the problem.
I'm currently looking through *Large Scale C++ Software Design* (Lakos) and *Working Effectively with Legacy Code* (Feathers) for dependency breaking techniques, but I haven't found a good solution yet. | You cannot forward declare enum values - and your workaround is a step down the path to complete madness.
Are you experiencing any major compilation slowdowns caused by #including headers? If not, just #include them. Use of forward declarations is **not** "best practice" it is a hack. | This is difficult to do nicely. Perhaps moving `enum`s to a common header file would be a reasonable solution?
Edit: I know the question asked to avoid including a header file, but there's just no way (AFAIK) to do this. Moving enums to a separate header file at least minimises the amount of stuff in the header file you do need to include. It's certainly better than the craziness suggested in the question! | In C++, how can I avoid #including a header file when I need to use an enumeration? | [
"",
"c++",
"include",
"header",
"dependencies",
""
] |
In C++, a function template specialization is supposed to act exactly like a normal function. Does that mean that I can make one virtual?
For example:
```
struct A
{
template <class T> void f();
template <> virtual void f<int>() {}
};
struct B : A
{
template <class T> void f();
template <> virtual void f<int>() {}
};
int main(int argc, char* argv[])
{
B b;
A& a = b;
a.f<int>();
}
```
[Visual Studio 2005](http://en.wikipedia.org/wiki/Microsoft_Visual_Studio#Visual_Studio_2005) gives me the following error:
> fatal error C1001: An internal error has occurred in the compiler. | Nice compiler error. For this type of checks I always fallback to the [Comeau](http://www.comeaucomputing.com/tryitout) compiler before going back to the standard and checking.
> Comeau C/C++ 4.3.10.1 (Oct 6 2008
> 11:28:09) for ONLINE\_EVALUATION\_BETA2
> Copyright 1988-2008 Comeau Computing.
> All rights reserved. MODE:strict
> errors C++ C++0x\_extensions
>
> "ComeauTest.c", line 3: error:
> "virtual" is not allowed in a function
> template
> declaration
> template virtual void f();
> ^
>
> "ComeauTest.c", line 10: error:
> "virtual" is not allowed in a function
> template
> declaration
> template virtual void f();
> ^
Now, as it has been posted by another user, the fact is that the standard does not allow you to define virtual templated methods. The rationale is that for all virtual methods, an entry must be reserved in the vtable. The problem is that template methods will only be defined when they have been instantiated (used). This means that the vtable would end up having a different number of elements in each compilation unit, depending on how many different calls to *f()* with different types happen. Then hell would be raised...
If what you want is a templated function on one of its arguments and one specific version being virtual (note the part of the argument) you can do it:
```
class Base
{
public:
template <typename T> void f( T a ) {}
virtual void f( int a ) { std::cout << "base" << std::endl; }
};
class Derived : public Base
{
public:
virtual void f( int a ) { std::cout << "derived" << std::endl; }
};
int main()
{
Derived d;
Base& b = d;
b.f( 5 ); // The compiler will prefer the non-templated method and print "derived"
}
```
If you want this generalized for any type, then you are out of luck. Consider another type of delegation instead of polymorphism (aggregation + delegation could be a solution). More information on the problem at hand would help in determining a solution. | According to <http://www.kuzbass.ru:8086/docs/isocpp/template.html> ISO/IEC 14882:1998:
> -3- A member function template shall not be virtual.
Example:
```
template <class T> struct AA {
template <class C> virtual void g(C); // Error
virtual void f(); // OK
};
``` | Is making a function template specialization virtual legal? | [
"",
"c++",
"templates",
"virtual",
"specialization",
"c1001",
""
] |
I have `IQueryable<>` object.
I want to Convert it into `List<>` with selected columns like `new { ID = s.ID, Name = s.Name }`.
Edited
Marc you are absolutely right!
but I have only access to `FindByAll()` Method (because of my architecture).
And it gives me whole object in `IQueryable<>`
And I have strict requirement( for creating json object for select tag) to have only `list<>` type with two fields. | Then just `Select`:
```
var list = source.Select(s=>new { ID = s.ID, Name = s.Name }).ToList();
```
(edit) Actually - the names could be inferred in this case, so you could use:
```
var list = source.Select(s=>new { s.ID, s.Name }).ToList();
```
which saves a few electrons... | Add the following:
```
using System.Linq
```
...and call `ToList()` on the `IQueryable<>`. | Convert IQueryable<> type object to List<T> type? | [
"",
"c#",
"list",
"iqueryable",
""
] |
Anyone have a t-sql function that takes a querystring from a url and returns a table of name/value pairs?
eg I have a value like this stored in my database:
```
foo=bar&baz=qux&x=y
```
and I want to produce a 2-column (key and val) table (with 3 rows in this example), like this:
```
name | value
-------------
foo | bar
baz | qux
x | y
```
UPDATE: there's a reason I need this in a t-sql function; I can't do it in application code. Perhaps I could use CLR code in the function, but I'd prefer not to.
UPDATE: by 'querystring' I mean the part of the url after the '?'. I don't mean that part of a query will be in the url; the querystring is just used as data. | ```
create function dbo.fn_splitQuerystring(@querystring nvarchar(4000))
returns table
as
/*
* Splits a querystring-formatted string into a table of name-value pairs
* Example Usage:
select * from dbo.fn_splitQueryString('foo=bar&baz=qux&x=y&y&abc=')
*/
return (
select 'name' = SUBSTRING(s,1,case when charindex('=',s)=0 then LEN(s) else charindex('=',s)-1 end)
, 'value' = case when charindex('=',s)=0 then '' else SUBSTRING(s,charindex('=',s)+1,4000) end
from dbo.fn_split('&',@querystring)
)
go
```
Which utilises [this](https://stackoverflow.com/questions/314824/) general-purpose split function:
```
create function dbo.fn_split(@sep nchar(1), @s nvarchar(4000))
returns table
/*
* From https://stackoverflow.com/questions/314824/
* Splits a string into a table of values, with single-char delimiter.
* Example Usage:
select * from dbo.fn_split(',', '1,2,5,2,,dggsfdsg,456,df,1,2,5,2,,dggsfdsg,456,df,1,2,5,2,,')
*/
AS
RETURN (
WITH Pieces(pn, start, stop) AS (
SELECT 1, 1, CHARINDEX(@sep, @s)
UNION ALL
SELECT pn + 1, stop + 1, CHARINDEX(@sep, @s, stop + 1)
FROM Pieces
WHERE stop > 0
)
SELECT pn,
SUBSTRING(@s, start, CASE WHEN stop > 0 THEN stop-start ELSE 4000 END) AS s
FROM Pieces
)
go
```
Ultimately letting you do something like this:
```
select name, value
from dbo.fn_splitQuerystring('foo=bar&baz=something&x=y&y&abc=&=whatever')
``` | I'm sure TSQL could be coerced to jump through this hoop for you, but why not parse the querystring in your application code where it most probably belongs?
Then you can look at [this answer](https://stackoverflow.com/questions/574868/c-asp-net-querystring-parser) for what others have done to parse querystrings into name/value pairs.
Or [this answer](https://stackoverflow.com/questions/506636/whats-the-quickest-way-to-dedupe-a-querystring-in-c-asp-net).
Or [this](https://stackoverflow.com/questions/562943/looping-through-a-request-querystring-in-vb-net).
Or [this](http://www.google.co.uk/search?q=querystring+name+value+parse). | sql function to return table of names and values given a querystring | [
"",
"sql",
"sql-server",
"function",
"user-defined-functions",
""
] |
What is the difference between using a `PropertyDescriptor` that returns a value for the `IsReadOnly()` method, and one that is associated with a `ReadOnlyAttribute`? | The main difference is that this allows you to seize more control if you provide your own `PropertyDescriptor` implementation (via `ICustomTypeDescriptor`, `TypeDescriptionProvider` or `TypeConverter`). Then you can choose your *own* logic for when it is writeable - for example, based on access rights.
But yes; under the default implementation, it will report read-only for properties without setters, and for properties marked with `ReadOnlyAttribute`. | No difference when I look at it using Reflector.
One of the derived class SimplePropertyDescriptor has the following code.
```
public override bool IsReadOnly
{
get
{
return this.Attributes.Contains(ReadOnlyAttribute.Yes);
}
}
``` | ReadOnlyAttribute vs PropertyDescriptor.IsReadOnly() | [
"",
"c#",
"attributes",
"readonly",
"propertydescriptor",
""
] |
I want to add an int into an array, but the problem is that I don't know what the index is now.
```
int[] arr = new int[15];
arr[0] = 1;
arr[1] = 2;
arr[2] = 3;
arr[3] = 4;
arr[4] = 5;
```
That code works because I know what index I am assigning to, but what if I don't know the index...
In PHP, I can just do `arr[]=22;`, which will automatically add 22 to the next empty index of the array. But in C++ I can't do that, it gives me a compiler error. What do you guys suggest? | There is no way to do what you say in C++ with plain arrays. The C++ solution for that is by using the STL library that gives you the [`std::vector`](http://en.cppreference.com/w/cpp/container/vector).
You can use a `vector` in this way:
```
#include <vector>
std::vector< int > arr;
arr.push_back(1);
arr.push_back(2);
arr.push_back(3);
``` | Arrays in C++ cannot change size at runtime. For that purpose, you should use `vector<int>` instead.
```
vector<int> arr;
arr.push_back(1);
arr.push_back(2);
// arr.size() will be the number of elements in the vector at the moment.
```
As mentioned in the comments, `vector` is defined in `vector` header and `std` namespace. To use it, you should:
`#include <vector>`
and also, either use `std::vector` in your code or add
```
using std::vector;
```
or
```
using namespace std;
```
after the `#include <vector>` line. | How to add element to C++ array? | [
"",
"c++",
"arrays",
""
] |
I need to programmatically find out exactly how much memory a given Java Object is occupying including the memory occupied by the objects that it is referencing.
I can generate a memory heap dump and analyse the results using a tool. However it takes a considerable amount of time to generate a heap dump and for such a tool to read the dump to generate reports. Given the fact that I will probably need to do this several times, my work would be a lot more agile if I could throw in some code in my project that would give me this value "runtime".
How could I best achieve this?
ps: Specifically I have a collection of objects of type javax.xml.transform.Templates | You will need to use **reflection** for that. The resulting piece of code is too complicated for me to post here (although it will soon be available as part of a GPL toolkit I am building), but the main idea is:
* An object header uses 8 bytes (for class pointer and reference count)
* Each primitive field uses 1, 2, 4 or 8 bytes depending on the actual type
* Each object reference (i.e. non-primitive) field uses 4 bytes (the reference, plus whatever the referenced object uses)
You need to treat arrays separately (8 bytes of header, 4 bytes of length field, 4\*length bytes of table, plus whatever the objects inside are using). You need to process other types of objects iterating through the fields (and it's parents fields) using reflection.
You also need to keep a set of "seen" objects during the recursion, so as not to count multiple times objects referenced in several places. | Looks like there is already a utility for doing this called [Classmexer](http://www.javamex.com/classmexer/).
I haven't tried it myself, but I would go that route before I rolled my own. | Programmatically calculate memory occupied by a Java Object including objects it references | [
"",
"java",
"memory-management",
""
] |
Suppose I have a model:
```
class SomeModel(models.Model):
id = models.AutoField(primary_key=True)
a = models.CharField(max_length=10)
b = models.CharField(max_length=7)
```
Currently I am using the default Django admin to create/edit objects of this type.
How do I remove the field **`b`** from the Django admin so that each object *cannot* be created with a value, and rather will receive a default value of `0000000`? | Set `editable` to `False` and `default` to your default value.
<http://docs.djangoproject.com/en/stable/ref/models/fields/#editable>
```
b = models.CharField(max_length=7, default='0000000', editable=False)
```
Also, your `id` field is unnecessary. Django will add it automatically. | You can also use a callable in the default field, such as:
```
b = models.CharField(max_length=7, default=foo)
```
And then define the callable:
```
def foo():
return 'bar'
``` | How can I set a default value for a field in a Django model? | [
"",
"python",
"django",
"django-models",
"django-admin",
""
] |
I have a program that displays messages posted to a forum. Right now, I am using the Response.Write method in the code behind to insert the HTML I want. But I would much rather avoid putting HTML in the code behind (because it is not in the spirit of the whole code behind/design separation feature of .NET). I would like to use a content placeholder, and insert child controls dynamically. However, I can only seem to insert them side by side, and one after another. I would like to have something that looks like this:
Table Column 1 Table Column 2
Username: [UserName]
[MessageSubject]
Posted on: [PostDate]
User Rating: [UserRating]
But the only thing I can seem to accomplish is:
Username: [UserName]Posted On: [PostDate] User Rating [UserRating][MessageSubject], without links or formatting.
How do I put paragraphs, line breaks, form buttons and regular hyperlinks into a content placeholder, and make them align the way I want them to? | You do it much the same way as you would int the .aspx page, for example:
```
Table table = new Table();
TableRow row1 = new TableRow();
table.Rows.Add(row1);
TableCell cell1 = new TableCell();
TableCell cell2 = new TableCell();
row1.Cells.Add(cell1);
row1.Cells.Add(cell2);
Label label1 = new Label();
label1.Text = "Username:";
cell1.Controls.Add(label1);
TextBox textBox1 = new TextBox();
textBox1.ID = "userNameTextBox";
cell2.Controls.Add(textBox1);
// and so on...
myPlaceholder.Controls.Add(table);
```
would be equivalent to:
```
<asp:Table runat="server">
<asp:TableRow runat="server">
<asp:TableCell runat="server">
<asp:Label runat="server" Text="Username:" />
</asp:TableCell>
<asp:TableCell runat="server">
<asp:TextBox runat="server" ID="userNameTextBox" />
</asp:TableCell>
</asp:TableRow>
</asp:Table>
```
Of course the code could be cleverer, this is just to illustrate the point. Any hierarchy of controls you can build declaratively to control you layout, you can do programatically too. | Try this overview on [Web Parts](http://msdn.microsoft.com/en-us/library/e0s9t4ck.aspx#). Or more simply, just use [User Controls](http://msdn.microsoft.com/en-us/library/y6wb1a0e.aspx) | Placeholder control, and aligning child controls | [
"",
"c#",
"asp.net",
"css",
""
] |
If this were possible to do prior to posting a form, it may save me having to upload the file to my server... | To do that you would have to load the file's binary information into JavaScript. Which is not possible.
But [here's](http://www.webtoolkit.info/javascript-sha1.html) an implementation of SHA1 in JavaScript. | Actually you **can** read the contents of a client-side file now, as long as it's chosen in a file upload field and you are using Firefox. See the [input.files](https://developer.mozilla.org/en/NsIDOMFileList) array. You can then indeed hash it, although it might be rather slow.
See [How would I get a Hash value of a users file with Javascript or Flash?](https://stackoverflow.com/questions/539488/how-would-i-get-a-hash-value-of-a-users-file-with-javascript-or-flash/539886#539886) for an example and a compact SHA-1 implementation. | Is it possible to compute a file's SHA1 ID using Javascript? | [
"",
"javascript",
"sha1",
""
] |
Let's say there is a list of `List<UInt32>`
Thus, :
```
12|12
23|33
33|22
11|22
```
I need to remove 0th and 2nd element (`List<UInt32>`). However, when I try to `foreach` this list and first remove 0th, the List collapses its elements and 1st becomes 0th now.. so I don't want to delete the wrong element, because my another `List<int>` includes the positions of elements I want to delete.
Anyway, I thought of doing some algorithm for this, but I wonder if there is already solution for this problem. | Sort the positions list in descending order and remove elements in that order.
```
foreach (var position in positions.OrderByDescending(x=>x))
list.RemoveAt(position);
``` | Are you able to tell which elements you need to remove based on the elements themselves instead of the index? If so, and you want to change the existing list instead of creating a newly filtered one, use:
```
list.RemoveAll(x => (whatever - a predicate));
```
This is more efficient than removing elements one at a time - each element is only moved once. It's also clearer, if the predicate is obvious :) | Is it possible to let List collapse after I do removeAt certain times? | [
"",
"c#",
"list",
""
] |
I am looking at the Zend Server (PE and CE) and am woundering if its just a frontend for php.ini and automatically has Zend Optimizer which basically is APC(right?) in it or if it would actually be interesting for our development machine. Basically does Zend Server have any special sauce I can't get from opensource caching software and what modules would you use to build something like this yourself. Just get Apache, PHP and APC or use lighttpd with xcache?
EDIT:
Is there an opensource alternative? | As always with that type of products, difference is support (**with SLA**) and packaging. It seems that Zend also put some nice frontends. | Zend Server has more features than APC+Apache. It's a PHP application server, that means:
- Monitoring of the PHP execution in a production environment;
- Code Tracing of a PHP event (to debug in a production environment, storing the execution stack of PHP code);
- Debug and profile system;
- Job Queue (to managing a queue of PHP scripts, to schedule the execution of PHP scripts);
- Java Bridge (to call Java classes from PHP);
- Page Cache (to cache an URL based on conditions $\_GET, $\_SESSION, $\_SERVER, etc);
- Data Cache (an API to cache PHP variables (in disk or in RAM);
- PHP accelerator (a PHP bytecode accelerator, Zend Optimizer+);
- Management of the PHP stack (configuration of PHP, extensions, etc).
The Zend Server Community Edition (CE) is the free version of Zend Server. In this version you have only:
- Debug and profile system;
- Data Cache (like APC);
- PHP bytecode accelerator, Zend Optimizer+ (like APC);
- Java Bridge;
- Management of the PHP stack.
For more info: <http://www.zend.com/en/products/server/> | Is Zend Server just APC and Apache munched together into an install? | [
"",
"php",
"open-source",
"caching",
""
] |
I seem to be getting an odd value.
How do I get the number of rows in my array:
```
double[,] lookup = { {1,2,3}, {4,5,6} };
```
The output should be 2. | lookup has two dimensions, this is how you can read them
```
double[,] lookup = { {1,2,3}, {4,5,6} };
int rows = lookup.GetLength(0); // 2
int cols = lookup.GetLength(1); // 3
int cells = lookup.Length; // 6 = 2*3
```
The concept of **rows** and **cols** is just tradition, you might just as well call the first dimension the columns.
Also see [this question](https://stackoverflow.com/questions/586972/how-to-get-multidimensional-length-of-one-axis/587017#587017) | You want the rank property on the array...
```
double[,] lookup = { { 1, 2, 3 }, { 4, 5, 6 } };
Console.WriteLine(lookup.Rank);
```
This will provide you with the number of dimensions.
Edit:
This will only provide you with the number of dimensions for the array as opposed to the number of primary elements or "rows" see @Henk Holterman's answer for a working solution. | double[,] type, how to get the # of rows? | [
"",
"c#",
"arrays",
""
] |
I need to remove elements with specific value from std::list. With the `list<int>` I used remove() method.
Now I have `list<CMyClass>` so I thought I should use remove\_if() but it's predicate takes only one paramater - the element to be tested.
How do I write a function `foo(const CMyClass &Bad)` which removes from list all the elements equal to Bad?
Thanks
PS
```
struct CMyClass {
void *Ptr;
int Var;
}
bool is_equal(const CMyClass &A, const CMyClass &B)
{
if (A.Ptr == B.Prt and A.Var == B.Var)
return true;
else
return false;
}
``` | Your class has to implement operator == in your ClassName
```
bool operator == ( const Class& rhs );
```
and then you can use
```
list.remove( Bad )
```
If it is reasonable to your class to have operator == ( not just for remove ) - than list::remove is good for you solution. If operator == only for list::remove than it is better to use remove\_if.
In the following example list::remove and list::remove\_if is demonstrated.
```
struct Class
{
int a_;
int b_;
Class( int a, int b ):
a_( a ),
b_( b )
{}
bool operator == (const Class &rhs)
{
return (rhs.a_ == a_ && rhs.b_ == b_);
}
void print()
{
std::cout << a_ << " " << b_ << std::endl;
}
};
bool isEqual( Class lhs, Class rhs )
{
return (rhs.a_ == lhs.a_ && rhs.b_ == lhs.b_);
}
struct IsEqual
{
IsEqual( const Class& value ):
value_( value )
{}
bool operator() (const Class &rhs)
{
return (rhs.a_ == value_.a_ && rhs.b_ == value_.b_);
}
Class value_;
};
int main()
{
std::list<Class> l;
l.push_back( Class( 1, 3 ) );
l.push_back( Class( 2, 5 ) );
l.push_back( Class( 3, 5 ) );
l.push_back( Class( 3, 8 ) );
Class bad( 2, 5 );
std::cout << "operator == " << std::endl;
l.remove( bad );
std::for_each( l.begin(), l.end(), std::mem_fun_ref( &Class::print ) );
std::cout << "binary function predicat" << std::endl;
l.push_back( Class( 2, 5 ) );
l.remove_if( std::bind2nd( std::ptr_fun(isEqual), bad ) );
std::for_each( l.begin(), l.end(), std::mem_fun_ref( &Class::print ) );
std::cout << "functor predicat" << std::endl;
l.push_back( Class( 2, 5 ) );
l.remove_if( IsEqual( bad ) );
std::for_each( l.begin(), l.end(), std::mem_fun_ref( &Class::print ) );
return 0;
}
``` | To remove all elements according to a Predicate:
```
struct Pred
{
bool operator()(int i) const
{
return i == 42;
}
};
std::list<int> l = ...;
l.remove_if(Pred());
```
or to remove all elements with the value 42:
```
std::list<int> l = ...;
l.remove(42);
```
or for a list of CMyClass:
```
struct Pred
{
bool operator()(const CMyClass& item) const
{
return item.GetSomething() == 42 && item.GetSomethingElse() == 314159;
}
};
std::list<CMyClass> l = ...;
l.remove_if(Pred());
``` | remove elements with specific value from std::list | [
"",
"c++",
"list",
"stl",
""
] |
I have a generic dictionary in a multithreaded application; to implement a lock i created a property.
```
static object myLock=new object();
Dictionary<key,SomeRef> dict=new Dictionary<key,SomeRef>();
public Dictionary<key,SomeRef> MyDict{
get{
lock(myLock){
return dict;
}
}
}
```
Now if i write CODE#1
```
MyDict.TryGetValue
```
or CODE#2
```
var result=MyDict.Values;
foreach(var item in result){
//read value into some other variable
}
```
so while i m runnig code 1 or 2 and at the same time if some other thread tries to do some write operation on the dictionary like ..clear dict or add new item. then, will this solution be thread safe (using a property).
if not ..then is there any other ways to do this.
When i say write operation it can be take a reference of the dict through property chek key exoist or not if not create key and assign value. (thus me not using the setter in the property) | No, this will not be threadsafe.
The lock will only lock around getting the reference to your internal (dict) instance of the dictionary. It will not lock when the user tries to add to the dictionary, or read from the dictionary.
If you need to provide threadsafe access, I would recommend keeping the dictionary private, and make your own methods for getting/setting/adding values to/from the dictionary. This way, you can put the locks in place to protect at the granularity you need.
---
This will look something like this:
```
public bool TryGetValue(key thekey, out SomeRef result)
{
lock(myLock) { return this.dict.TryGetValue(thekey, out result); }
}
public void Add(key thekey, SomeRef value)
{
lock(myLock) { this.dict.Add(thekey, value) }
}
// etc for each method you need to implement...
```
The idea here is that your clients use your class directly, and your class handles the synchronization. If you expect them to iterate over the values (such as your foreach statement), you can decide whether to copy the values into a List and return that, or provide an enumerator directly (`IEnumerator<SomeRef> GetValues()`), etc. | No, this will not be safe, as the only code that's `locked` is the retrieval code. What you need to do is
```
lock(MyDict)
{
if(MyDict.TryGetValue()...
}
```
and
```
lock(MyDict)
{
foreach(var item in MyDict.Values) ...
}
```
The basic idea is to enclose your working code within the lock() block. | Threading:Lock on generic dictionary | [
"",
"c#",
"multithreading",
""
] |
If get a gring from the registry and it correctly displays when I place it in a message box.
::MessageBoxW(0, (LPCWSTR)achValue, \_T("Found"), MB\_YESNO);
The value is stored in archValue which is a DWORD. What I want to do is compare it to the following string "2.0.7045.0" but strcmp fails to work for me.
Any ideas on how to do this wiould be greatly appreciated.
Pretty rubbish at c++ and I cant debug easily as its in a dll.
Much appreciated
Tony | You need to use the wide char version of strcmp: [wcscmp](http://msdn.microsoft.com/en-us/library/e0z9k731(VS.80).aspx). | The question is confusing; you have problem getting the data from the registry or doing a strcmp ?
You get a DWORD (???) out of the registry that should be something like "2.0.7045.0" ? aren't you certain it's not a string (REG\_SZ) ?
If you can get the string out of the registry, you should be able to do a string compare; remember that strcmp (or other similar functions/methods) return 0 (zero) if the strings are equals. | String Compare not working in Visual C++ 2005 | [
"",
"c++",
"visual-studio",
"visual-c++",
"visual-c++-2005",
"strcmp",
""
] |
What's the best way in C++ to copy a pair from a map to vector? I'm doing this so I can subsequently sort the vector. | This should do what you want:
```
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>
#include <iterator>
using namespace std;
bool cmp(const pair<int, int> &p1, const pair<int, int> &p2)
{
return p1.second < p2.second;
}
int main()
{
map<int, int> m;
for(int i = 0; i < 10; ++i)
m[i] = i * -i;
vector<pair<int, int> > v;
copy(m.begin(), m.end(), back_inserter(v));
sort(v.begin(), v.end(), cmp);
for(int i = 0; i < v.size(); ++i)
cout << v[i].first << " : " << v[i].second << endl;
return 0;
}
``` | ```
vector<pair<K,V> > v(m.begin(), m.end());
```
or
```
vector<pair<K,V> > v(m.size());
copy(m.begin(), m.end(), v.begin());
```
`copy()` is in `<algorithm>`. | C++ how to copy a map to a vector | [
"",
"c++",
"collections",
"vector",
"dictionary",
""
] |
I have simple user registration form. In which i am puting city as a tag. Here drop down box value coming from city master table from mysql database.
But when i storing whole user registration values, i m not be able to fetch currently selected city value. Can anyone help me...? My user registration form contains :
```
<s:form action="UserAction" >
<s:textfield name="name" label="User Name" />
<s:textfield name="age" label="Age" />
<s:radio name="sex" label="Sex" list="{'M','F'}" />
<s:select list="cities" key="cities.name" listValue="name">
</s:select>
<s:submit />
</s:form>
``` | Finally got the solution after writing following code :
```
<s:select list="cities" name="city">
<s:iterator value="cities">
</s:iterator>
</s:select>
```
And at the time of insertion through DAO, it will automatically fetching all the value from bean. | Give your list the exact name what you have in your bean, in your case **city**. It should start working now. | struts2 <s:select...> tag | [
"",
"java",
"struts2",
""
] |
Ignoring the special libraries that allow you to work with very big numbers, what's the largest int value you can store in PHP? | From the [PHP manual](http://php.net/manual/en/language.types.integer.php):
> The size of an integer is
> platform-dependent, although a maximum
> value of about two billion is the
> usual value (that's 32 bits signed).
> PHP does not support unsigned
> integers. Integer size can be
> determined using the constant
> PHP\_INT\_SIZE, and maximum value using
> the constant PHP\_INT\_MAX since PHP
> 4.4.0 and PHP 5.0.5.
>
> 64-bit platforms usually have a maximum value of about 9E18, except on Windows prior to PHP 7, where it was always 32 bit. | **32-bit builds of PHP:**
* Integers can be from **-2,147,483,648** to **2,147,483,647** (~ ± 2 billion)
**64-bit builds of PHP:**
* Integers can be from **-9,223,372,036,854,775,808** to **9,223,372,036,854,775,807** (~ ± 9 quintillion)
Numbers are inclusive.
*Note: some 64-bit builds once used 32-bit integers, particularly older Windows builds of PHP*
Values outside of these ranges are represented by floating point values, as are non-integer values within these ranges. The interpreter will automatically determine when this switch to floating point needs to happen based on whether the result value of a calculation can't be represented as an integer.
PHP has no support for "unsigned" integers as such, limiting the maximum value of all integers to the range of a "signed" integer. | What's the maximum value for an int in PHP? | [
"",
"php",
"integer",
""
] |
Here is the exact error I got.
[](https://i.stack.imgur.com/Gr2xa.png)
(source: [clip2net.com](http://clip2net.com/clip/m12122/1237235885-clip-36kb.png))
The favicon.ico has been added in the project as a resource and I have set to "Resource" the Build Action.
[](https://i.stack.imgur.com/CPbLS.png)
(source: [clip2net.com](http://clip2net.com/clip/m12122/1237236030-clip-6kb.png))
I found some solution that require to add some code. My question is why I can't do it with the Visual Studio Interface? | I had a similar problem with close.bmp. I renamed it to close-image.bmp, and it fixed it. But right now, I tryed to rename it into close.bmp again, and today it works. Seems to be a problem with solution... Read this discussion:
<http://social.msdn.microsoft.com/Forums/en-US/vswpfdesigner/thread/b03061e5-5500-442f-9c88-a6d82f97c2b7>
Also, your settings are right. You need to include it and make 'Build Action: Resource' | I just tried in Visual Studio 2008 SP 1 and it worked. I dragged the file into the project, and I was simply able to type "favicon.ico" in the property pane.
Are you sure it's at the root level of your application? If you have it in a subfolder in the project it will require the full relative path (like "icons\favicon.ico"). | WPF adding Icon to windows cause Property Error | [
"",
"c#",
".net",
"wpf",
""
] |
I have a page that consists of two frames: one being a flash app, and one being an aspx page with a user control that contains a grid with several "add to cart" buttons. When the user clicks a button I would like to reload the whole window with a shopping cart page.
I found out how to do so [here](http://weblogs.asp.net/ksamaschke/archive/2003/02/23/2831.aspx) quite nicely by avoiding response.redirect, and using response.write to insert some javascript that redirects. The problem is that when the user hits the back button from the shopping cart page, the script executes again, effectively canceling out the back button. (bad usability)
So my question is, is there a way to detect if the user arrived at the page via the back button and avoid executing the script? | Change your javascript to replace the current URL instead of just setting it
```
// Creates browser history
top.location = 'http://www.stackoverflow.com'
// Doesn't create browser history
top.location.replace( 'http://www.stackoverflow.com' );
``` | > When the user clicks a button I would like to reload the whole window with a shopping cart page.
You should be using the [Post-Redirect-Get](http://en.wikipedia.org/wiki/Post/Redirect/Get) model. | Remove/Disable javascript when using browser's back button | [
"",
"javascript",
""
] |
I'm using a library that generates a bunch of classes for me.
These classes all inherit from a common base class but that base class doesn't define a couple methods that are common to all subclasses.
For example:
```
SubClassA : BaseClass{
void Add(ItemA item) {...}
ItemA CreateNewItem() {...}
}
SubClassB: BaseClass{
void Add(ItemB item) {...}
ItemB CreateNewItem() {...}
}
```
Unfortunately, the base class **doesn't have these methods**. This would be great:
```
BaseClass{
// these aren't actually here, I'm just showing what's missing:
abstract void Add(ItemBaseClass item); // not present!
abstract ItemBaseClass CreateNewItem(); // not present!
}
```
Since there is a common base class for my A+B objects and a common base class for the Item objects, I had hoped to benefit from the wonderful world of polymorphism.
Unfortunately, since the common methods aren't actually present in the base class, I can't call them virtually. e.g., this would be perfect:
```
BaseClass Obj;
Obj = GetWorkUnit(); // could be SubClassA or SubClassB
ItemBaseClass Item = Obj.CreateNewItem(); // Compile Fail: CreateNewItem() isn't in the base class
Item.DoSomething();
Obj.Add(Item); // Compile Fail: Add(...) isn't in the base class
```
Obviously casting would work but then I'd need to know which type I had which would negate the benefits.
How can I "force" a call to these methods? I'm not worried about getting an object that doesn't implement the method I'm trying to call. I can actually do what I want in VB--I don't get intellisense but the compiler's happy and it works:
```
CType(Obj, Object).Add(Item) // Note: I'm using C#--NOT VB
```
Againt, I have no control over these classes (which I think rules out partial classes). | You cannot call a non-virtual method of a derived class without resorting to reflection or other dirty tricks. If you want to do it, it's easy then:
```
// obj is your object reference.
obj.GetType().InvokeMember("MethodName",
System.Reflection.BindingFlags.InvokeMethod, null, obj, null /* args */)
``` | I might be missing something, but why not make and inherit from an interface with those methods?
If you are in control of the creation process for the instances, you might get what you want by inheriting from the classes which you didn't write and add then interface (no code needs to be written, the compiler will map the interface to the existing non-virtual methods). | How do I call a subclass method on a baseclass object? | [
"",
"c#",
"inheritance",
"c#-2.0",
"polymorphism",
""
] |
I was looking through some pages when I stumbled across [this open source JavaScript date library: Datejs](http://code.google.com/p/datejs/). Now I've been trying to use it but everytime I try any function like:
```
$(function() { Date.today().toLongDateString() } );
```
or even only
```
Date.today().toLongDateString()
```
withing tags, I get errors when the webpage loads, it tells me Date.today() is not a function but it appears as such in the [documentation](http://code.google.com/p/datejs/wiki/APIDocumentation) I've been at this for like almost 2 hours now xD it's driving me crazy and I know I just probably overlooked something...
I loaded the:
```
<script type="text/javascript" src="assets/js/dia_hora/date_es-MX.js"></script>
``` | Sounds like the script is not getting loaded. Put an alert('hello'); at the beginning of the script and see if you get that popup when the page loads. | Are your script path and filename correct? You wrote:
```
<script type="text/javascript" src="assets/js/dia_hora/date_es-MX.js"></script>
```
But according to the ["Getting Started" page of the project](http://www.datejs.com/2007/11/27/getting-started-with-datejs/), it should be:
```
<script type="text/javascript" src="assets/js/dia_hora/date-es-MX.js"></script>
```
There are two hyphens in the original file: "date-es-MX.js", not an underscore. Or did you rename the file?
Check if the file correctly loads using [Firefox Firebug (network tab)](http://getfirebug.com/net.html) or [FiddlerTool](http://www.fiddler2.com/fiddler2/) if you're using Internet Explorer. | Javascript Datejs | [
"",
"javascript",
"jquery",
"datetime",
""
] |
There are some posts that asks what the difference between those two are already.
(why do I have to even mention this...)
But my question is different in a way that I am calling "throw ex" in another error *god-like* handling method.
```
public class Program {
public static void Main(string[] args) {
try {
// something
} catch (Exception ex) {
HandleException(ex);
}
}
private static void HandleException(Exception ex) {
if (ex is ThreadAbortException) {
// ignore then,
return;
}
if (ex is ArgumentOutOfRangeException) {
// Log then,
throw ex;
}
if (ex is InvalidOperationException) {
// Show message then,
throw ex;
}
// and so on.
}
}
```
If `try & catch` were used in the `Main`, then I would use `throw;` to rethrow the error.
But in the above simplied code, all exceptions go through `HandleException`
Does `throw ex;` has the same effect as calling `throw` when called inside `HandleException`? | Yes, there is a difference.
* `throw ex` resets the stack trace (so your errors would appear to originate from `HandleException`)
* `throw` doesn't - the original offender would be preserved.
```
static void Main(string[] args)
{
try
{
Method2();
}
catch (Exception ex)
{
Console.Write(ex.StackTrace.ToString());
Console.ReadKey();
}
}
private static void Method2()
{
try
{
Method1();
}
catch (Exception ex)
{
//throw ex resets the stack trace Coming from Method 1 and propogates it to the caller(Main)
throw ex;
}
}
private static void Method1()
{
try
{
throw new Exception("Inside Method1");
}
catch (Exception)
{
throw;
}
}
``` | (I posted earlier, and @Marc Gravell has corrected me)
Here's a demonstration of the difference:
```
static void Main(string[] args) {
try {
ThrowException1(); // line 19
} catch (Exception x) {
Console.WriteLine("Exception 1:");
Console.WriteLine(x.StackTrace);
}
try {
ThrowException2(); // line 25
} catch (Exception x) {
Console.WriteLine("Exception 2:");
Console.WriteLine(x.StackTrace);
}
}
private static void ThrowException1() {
try {
DivByZero(); // line 34
} catch {
throw; // line 36
}
}
private static void ThrowException2() {
try {
DivByZero(); // line 41
} catch (Exception ex) {
throw ex; // line 43
}
}
private static void DivByZero() {
int x = 0;
int y = 1 / x; // line 49
}
```
and here is the output:
```
Exception 1:
at UnitTester.Program.DivByZero() in <snip>\Dev\UnitTester\Program.cs:line 49
at UnitTester.Program.ThrowException1() in <snip>\Dev\UnitTester\Program.cs:line 36
at UnitTester.Program.TestExceptions() in <snip>\Dev\UnitTester\Program.cs:line 19
Exception 2:
at UnitTester.Program.ThrowException2() in <snip>\Dev\UnitTester\Program.cs:line 43
at UnitTester.Program.TestExceptions() in <snip>\Dev\UnitTester\Program.cs:line 25
```
You can see that in Exception 1, the stack trace goes back to the `DivByZero()` method, whereas in Exception 2 it does not.
Take note, though, that the line number shown in `ThrowException1()` and `ThrowException2()` is the line number of the `throw` statement, **not** the line number of the call to `DivByZero()`, which probably makes sense now that I think about it a bit...
### Output in Release mode
Exception 1:
```
at ConsoleAppBasics.Program.ThrowException1()
at ConsoleAppBasics.Program.Main(String[] args)
```
Exception 2:
```
at ConsoleAppBasics.Program.ThrowException2()
at ConsoleAppBasics.Program.Main(String[] args)
```
Is it maintains the original stackTrace in debug mode only? | Is there a difference between "throw" and "throw ex"? | [
"",
"c#",
".net",
"exception",
""
] |
I just upgraded to Resharper 4.5 and now see that all my BDDish test methods are marked as not conforming to the naming standard. My naming convention is like this:
```
public void Something_ShouldHaveThisResult()
```
Resharper doesn't like the underscore in the method. Is there a way to turn this off, just for test methods? I have a normal naming convention for the rest of my code. | On the menu:
Resharper | Options -> Languages -> Common -> Naming Style: remove what ever naming style you want. They should have a "disable" feature, but they don't. | [How to change the ReSharper naming style for test methods](http://atombrenner.blogspot.com/2010/07/how-to-change-resharper-naming-style.html) | How to use bdd naming style with Resharper 4.5? | [
"",
"c#",
"resharper",
"bdd",
""
] |
do you guys know how can i determine from what file was a function called inside of that function?
I was thinking of using debug\_backtrace .. but that does not look as an elegant way to do it, and they also enumarate other reasons in another question [here](https://stackoverflow.com/questions/346703/php-debugbacktrace-in-production-code)
So what other alternatives are there ?
thanks a lot | From within the function `debug_backtrace()` is the only way to determine the caller, unless of course you pass that information as parameter.
Note, that you **cannot** use default values to do this. E.g.:
```
function f($param1, $param2, $caller=__FUNCTION__) ...
```
`__FUNCTION__` will be evaluated at parse time, so it'll always have the same value. The function in which scope `f` is declared. | I borrowed this code some time ago from somewhere and it works like a charm using [debug\_backtrace()](https://www.php.net/manual/en/function.debug-backtrace.php). Hope you find it useful:
```
function backtrace(){
$backtrace = debug_backtrace();
$output = '';
foreach ($backtrace as $bt) {
$args = '';
foreach ($bt['args'] as $a) {
if (!empty($args)) {
$args .= ', ';
}
switch (gettype($a)) {
case 'integer':
case 'double':
$args .= $a;
break;
case 'string':
//$a = htmlspecialchars(substr(, 0, 64)).((strlen($a) > 64) ? '...' : '');
$args .= "\"$a\"";
break;
case 'array':
$args .= 'Array('.count($a).')';
break;
case 'object':
$args .= 'Object('.get_class($a).')';
break;
case 'resource':
$args .= 'Resource('.strstr($a, '#').')';
break;
case 'boolean':
$args .= $a ? 'TRUE' : 'FALSE';
break;
case 'NULL':
$args .= 'Null';
break;
default:
$args .= 'Unknown';
}
}
$output .= '<br />';
$output .= '<b>file:</b> '.@$bt['file'].' - line '.@$bt['line'].'<br />';
$output .= '<b>call:</b> '.@$bt['class'].@$bt['type'].@$bt['function'].'('.$args.')<br />';
}
return $output;
}
``` | Determine where a function has been called with PHP | [
"",
"php",
""
] |
I'd like to call a JavaScript function from an embedded `.swf` file. Specifically, I'd like to call a function in one of my externally linked JavaScript files from within:
```
function loadTrack(){
//Radio Mode feature by nosferathoo, more info in: https://sourceforge.net/tracker/index.php?func=detail&aid=1341940&group_id=128363&atid=711474
if (radio_mode && track_index == playlist_size - 1) {
playlist_url=playlist_array[track_index].location;
for (i=0;i<playlist_mc.track_count;++i) {
removeMovieClip(playlist_mc.tracks_mc["track_"+i+"_mc"]);
}
playlist_mc.track_count=0;
playlist_size=0;
track_index=0;
autoload=true;
autoplay=true;
loadPlaylist();
return(0);
}
start_btn_mc.start_btn._visible = false;
track_display_mc.display_txt.text = playlist_array[track_index].label;
if (track_display_mc.display_txt._width > track_display_mc.mask_mc._width) {
track_display_mc.onEnterFrame = scrollTitle;
}else{
track_display_mc.onEnterFrame = null;
track_display_mc.display_txt._x = 0;
}
mysound.loadSound(playlist_array[track_index].location,true);
play_mc.gotoAndStop(2)
//info button
if(playlist_array[track_index].info!=undefined){
info_mc._visible = true;
info_mc.info_btn.onPress = function(){
getURL(playlist_array[track_index].info,"_blank")
}
info_mc.info_btn.onRollOver = function(){
track_display_mc.display_txt.text = info_button_text;
}
info_mc.info_btn.onRollOut = function(){
track_display_mc.display_txt.text = playlist_array[track_index].label;
}
}else{
info_mc._visible = false;
}
resizeUI();
_root.onEnterFrame=function(){
//HACK doesnt need to set the volume at every enterframe
mysound.setVolume(this.volume_level)
var load_percent = (mysound.getBytesLoaded()/mysound.getBytesTotal())*100
track_display_mc.loader_mc.load_bar_mc._xscale = load_percent;
if(mysound.getBytesLoaded()==mysound.getBytesTotal()){
//_root.onEnterFrame = null;
}
}
}
```
which is in an .as file which I assume somehow becomes the swf file. How would I go about this and `re-compile` the `.as` file? | Let's compile those answers together for AS2 and AS3 using JS injection AND the ExternalInterface (both ways work in BOTH languages)
AS2:
```
// to use javascript injection in a url request
getURL("javascript:displayPost(" + postId + "," + feedId +");", "_self");
// to use the external interface
import flash.external.ExternalInterface;
ExternalInterface.call("displayPost",postId,feedId);
```
AS3:
```
// to use javascript injection in a url request
navigateToURL(new URLRequest("javascript:displayPost(" + postId + "," + feedId +");"), "_self");
// to use the external interface
import flash.external.ExternalInterface;
ExternalInterface.call("displayPost",postId,feedId);
```
Notice that in AS2 and AS3 the ExternalInterface method is the exact same (ExternalInterface was introduced in Flash 8 for AS2). And in AS2 and AS3 the javascript injection method are the same except that it's navigateToURL instead of getURL, and the url string is wrapped in new URLRequest(), because it needs a URLRequest object. Also when using javascript injection, it's a good practice to set the target window to "\_self" to avoid a new tab or window from opening. | Also incase anyone in the future is looking at this question the Actionscript 3 version of altCognito's answer is like this:
```
ExternalInterface.call("displayPost",postId,feedId);
``` | ActionScript + JavaScript | [
"",
"javascript",
"actionscript",
"flash",
""
] |
I'm working on a project that has to read and manipulate QuickTimes on Windows. Unfortunately, all the tutorials and sample code at the Apple site seem to be pretty much Mac specific. Is there a good resource on the web that deals specifically with programming QuickTime for Windows? Yes, I know that I can bludgeon my way (eventually) through the Mac stuff and eventually get something to work, but I would really like to see a treatment of the cleanest and best way to deal with it on Windows and what gotcha's to beware.
For extra points, it would be cool to see how someone might use the QuickTime API from a dynamic language like REBOL or Python (no, the Mac Python QuickTime bindings don't count!).
Thanks! | [QuickTime For Windows](http://developer.apple.com/documentation/QuickTime/Rm/QTforWindows/QTforWindows/B-Chapter/2QuickTimeForWindows.html) starts off with the differences between Mac OS and Windows programming and [Building QuickTime Capability Into a Windows Application](http://developer.apple.com/documentation/QuickTime/Rm/QTforWindows/QTforWindows/C-Chapter/3BuildingQuickTimeCa.html) then discusses how to incorporate the capability into Windows platform | There is an official mailing list for [QT developers](http://lists.apple.com/mailman/listinfo/quicktime-api). It has an archive. It would certainly be worth subscribing to it if you are seriously trying to *use* QT for something, especially if it is the slightest bit off the beaten path.
IMHO, the official docs are more than a little too Apple-centric. Note that the Windows book assumes you already have experience with QT on Macs. At the time I was looking (about a year ago), I had a mandate to deal with QT from .NET, either from C# or managed C++. That was not a well documented way of doing things then.
There is a body of sample code for Windows somewhere at the Apple developer site, which might help if you can find it. I seem to have lost the links I had at one time. Just knowing it does (or did a year ago) exist might be enough to nudge you in the right direction.
Almost all of the sample code available is ordinary C or C++. | What is a good tutorial on the QuickTime API for MS Windows? | [
"",
"python",
"windows",
"quicktime",
"rebol",
""
] |
OK I have a table like this:
```
ID Signal Station OwnerID
111 -120 Home 1
111 -130 Car 1
111 -135 Work 2
222 -98 Home 2
222 -95 Work 1
222 -103 Work 2
```
This is all for the same day. I just need the Query to return the max signal for each ID:
```
ID Signal Station OwnerID
111 -120 Home 1
222 -95 Work 1
```
I tried using MAX() and the aggregation messes up with the Station and OwnerID being different for each record. Do I need to do a JOIN? | Something like this? Join your table with itself, and exclude the rows for which a higher signal was found.
```
select cur.id, cur.signal, cur.station, cur.ownerid
from yourtable cur
where not exists (
select *
from yourtable high
where high.id = cur.id
and high.signal > cur.signal
)
```
This would list one row for each highest signal, so there might be multiple rows per id. | You are doing a group-wise maximum/minimum operation. This is a common trap: it feels like something that should be easy to do, but in SQL it aggravatingly isn't.
There are a number of approaches (both standard ANSI and vendor-specific) to this problem, most of which are sub-optimal in many situations. Some will give you multiple rows when more than one row shares the same maximum/minimum value; some won't. Some work well on tables with a small number of groups; others are more efficient for a larger number of groups with smaller rows per group.
[Here's a discussion](http://kristiannielsen.livejournal.com/6745.html) of some of the common ones (MySQL-biased but generally applicable). Personally, if I know there are no multiple maxima (or don't care about getting them) I often tend towards the null-left-self-join method, which I'll post as no-one else has yet:
```
SELECT reading.ID, reading.Signal, reading.Station, reading.OwnerID
FROM readings AS reading
LEFT JOIN readings AS highersignal
ON highersignal.ID=reading.ID AND highersignal.Signal>reading.Signal
WHERE highersignal.ID IS NULL;
``` | Simple Query to Grab Max Value for each ID | [
"",
"sql",
"sql-server",
"max",
"greatest-n-per-group",
""
] |
I have a program that uses threads in C#. Is there a way to know programmatically the memory usage of the application? I want to limit the spawning of threads to say 10 megabytes of memory, how would I do that? | If you want the memory of the entire running process and not on a per thread basis, how about:
```
// get the current process
Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
// get the physical mem usage
long totalBytesOfMemoryUsed = currentProcess.WorkingSet64;
```
There's a whole host of other process memory properties besides `WorkingSet64` check out the "memory related" ones at the following link for the one that best suit
<http://msdn.microsoft.com/en-us/library/system.diagnostics.process_properties.aspx> | While I agree with the comments you've already received on your question, the use of `System.Environment.WorkingSet` might perhaps be an actual answer to it if you really decide to take this course of action? | Memory usage in C# | [
"",
"c#",
".net",
"multithreading",
"memory",
""
] |
I've got a chunk of C# code that is supposed to set VerticalScroll.Value within a class that inherits from UserControl. It gets called when any child object of the class changes sizes. The class has its AutoScroll property set to true.
```
public void ScrollTo(int top)
{
if (top >= this.VerticalScroll.Minimum && top <= this.VerticalScroll.Maximum)
{
this.VerticalScroll.Value = top;
}
}
```
The problem is, when tracing through the code, sometimes this.VerticalScroll.Value gets set, sometimes it keeps the value that it had before this method was called.
Is this a bug in VS, or are there known conditions under which the value will ignore attempts to set it?
Thanks,
Rob | I was having the same problem and came upon the solution in some dev forum. After setting the VerticalScroll.Value, you have to call PerformLayout() to make the scrolling control update. So do this:
```
scrollingcontrol.VerticalScroll.Value = top;
scrollingcontrol.PerformLayout();
```
This makes more sense than setting .Value twice, though it seems to have the same effect. | I was running into the same problem, and I found a solution on the MSDN webpage (won't let me post links, 'cause I'm a new user).
The suggested solution was to assign to .Value twice, and it worked for me:
```
int newVerticalScrollValue =
pDashboard.VerticalScroll.Value - pDashboard.VerticalScroll.SmallChange;
pDashboard.VerticalScroll.Value = newVerticalScrollValue;
pDashboard.VerticalScroll.Value = newVerticalScrollValue;
``` | C# UserControl.VerticalScroll.Value not being set | [
"",
"c#",
"winforms",
"controls",
""
] |
I'm trying to create a simple web project using Tomcat in Java.
In the web.xml file, I point to a servlet that I want to be run when someone goes to `http://localhost:8080/MyProject` , so I used `/` as the URL pattern. That worked, however it has the disadvantage that all links to html and javascript files are being passed on to the main servlet instead of the appropriate file itself. Changing the Url pattern from `/` to `/Home` or `/Main` fixes it.
What am I doing wrong? | you can setup a forward in the index.jsp at the root, and have it redirect to your servlet.
e.g., in your web.xml, you'd define your servlet mapping to some known path, such as "/home".
and in the your index.jsp at the root of your web-inf, you can write
```
<jsp:forward page="/home" />
```
check this for more info if you decide to take this route <http://java.sun.com/products/jsp/tags/syntaxref.fm9.html> | Why not use [`<welcome-file>`](http://edocs.bea.com/wls/docs61/webapp/web_xml.html#1026980) attribute of web.xml. | How to set a Servlet to run as the Homepage in Java? | [
"",
"java",
"tomcat",
"servlets",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.