Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
How can I see the assembly code for a C++ program? What are the popular tools to do this?
## Ask the compiler If you are building the program yourself, you can ask your compiler to emit assembly source. For most UNIX compilers use the `-S` switch. * If you are using the GNU assembler, compiling with `-g -Wa,-alh` will give intermixed source and assembly on stdout (`-Wa` asks compiler driver to pass options to assembler, `-al` turns on assembly listing, and `-ah` adds "high-level source" listing): `g++ -g -c -Wa,-alh foo.cc` * For Visual Studio, use [`/FAsc`](http://msdn.microsoft.com/en-us/library/367y26c6.aspx). ## Peek into a binary If you have a compiled binary, * use `objdump -d a.out` on UNIX (also works for cygwin), * [`dumpbin /DISASM foo.exe`](http://msdn.microsoft.com/en-us/library/756as972.aspx) on Windows. ## Use your debugger Debuggers could also show disassembly. * Use `disas` command in GDB. Use `set disassembly-flavor intel` if you prefer Intel syntax. * or the [disassembly window](http://msdn.microsoft.com/en-us/library/a3cwf295.aspx) of Visual Studio on Windows.
In GCC/G++, compile with `-S`. That will output a `something.s` file with the assembly code. Edit: If you want the output to be in Intel syntax (which is IMO, much more readable, and most assembly tutorials use it), compile with `-masm=intel`.
How can I see the assembly code for a C++ program?
[ "", "c++", "assembly", "disassembly", "" ]
I am trying to debug an issue involving a ClassCastException in Java. In the interest of solving the issue I need to know what is going on when I cast from Object to a specific type. **Can anyone explain to me how the Java cast operator works at the Java level and the JVM level?**
Is the [JLS](http://docs.oracle.com/javase/specs/jls/se5.0/html/conversions.html#5.5) good enough? > Casting conversion is applied to the operand of a cast operator (§15.16): the type of the operand expression must be converted to the type explicitly named by the cast operator. Casting contexts allow the use of: > > * an identity conversion (§5.1.1) > * a widening primitive conversion (§5.1.2) > * a narrowing primitive conversion (§5.1.3) > * a widening reference conversion (§5.1.5) optionally followed by an unchecked conversion (§5.1.9) > * a narrowing reference conversion (§5.1.6) optionally followed by an unchecked conversion > * a boxing conversion (§5.1.7) > * an unboxing conversion (§5.1.8). Actually, maybe [this part](http://docs.oracle.com/javase/specs/jls/se5.0/html/conversions.html#192526) is more relevant: > The detailed rules for compile-time legality of a casting conversion of a value of compile-time reference type *S* to a compile-time reference type *T* are as follows: > > * If > *S* is a class type: > + If *T* is > a class type, then either |*S*| > <: |*T*|, or |*T*| <: > |*S*|; otherwise a compile-time > error occurs. Furthermore, if there > exists a supertype *X* of > *T*, and a supertype *Y* of > *S*, such that both *X* and > *Y* are provably distinct > parameterized types (§4.5), > and that the erasures of *X* and > *Y* are the same, a compile-time > error occurs.+ If *T* is an interface type: > > * If > *S* is not a `final` > class (§8.1.1), > then, if there exists a supertype > *X* of *T*, and a supertype > *Y* of *S*, such that both > *X* and *Y* are provably > distinct parameterized types, and that > the erasures of *X* and *Y* > are the same, a compile-time error > occurs. Otherwise, the cast is always > legal at compile time (because even if > *S* does not implement *T*, > a subclass of *S* might).* If *S* is a > `final` class (§8.1.1), > then *S* must implement *T*, > or a compile-time error occurs. > > - If *T* > is a type variable, then this > algorithm is applied recursively, > using the upper bound of *T* in > place of *T*.- If *T* is > an array type, then *S* must be > the class `Object`, or a > compile-time error occurs. - If *S* is > an interface type: > * If *T* is > an array type, then *T* must > implement *S*, or a compile-time > error occurs.* If *T* is a type that is not > `final` (§8.1.1), > then if there exists a supertype > *X* of *T*, and a supertype > *Y* of *S*, such that both > *X* and *Y* are provably > distinct parameterized types, and that > the erasures of *X* and *Y* > are the same, a compile-time error > occurs. Otherwise, the cast is always > legal at compile time (because even if > *T* does not implement *S*, > a subclass of *T* might).* If *T* is > a type that is `final`, > then: > + If *S* is not a parameterized > type or a raw type, then *T* must > implement *S*, and the cast is > statically known to be correct, or a > compile-time error occurs.+ Otherwise, > *S* is either a parameterized > type that is an invocation of some > generic type declaration *G*, or > a raw type corresponding to a generic > type declaration *G*. Then there > must exist a supertype *X* of > *T*, such that *X* is an > invocation of *G*, or a > compile-time error occurs. > Furthermore, if *S* and *X* > are provably distinct parameterized > types then a compile-time error > occurs.- If *S* is > a type variable, then this algorithm > is applied recursively, using the > upper bound of *S* in place of > *S*.- If > *S* is an array type *SC*[], > that is, an array of components of > type *SC*: > * If *T* is a > class type, then if *T* is not > `Object`, then a > compile-time error occurs (because > `Object` is the only class > type to which arrays can be assigned).* If *T* > is an interface type, then a > compile-time error occurs unless > *T* is the type > `java.io.Serializable` or > the type `Cloneable`, the > only interfaces implemented by arrays.* If *T* > is a type variable, then: > + If the upper > bound of *T* is > `Object` or the type > `java.io.Serializable` or > the type `Cloneable`, or a > type variable that *S* could > legally be cast to by recursively > applying these rules, then the cast is > legal (though unchecked).+ If the upper > bound of *T* is an array type > *TC[]*, then a compile-time error > occurs unless the type *SC[]* can > be cast to *TC[]* by a recursive > application of these compile-time > rules for casting.+ Otherwise, a > compile-time error occurs.* If *T* is > an array type *TC*[], that is, an > array of components of type *TC*, > then a compile-time error occurs > unless one of the following is true: > > - *TC* and *SC* are the > same primitive type.- *TC* and > *SC* are reference types and type > *SC* can be cast to *TC* by > a recursive application of these > compile-time rules for casting. Perfectly clear now, isn't it? :D In other words, this is the best I can do without knowing more details about your problem.
A likely cause of class cast mystifcation is that not only do the types have to match but also they must be loaded by the same classloader. You should be able to dump not only the type hierarchy but also the identity of the classloader for each class. These kind of problems are not uncommon in appserver-style environments where application code and infratructure code are deliberately isolated - for example if system classes are accidentally included in applciation JARs you can have two copies of the "same" class inthe JVM and life gets confusing
How does the Java cast operator work?
[ "", "java", "casting", "jvm", "" ]
I want to allow uploads of very large files into our PHP application (hundred of megs - 8 gigs). There are a couple of problems with this however. Browser: * HTML uploads have crappy feedback, we need to either poll for progress (which is a bit silly) or show no feedback at all * Flash uploader puts entire file into memory before starting the upload Server: * PHP forces us to set post\_max\_size, which could result in an easily exploitable DOS attack. I'd like to not set this setting globally. * The server also requires some other variables to be there in the POST vars, such as an secret key. We'd like to be able to refuse the request right away, instead of after the entire file is uploaded. Requirements: * HTTP is a must. * I'm flexible with client-side technology, as long as it works in a browser. * PHP is not a requirement, if there's some other technology that will work well on a linux environment, that's perfectly cool.
How about a Java applet? That's how we had to do it at a company I previously worked for. I know applets suck, especially in this day and age with all our options available, but they really are the most versatile solution to desktop-like problems encountered in web development. Just something to consider.
upload\_max\_filesize can be set [on a per-directory basis](https://www.php.net/manual/en/ini.core.php#ini.sect.file-uploads); the same goes for post\_max\_size e.g.: ``` <Directory /uploadpath/> php_value upload_max_filesize 10G php_value post_max_size 10G </IfModule> ```
Very large uploads with PHP
[ "", "php", "upload", "large-files", "" ]
What is the best way to create multi-language database? To create localized table for every table is making design and querying complex, in other case to add column for each language is simple but not dynamic, please help me to understand what is the best choose for enterprise applications
What we do, is to create two tables for each multilingual object. E.g. the first table contains only language-neutral data (primary key, etc.) and the second table contains one record per language, containing the localized data plus the ISO code of the language. In some cases we add a DefaultLanguage field, so that we can fall-back to that language if no localized data is available for a specified language. Example: ``` Table "Product": ---------------- ID : int <any other language-neutral fields> Table "ProductTranslations" --------------------------- ID : int (foreign key referencing the Product) Language : varchar (e.g. "en-US", "de-CH") IsDefault : bit ProductDescription : nvarchar <any other localized data> ``` With this approach, you can handle as many languages as needed (without having to add additional fields for each new language). --- *Update (2014-12-14): please have a look at [this answer](https://stackoverflow.com/a/27474681/19635), for some additional information about the implementation used to load multilingual data into an application.*
I recommend the answer posted by Martin. But you seem to be concerned about your queries getting too complex: > To create localized table for every table is making design and querying complex... So you might be thinking, that instead of writing simple queries like this: ``` SELECT price, name, description FROM Products WHERE price < 100 ``` ...you would need to start writing queries like that: ``` SELECT p.price, pt.name, pt.description FROM Products p JOIN ProductTranslations pt ON (p.id = pt.id AND pt.lang = "en") WHERE price < 100 ``` Not a very pretty perspective. But instead of doing it manually you should develop your own database access class, that pre-parses the SQL that contains your special localization markup and converts it to the actual SQL you will need to send to the database. Using that system might look something like this: ``` db.setLocale("en"); db.query("SELECT p.price, _(p.name), _(p.description) FROM _(Products p) WHERE price < 100"); ``` And I'm sure you can do even better that that. The key is to have your tables and fields named in uniform way.
What are best practices for multi-language database design?
[ "", "sql", "database", "database-design", "" ]
I've got an SDK I'm working on and the previous developer just dropped the DLLs in System32 (Apparently a serious offense: [see here](https://stackoverflow.com/questions/926425/windows-versus-windows-system32-file-location-conventions)) So assuming I move them out into \Program Files\\SDK (or whatever), how do I make sure that all the apps that needs those DLLs can access them? And to clarify, all apps that access these are doing early (static) binding to the DLLs at compile time so I can't pass the full path to them or anything. They need to be able to find it just given the DLL filename only. Along the same lines, what about including a particular version of MSVCR80.dll? They all depend on this but I need to make sure they get a specific version (the one I include). Any ideas?
An SDK is by definition a development kit. It's not a deployment patch... What this means is that the applications that depend on those assemblies should ship with them and install them into their local \program files.. directories. The reason for this is let's say you decide to do a breaking change by eliminating an entry point for example. By installing your "SDK", it has the potential to stop older programs from functioning. You could take a play from the Java handbook and update the PATH environment variable. Whenever a program makes a call to an external assembly it searches along that environment variable until it finds it. Of course, this could still result in the problem showing up. So your best bet is to just install the SDK into Program Files and let the developers of the products that depend on your toolkit decide whether they want to update their versions or not. **UPDATE** As I'm thinking about this, one last possibility is to GAC your assemblies. In the event you do so, bear in mind that they should be strongly named and properly versioned so as not to step on each other. I don't recommend this route because it hides the actual locations of the assemblies and makes uninstalling a little more difficult then simply hitting delete on your directory.
I can't tell you about your own DLLs, but you should **never** redistribute Microsoft DLLs alone. You always have to use Microsoft Redistributable Package. For example, if your application depends on dll from Dev Studio 2005 SP1, you should redistribute your application with Microsoft Visual Studio 2005 SP1 redistributable. The same applies to 2008. MS provide MSI based installer and Merge Module to include in your own product installer.
Where to install SDK DLLs on a system so that they can be found by apps that need them
[ "", "c++", "windows", "dll", "path", "" ]
I want to be able to do some profiling to some app using the Netbeans Profiler API. I'm not interested in using Visual VM , but rather in programmatically collecting data from the application[let's say CPU usage, and method execution times]. For instance, using CPU usage and hot methods. How to get that data and print it on console for instance?
This was from Jiri Sedlacek - one of the VisualVM develpers: > There's nothing like 'Netbeans > Profiler API', the profiler doesn't > have any API for public usage. Neither > VisualVM nor the NetBeans Profiler > will help you with this So that's it folks!
JRockit Mission Control have according to [new and noteworthy](http://www.oracle.com/technology/products/jrockit/missioncontrol/new_and_noteworthy/3.1.0/index.html) for the 3.1 release a public API that be used to subscribe to JMX-data and to establish connections to local/remote servers. See at the bottom of the page.
How to use the Netbeans Profiler programmatically?
[ "", "java", "api", "netbeans", "profiler", "" ]
``` double? test = true ? null : 1.0; ``` In my book, this is the same as ``` if (true) { test = null; } else { test = 1.0; } ``` But the first line gives this compiler error: > Type of conditional expression cannot > be determined because there is no > implicit conversion between '`<null>`' > and '`double`'.
This happens because the compiler tries to evaluate the statement from right to left. This means that it sees `1.0` and it decides it is double (not double?) and then it sees `null`. So there is clearly no implicit conversion between `double` and `null` (in fact there is no implicit conversion between `Struct` and `null`). What you can do is explicitly tell the compiler that one of the two expressions that are convertible to each other. ``` double? test = true ? null : (double?) 1.0; // 1 double? test = true ? (double?)null : 1.0; // 2 double? test = true ? default(double?) : 1.0; // 3 double? test = true ? new double?() : 1.0; // 4 ```
``` double? test = true ? (double?)null : 1.0; ``` will work. That's because there is no conversion from the type of the first expression (`null`) to the type of the second expression (`double`).
Why doesn't this C# code compile?
[ "", "c#", ".net", "nullable", "" ]
I'm looking to simulate the action of holding a keyboard key down for a short period of time in Java. I would expect the following code to hold down the A key for 5 seconds, but it only presses it once (produces a single 'a', when testing in Notepad). Any idea if I need to use something else, or if I'm just using the awt.Robot class wrong here? ``` Robot robot = null; robot = new Robot(); robot.keyPress(KeyEvent.VK_A); Thread.sleep(5000); robot.keyRelease(KeyEvent.VK_A); ```
Thread.sleep() stops the current thread (the thread that is holding down the key) from executing. If you want it to hold the key down for a given amount of time, maybe you should run it in a parallel Thread. Here is a suggestion that will get around the Thread.sleep() issue (uses the command pattern so you can create other commands and swap them in and out at will): ``` public class Main { public static void main(String[] args) throws InterruptedException { final RobotCommand pressAKeyCommand = new PressAKeyCommand(); Thread t = new Thread(new Runnable() { public void run() { pressAKeyCommand.execute(); } }); t.start(); Thread.sleep(5000); pressAKeyCommand.stop(); } } class PressAKeyCommand implements RobotCommand { private volatile boolean isContinue = true; public void execute() { try { Robot robot = new Robot(); while (isContinue) { robot.keyPress(KeyEvent.VK_A); } robot.keyRelease(KeyEvent.VK_A); } catch (AWTException ex) { // Do something with Exception } } public void stop() { isContinue = false; } } interface RobotCommand { void execute(); void stop(); } ```
Just keep pressing? ``` import java.awt.Robot; import java.awt.event.KeyEvent; public class PressAndHold { public static void main( String [] args ) throws Exception { Robot robot = new Robot(); for( int i = 0 ; i < 10; i++ ) { robot.keyPress( KeyEvent.VK_A ); } } } ``` I think the answer provided by edward will do!!
Simulate a key held down in Java
[ "", "java", "awt", "keypress", "keyevent", "" ]
Let's say i have a sql datetime of '1 May 2009' or '12 May 2009'. Is there any built in sql function / operation i can perform on the dates above to return the string representation of the DAY of the date? So for '1 May 2009' i'll get "Friday" as the answer (case not important). For '12 May 2009' i'll get "Tuesday".
[DATENAME](http://msdn.microsoft.com/en-us/library/ms174395.aspx) ``` SELECT DATENAME(weekday, '1 May 2009') ``` Edit: For MS SQL Server
``` DATE_FORMAT(somedatetimevariable, '%W'); ``` Ref: <http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-format> Edit (gbn): For MySQL
Get string representation of a sql DateTime day
[ "", "sql", "datetime", "dayofweek", "weekday", "" ]
Why does defining `__getitem__` on a class make it iterable? For instance if I write: ``` class B: def __getitem__(self, k): return k cb = B() for k in cb: print k ``` I get the output: ``` 0 1 2 3 4 5 ... ``` I would really expect to see an error returned from `for k in cb:`.
If you take a look at [PEP234](http://www.python.org/dev/peps/pep-0234) defining iterators, it says: > 1. An object can be iterated over with `for` if it implements `__iter__()` or `__getitem__()`. > 2. An object can function as an iterator if it implements `next()`.
Iteration's support for `__getitem__` can be seen as a "legacy feature" which allowed smoother transition when [PEP234](https://peps.python.org/pep-0234/) introduced iterability as a primary concept. It only applies to classes without `__iter__` whose `__getitem__` accepts integers 0, 1, &c, and raises `IndexError` once the index gets too high (if ever), typically "sequence" classes coded before `__iter__` appeared (though nothing stops you from coding new classes this way too). Personally, I would rather not rely on this in new code, though it's not deprecated nor is it going away (works fine in Python 3 too), so this is just a matter of style and taste ("explicit is better than implicit" so I'd rather explicitly support iterability rather than rely on `__getitem__` supporting it implicitly for me -- but, not a bigge).
Why does defining __getitem__ on a class make it iterable in python?
[ "", "python", "iterator", "overloading", "" ]
I want to convert a web pages which is heavily CSS styled is written in PHP to static html so that I can embed it in an email. I have managed to do this but for achieving this I had to convert the whole page into a string and then assign that string as email body. The layout of the page does not look as good as original as I have not been able embed CSS. This approach has a few problems like if any changes have to be made to the layout of the page I have to redo the whole process for generating an embeddable page. I want an easier way which will allow me to keep the original page editable in Dreamweaver visually.
You can use output buffers. If you have an html page, such as: ``` <html> <head> <title>Blah</title> </head> <body> Some text here </body> </html> ``` Then if you put, at the top of the html file: ``` <?php ob_start(); ?> ``` And right at the bottom, after the last tag, put: ``` <?php $string = ob_get_contents(); //do whatever you need to do to the html, save it to a seperate file, email it, etc ob_flush(); ?> ``` What this basically means is that the $string variable will end up with the entire static html of the page, after it has been dynamically generated. You can then use that string in an email. Although really, html pages don't work exactly the same in emails, so you may want to rethink the approach.
This is a hard thing to do automatically for several reasons: 1. If your thought HTML support in browsers was bad, email programs are an order of magnitude worse. Basically you should write HTML like it was 1999, so HTML 3.2/4.0, no CSS; 2. You have a choice of including images as external links or embed them directly in the email. External links take up less space but many mailers block them as they're used by spammers to tag live addresses (by making each image URL they send unique and thus they can figure out which email was opened). Embedded images use a slightly different reference format; 3. CSS support should basically be treated as nonexistant. All CSS must be internal; 4. It is best practice, when sending HTML email, to also send a plain-text version for clients that either don't have HTML support or the user has disabled it (yes this does happen). And there is no good way of turning a complex HTML page into a plain text equivalent. It basically has to be done by hand; and 5. Email content is different to Webpage content. Webpages typically have search boxes, menus, sidebars, headers, footers and so on. These are all things you're not interested in emailing. You're only interested in the content of the page. So blogs work quite well for this because the content of a blog post can easily be extracted. It's harder with arbitrary pages. So there are various ways you could do this like using cURL to get the Webpage, using output buffering to capture the page by using require/include, etc but all these methods suffer from one or more of the above problems. I've generally found the only way to do HTML email is to hand-roll it.
Easiest way to convert a PHP page to static HTML page
[ "", "php", "html", "email", "xhtml", "static", "" ]
In my app I have some longish labels, on a chinese os the labels overflow and push out other components also. This has only been observed on a chinese os. How can I detect and handle overflowing components?
I am guessing that this is a problem for some, depending on the window-size and language. Maybe not what you want, but you can check the size of the text like this: ``` // get metrics from the graphics FontMetrics metrics = graphics.getFontMetrics(font); // get the height of a line of text in this font and render context int hgt = metrics.getHeight(); // get the advance of my text in this font and render context int adv = metrics.stringWidth(text); ``` If the text is longer than a limit (you have to pull out of a hat,) you can truncate or perhaps even abbreviate it - if it is known, or possibly replace it with an icon and use a tooltip to show the full text.
JComponent has a [setMaximumSize](http://java.sun.com/javase/6/docs/api/javax/swing/JComponent.html#setMaximumSize(java.awt.Dimension)) method that could help you. Depending on the LayoutManager you are using, the results may be different. For setting constraints like this at Layout level, check the [SpringLayout](http://java.sun.com/docs/books/tutorial/uiswing/layout/spring.html).
Handling overflowing components in swing
[ "", "java", "swing", "" ]
Hey, I want to store application configuration data. Currently, I'm using INIs but they are too old and now I want to try something new. I'm on .NET platform using C#. What solutions do I have? app.configs? The scenario here is like that, I want to let other programs read the configuration data.
Yes, the various .config files (app.config, web.config, etc..) have replaced INI and, to a certain extent, the Registry as the preferred means of storing configuration data for your application. Any program, .Net or otherwise, can read those files. .Net has the ConfigurationManager class and other languages can simply do XML parsing to get the values they need.
The standard approach with .NET is to use app.config files for application settings and user.config files for user specific settings (the location varies between XP and Vista though). There's nothing to stop other programs reading the configuration data, you just need to have a configuration setting in the second (or third) application that tells it where to look.
C# Application Configuration Data
[ "", "c#", ".net", "configuration", "" ]
I have been reading about the various memory management issues that .NET Asynchronous Sockets have. There are but a handful of links, but spidering this one will get you them all: <http://codebetter.com/blogs/gregyoung/archive/2007/06/18/async-sockets-and-buffer-management.aspx> **Basically** when a socket is asynchronously sending/receiving many small byte[]'s the send/receive byte[]'s are pinned in memory leading to fragmentation. SO for the purposes of creating a buffer manager : I have a managed buffer (byte[]) ``` byte[] managedBuffer = new byte[1024]; // do stuff with managedBuffer; ``` how do I send this byte[] to the socket's asynchronous .BeginSend() method by reference? ``` // I don't want to pass the VALUE to the method, but a reference // to managedBuffer; System.Net.Sockets.Socket.BeginSend(managedBuffer...(other params)); ```
As indicated by Nik, you are already passing it by reference when you pass the `byte[]` to the method. However, there are benefits to using the `ArraySegment` method you found in the documentation; they are primarily to avoid memory fragmentation issues inherent in the pinning of the `byte[]` buffer during an async call. See my answer to: [How to write a scalable Tcp/Ip based server](https://stackoverflow.com/questions/869744/how-to-write-a-scalable-tcp-ip-based-server/908766#908766) for more details.
Arrays are always passed by reference, so you're already doing that. If you're using the socket asynchronously then you'll need to make sure you don't use managedBuffer while it's in progress.
how do I pass a byte[] reference as the buffer in a System.Net.Sockets.Send().Recieve()
[ "", "c#", "sockets", "memory-management", "" ]
Following query is used for Getting Categories and one news for each category. How can I write this query using LINQ ``` SELECT * FROM News n where n.NewsID IN (SELECT TOP 1 NewsID FROM News v WHERE v.CategoryID = n.CategoryID ORDER BY CreatedOn DESC) ``` Thanks in advance.
Not tested, but try something like this: ``` using (var db = new YourDataContext()) { var results = from n in db.News let v = db.News where n.NewsId == v.Where(c=>c.CategoryId == n.CategoryId) .OrderByDescending(o=>o.CreatedOn).First() select n; } ```
``` var q = from n in dc.News group n by n.CategoryId into g let ti = g.OrderByDescending(x => x.CreatedOn).FirstOrDefault() where ti != null select ti; ```
How to write this query in LINQ?
[ "", "sql", "linq", "" ]
How can I use the `NOLOCK` function on Entity Framework? Is XML the only way to do this?
No, but you can start a transaction and set the [isolation level to read uncommited](https://stackoverflow.com/questions/1018651/nolock-vs-transaction-isolation-level). This essentially does the same as NOLOCK, but instead of doing it on a per table basis, it will do it for everything within the scope of the transaction. If that sounds like what you want, here's how you could go about doing it... ``` //declare the transaction options var transactionOptions = new System.Transactions.TransactionOptions(); //set it to read uncommited transactionOptions.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted; //create the transaction scope, passing our options in using (var transactionScope = new System.Transactions.TransactionScope( System.Transactions.TransactionScopeOption.Required, transactionOptions) ) //declare our context using (var context = new MyEntityConnection()) { //any reads we do here will also read uncomitted data //... //... //don't forget to complete the transaction scope transactionScope.Complete(); } ```
Extension methods can make this easier ``` public static List<T> ToListReadUncommitted<T>(this IQueryable<T> query) { using (var scope = new TransactionScope( TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted })) { List<T> toReturn = query.ToList(); scope.Complete(); return toReturn; } } public static int CountReadUncommitted<T>(this IQueryable<T> query) { using (var scope = new TransactionScope( TransactionScopeOption.Required, new TransactionOptions() { IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted })) { int toReturn = query.Count(); scope.Complete(); return toReturn; } } ```
Entity Framework with NOLOCK
[ "", "c#", "entity-framework", "ado.net", "" ]
While it is trivial to store a checkbox's checked state in a variable using the checkbox's Click event, how would I do it via databinding? All the examples I have found have the UI updated from some datasource, or bind one control to another; I want to update a member variable when the checkbox is clicked. TIA for any pointers...
You need a dependency property for this: ``` public BindingList<User> Users { get { return (BindingList<User>)GetValue(UsersProperty); } set { SetValue(UsersProperty, value); } } public static readonly DependencyProperty UsersProperty = DependencyProperty.Register("Users", typeof(BindingList<User>), typeof(OptionsDialog)); ``` Once that is done, you bind the checkbox to the dependency property: ``` <CheckBox x:Name="myCheckBox" IsChecked="{Binding ElementName=window1, Path=CheckBoxIsChecked}" /> ``` For that to work you have to name your Window or UserControl in its openning tag, and use that name in the ElementName parameter. With this code, whenever you change the property on the code side, you will change the textbox. Also, whenever you check/uncheck the textbox, the Dependency Property will change too. EDIT: An easy way to create a dependency property is typing the snippet propdp, which will give you the general code for Dependency Properties. All the code: XAML: ``` <Window x:Class="StackOverflowTests.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="Window1" x:Name="window1" Height="300" Width="300"> <Grid> <StackPanel Orientation="Vertical"> <CheckBox Margin="10" x:Name="myCheckBox" IsChecked="{Binding ElementName=window1, Path=IsCheckBoxChecked}"> Bound CheckBox </CheckBox> <Label Content="{Binding ElementName=window1, Path=IsCheckBoxChecked}" ContentStringFormat="Is checkbox checked? {0}" /> </StackPanel> </Grid> </Window> ``` C#: ``` using System.Windows; namespace StackOverflowTests { /// <summary> /// Interaction logic for Window1.xaml /// </summary> public partial class Window1 : Window { public bool IsCheckBoxChecked { get { return (bool)GetValue(IsCheckBoxCheckedProperty); } set { SetValue(IsCheckBoxCheckedProperty, value); } } // Using a DependencyProperty as the backing store for //IsCheckBoxChecked. This enables animation, styling, binding, etc... public static readonly DependencyProperty IsCheckBoxCheckedProperty = DependencyProperty.Register("IsCheckBoxChecked", typeof(bool), typeof(Window1), new UIPropertyMetadata(false)); public Window1() { InitializeComponent(); } } } ``` Notice how the only code behind is the Dependency Property. Both the label and the checkbox are bound to it. If the checkbox changes, the label changes too.
You must make your binding bidirectional : ``` <checkbox IsChecked="{Binding Path=MyProperty, Mode=TwoWay}"/> ```
WPF checkbox binding
[ "", "c#", "wpf", "xaml", "data-binding", "checkbox", "" ]
I have the following structure: ``` <div id="container"> <div id="someid1" style="float:right"></div> <div id="someid2" style="float:right"></div> <div id="someid3" style="float:right"></div> <div id="someid4" style="float:right"></div> </div> ``` Now someid is acually a unique id for that div. Now i receive an array which has a different order say someid 3,2,1,4, then how do i move these divs around to match the new order using jQuery? Thankyou very much for your time.
My plugin version - **[Working Demo](http://jsbin.com/ihuqo)** Takes an array and optional id prefix and reorders elements whose ids correspond to the order of (id prefix) + values inside the array. Any values in the array that don't have an element with the corresponding id will be ignored, and any child elements that do not have an id within the array will be removed. ``` (function($) { $.fn.reOrder = function(array, prefix) { return this.each(function() { prefix = prefix || ""; if (array) { for(var i=0; i < array.length; i++) array[i] = $('#' + prefix + array[i]); $(this).empty(); for(var i=0; i < array.length; i++) $(this).append(array[i]); } }); } })(jQuery); ``` Code from the demo **jQuery** ``` $(function() { $('#go').click(function() { var order = $('#order').val() == ""? null: $('#order').val().split(","); $('#container').reOrder(order, 'someid'); }); }); (function($) { $.fn.reOrder = function(array, prefix) { return this.each(function() { prefix = prefix || ""; if (array) { for(var i=0; i < array.length; i++) array[i] = $('#' + prefix + array[i]); $(this).empty(); for(var i=0; i < array.length; i++) $(this).append(array[i]); } }); } })(jQuery); ``` **HTML** ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script> <title>reOrder Demo</title> <meta http-equiv="Content-type" content="text/html; charset=utf-8" /> <style type="text/css" media="screen"> body { background-color: #fff; font: 16px Helvetica, Arial; color: #000; } div.style { width: 200px; height: 100px; border: 1px solid #000000; margin: 5px; } </style> </head> <body> <div id="container"> <div id="someid1" class="style" style="background-color:green;">div1</div> <div id="someid2" class="style" style="background-color:blue;">div2</div> <div id="someid3" class="style" style="background-color:red;">div3</div> <div id="someid4" class="style" style="background-color:purple;">div4</div> </div> <p>Pass in a comma separated list of numbers 1-4 to reorder divs</p> <input id="order" type="text" /> <input id="go" type="button" value="Re-Order" /> </body> </html> ```
[Edit], This is tested and works: ``` var order = [3,2,1,4]; var container = $("#container"); var children = container.children(); container.empty(); for (var i = 0; i < order.length; i++){ container.append(children[order[i]-1]) } ``` The i-1 is necessary since your ordering starts at 1 but arrays are indexed from 0. Thanks to J-P and Russ Cam for making me look at it again.
Dynamically arranging divs using jQuery
[ "", "javascript", "jquery", "" ]
I need recommendations for a good (free) development notepad to work in on my new macbook, mainly for PHP, AJAX etc.
[TextWrangler](http://www.barebones.com/products/TextWrangler/) is a free Mac text editor, which has PHP support built-in.
I know you've request it be free - but really, I can't stress TextMate enough. It's fantastic and it's also cheap (around $30). It is well worth the price tag. If you insist on staying free - try Eclipse with PDT.
What development notepad should I use?
[ "", "php", "macos", "notepad", "" ]
Does anyone know a way to execute a bulk dump of every email of a gmail account and write the emails to a file? I'm looking to write a program that would let users back up there gmail (probably via imap) and back it up to either individual files or as a pst (I know pst will probably be much harder)
some time ago I wrote a blog post about exactly same topic. See [HOWTO: Download emails from a GMail account in C#](http://blog.rebex.net/news/archive/2007/05/14/howto-download-emails-from-gmail-account-in-csharp.aspx) for details. Code uses our [Rebex Mail component](http://www.rebex.net/secure-mail.net/): ``` using Rebex.Mail; using Rebex.Net; ... // create the POP3 client Pop3 client = new Pop3(); try { // Connect securely using explicit SSL. // Use the third argument to specify additional SSL parameters. Console.WriteLine("Connecting to the POP3 server..."); client.Connect("pop.gmail.com", 995, null, Pop3Security.Implicit); // login and password client.Login(email, password); // get the number of messages Console.WriteLine("{0} messages found.", client.GetMessageCount()); // ----------------- // list messages // ----------------- // list all messages ListPop3MessagesFast(client); // unique IDs and size only //ListPop3MessagesFullHeaders(client); // full headers } finally { // leave the server alone client.Disconnect(); } public static void ListPop3MessagesFast(Pop3 client) { Console.WriteLine("Fetching message list..."); // let's download only what we can get fast Pop3MessageCollection messages = client.GetMessageList(Pop3ListFields.Fast); // display basic info about each message Console.WriteLine("UID | Sequence number | Length"); foreach (Pop3MessageInfo messageInfo in messages) { // display header info Console.WriteLine ( "{0} | {1} | {2} ", messageInfo.UniqueId, messageInfo.SequenceNumber, messageInfo.Length ); // or download the whole message MailMessage mailMessage = client.GetMailMessage(messageInfo.SequenceNumber); } } ```
Gmail provides [POP](http://en.wikipedia.org/wiki/Post_Office_Protocol) [access](http://mail.google.com/support/bin/answer.py?hl=en&answer=13273). So just use any [library](http://sourceforge.net/projects/hpop/) that allows you to communicate using POP and you're golden. **Edit:** I just noticed that you mentioned IMAP; I recommend you use POP instead for bulk dumps. IMAP is too chatty for what you want to do. If you must use IMAP, here's [a library](http://sourceforge.net/projects/imapnet/) for you.
Download emails (backup) from gmail programmatically
[ "", "c#", "email", "backup", "gmail", "imap", "" ]
My application keeps running into Timeout Expired SqlExceptions. The thing is that this query is one that will simply have to run for a decent amount of time. I'm having trouble figuring out where this exception is occurring though. Is this a timeout that's created at the database server or is it happening in my program? Or if it could be both, how do I figure out which one it is? And lastly, how do I extend the timeout period?
It is likely that you are running over the [CommandTimeout](http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.commandtimeout.aspx) set on your DataContext. This defaults to 30 seconds. All you need to do is set the property on the DataContext before you execute your query.
increase timeout = **BAD** fix query = **GOOD** I'm not sure of all the details involved, but in general the followng applies: when a query runs slow do the following in management studio: * run SET ShowPlan\_All ON * run your query * look at the output for the word "scan". your problem is there. "Scan" = touch each row (table or index). Would you like to "scan" a phone book looking for one number or use the index?
What causes Timeout expired SqlExceptions in LINQ to SQL?
[ "", "c#", "sql-server", "sql-server-2005", "linq-to-sql", "sqlexception", "" ]
I want to build projects from the command line. Is it possible to deploy a C# compiler without installing [Visual Studio](http://en.wikipedia.org/wiki/Microsoft_Visual_Studio)?
Sure, the framework includes a compiler, csc.exe. Look at [this article](https://web.archive.org/web/20090426124057/http://www.tipsntracks.com/52/get-a-free-csharp-command-line-compiler.html) for a quick how-to. The important parts: > You can get the command-line compiler (csc.exe) from Microsoft site > <http://msdn2.microsoft.com/en-us/netframework/aa731542.aspx>. > > Download the redistributable package of the .NET Framework, which includes the compiler and the .NET Framework with C# 2005 syntax support. > > The compiler is located in the following > directory: > %windir%\Microsoft.NET\Framework\ Also look at [this MSDN article](http://msdn.microsoft.com/en-us/library/ms379563(VS.80).aspx) for a full guide and explanation. Note that for more recent versions, you will be looking for the MSBuild standalone package rather than the framework -- see [@Vadzim's answer](https://stackoverflow.com/a/47624225/44853).
Of course. Do: ``` sudo apt-get install mono-gmcs ``` Everyone else assumed Windows and MS .NET, but...
Is it possible to install a C# compiler without Visual Studio?
[ "", "c#", "compiler-construction", "msbuild", "csc", "" ]
I'm using an API that has a method that requires this type of argument: ``` System.Collections.ObjectModel.Collection<GenericTickType> genericTickList ``` How do I instantiate an object for that argument? Here's what I've tried but it keeps saying that the method call has some invalid arguments. ``` List<TickType> ticks_to_get = new List<TickType> { TickType.Price }; ``` I've tried instantiating a Collection directly instead of a List and that doesn't seem to work.
> "I've tried instantiating a Collection directly instead of a List and that doesn't seem to work." What error do you get? You can definitely create an instance of `Collection<T>` directly, it is not an abstract class and it has several public constructors, including one that's parameter-less. You can do this, for example: ``` var values = new System.Collections.ObjectModel.Collection<int> { 1,2,3,4 }; ``` I noticed your sample code has a `GenericTickType` and a `TickType`. Is this a mistake or do you actually have two classes? You said it's an enum (which one?), so one cannot possibly derive from the other. If they are two enum types, `Collection<GenericTickType>` and `Collection<TickType>` are two different classes and one is not assignable to the other. Now, if `TickType` is *castable* to `GenericTickType` (and they probably are if they are both enums, and assuming they share the same numeric values), you still cannot cast `Collection<TickType>` to `Collection<GenericTickType>`. There's no contra/co-variance in C# for most classes yet (coming in C# 4). But you could cast *each* `TickType` by doing something like this: ``` List<GenericTickType> list = new List<GenericTickType> { (GenericTickType)TickType.Price }; list.Add((GenericTickType)TickType.Price); // add more... Collection<GenericTickType>genericTicks = new Collection<GenericTickType>(list); ``` If you already have a `List<TickType>` and have access to C# 3.0 and LINQ, you can do this: ``` List<TickType> ticks = new List<TickType> { TickType.Price }; list.Add(TickType.Price); // add more... List<GenericTickType> castedList = ticks.Cast<GenericTickType>().ToList(); Collection<GenericTickType>genericTicks = new Collection<GenericTickType>(castedList); ``` This uses the LINQ `Cast<T>()` and `ToList<T>()` extension methods to cast *each* `TickType` in the original list to `GenericTickType` and creating a new `List<GenericTickType>` which is used to instantiate the `Collecion<GenericTickType>`. (I avoided using `var` so you could see the types in each step).
You can't pass a `List<>` as a `Collection<>` Maybe you have problems with covariance/contravariance? You have to do the cast on your own: ``` List<TickType> ticks_to_get = new Collection<TickType> { TickType.Price }; genericTickList = (Collection<GenericTickType>) ticks_to_get; ``` Look at Dave Bauman's answer ... unless TickType.Price doesn't return an object of type TickType it will not work **EDIT:** Since GenericTickType is an enum - which API are you using? Is it of your company - can you change it? It seems to be strange that you are asked to pass a collection of enum values. See, if you can change the enum to a [flagged enum](http://msdn.microsoft.com/en-us/library/cc138362.aspx) ... and then pass the required values by combining them with the or-operator.
Format for Passing a Collection to a Method
[ "", "c#", "collections", "" ]
Is there a way to get the value of a HashMap randomly in Java?
This works: ``` Random generator = new Random(); Object[] values = myHashMap.values().toArray(); Object randomValue = values[generator.nextInt(values.length)]; ``` If you want the random value to be a type other than an `Object` simply add a cast to the last line. So if `myHashMap` was declared as: ``` Map<Integer,String> myHashMap = new HashMap<Integer,String>(); ``` The last line can be: ``` String randomValue = (String) values[generator.nextInt(value.length)]; ``` --- The below **doesn't work**, `Set.toArray()` always returns an array of `Object`s, which can't be coerced into an array of `Map.Entry`. ``` Random generator = new Random(); Map.Entry[] entries = myHashMap.entrySet().toArray(); randomValue = entries[generator.nextInt(entries.length)].getValue(); ```
Since the requirements only asks for a random value from the `HashMap`, here's the approach: 1. The [`HashMap`](http://java.sun.com/javase/6/docs/api/java/util/HashMap.html) has a [`values`](http://java.sun.com/javase/6/docs/api/java/util/HashMap.html#values()) method which returns a [`Collection`](http://java.sun.com/javase/6/docs/api/java/util/Collection.html) of the values in the map. 2. The `Collection` is used to create a [`List`](http://java.sun.com/javase/6/docs/api/java/util/List.html). 3. The [`size`](http://java.sun.com/javase/6/docs/api/java/util/List.html#size()) method is used to find the size of the `List`, which is used by the [`Random.nextInt`](http://java.sun.com/javase/6/docs/api/java/util/Random.html#nextInt(int)) method to get a random index of the `List`. 4. Finally, the value is retrieved from the `List` [`get`](http://java.sun.com/javase/6/docs/api/java/util/List.html#get(int)) method with the random index. Implementation: ``` HashMap<String, Integer> map = new HashMap<String, Integer>(); map.put("Hello", 10); map.put("Answer", 42); List<Integer> valuesList = new ArrayList<Integer>(map.values()); int randomIndex = new Random().nextInt(valuesList.size()); Integer randomValue = valuesList.get(randomIndex); ``` The nice part about this approach is that all the methods are [generic](http://java.sun.com/j2se/1.5.0/docs/guide/language/generics.html) -- there is no need for typecasting.
Is there a way to get the value of a HashMap randomly in Java?
[ "", "java", "collections", "hashmap", "" ]
I'm opening lots of files with fopen() in VC++ but after a while it fails. Is there a limit to the number of files you can open simultaneously?
The C run-time libraries have a 512 limit for the number of files that can be open at any one time. Attempting to open more than the maximum number of file descriptors or file streams causes program failure. Use `_setmaxstdio` to change this number. More information about this can be read [here](http://msdn.microsoft.com/en-us/library/kdfaxaay(vs.71).aspx) Also you may have to check if your version of windows supports the upper limit you are trying to set with `_setmaxstdio`. For more information on `_setmaxstdio` check [here](http://msdn.microsoft.com/en-us/library/6e3b887c(vs.71).aspx) Information on the subject corresponding to VS 2015 can be found [here](https://msdn.microsoft.com/en-us/library/kdfaxaay(v=vs.140).aspx)
In case anyone else is unclear as to what the limit applies to, I believe that this is a per-process limit and not system-wide. I just wrote a small test program to open files until it fails. It gets to 2045 files before failing (2045 + STDIN + STDOUT + STDERROR = 2048), then I left that open and ran another copy. The second copy showed the same behaviour, meaning I had at least 4096 files open at once.
Is there a limit on number of open files in Windows
[ "", "c++", "windows", "" ]
All our applications rely on a certain amount of client data i.e. Lookups for comboboxes, users, roles, user-roles... We currently use a spreadsheet to map the data and generate insert scripts that are then imported into SQL server. The has seemed to work for us but it is very difficult to update and maintain when there are a lot of changes going on (excel is not good at merging data) and it is slow when there is a lot of data. I am sure this is a common problem and would to hear how others have approached it so we could borrow some ideas and improve our process.
Excel rocks for importing data. You can quickly edit, troubleshoot, and it has lots of options to organize data. Several developers at my company tried to phase out the Excel data import sheets, but they all failed (one after 6 man-months.) It not always worth the effort to build a specialized data entry web site or windows app. :)
Infopath and SharePoint? (just throwing it out there. It takes some skill to setup well which I would generally doubt that you have at your company)
Maintaining Customer Data
[ "", "sql", "database", "excel", "agile", "" ]
Is it possible for a Non-Interpreted language to have a Garbage collector. Interpreted languages have the Interpretor executing the Program line by line so the Interpretor might just as well provide a runtime with a GC. But is it possible to have a Garbage collector for any other language without building the GC in your code itself ?
Yes. C++ with a smart pointer implementation will garbage collect as the smart pointer reference counts go to zero. You have garbage collection. You did not build it yourself.
Garbage collection only requires the pointer variables be marked special way so that the runtime can identify them and use for garbage collection. It has nothing to do with interpretation/compilation, but instead requires special runtime and storing additional data with each variable.
Can a Non-Interpreted language have a Garbage Collector?
[ "", "java", "language-agnostic", "garbage-collection", "interpreter", "" ]
I wrote a console program in c# that takes up to three files as input, and does some data calculations on them. I'd like to make a simple frontend that allows the user to easily * import files - basically choose up to three files to be routed to the backend code * change settings - I have about 10 settings that I'm currently storing in an app.config file. maybe a simple settings box would be nice * see what's going on - the console program shows some status messages that might be useful to display on a GUI I have practically no experience with windows forms or GUI design, so I really don't know where to begin. I compiled the backend stuff into a \*.dll and am currently playing around in design mode of sharpdevelop...but i really have no idea how to get the two to work together. any pointers would be greatly appreciated!
If you want to get started with GUI design in .NET, I recommend you choose WPF (Windows Presentation Foundation). This is the latest technology released in the UI/graphics area by Microsoft and is where everything is heading now. (Windows Forms won't be obsolete for a long time, though it is surely but slowly becoming deprecated.) I noticed however that you are using SharpDevelop, which doesn't yet have real support for WPF (as far as I know), whereas it certainly does for WinForms. If there's any chance you can use Visual Studio, I recommend you begin by learning WPF. You have the advantage of not being confused by previous experience with the styles and methodologies of WinForms, so it would very much be the right way to go. Whichever you wish to learn, the [Getting Started page of WindowsClient.NET](http://windowsclient.net/getstarted/) (the official MS site for both WinForms and WPF) would be a great resource. There's also a few [MSDN articles](http://msdn.microsoft.com/en-us/library/ms742119.aspx) on getting started with WPF. Hope that helps.
The usual pattern, in cases like these, is to make the main features of the application into a class library and call that from a wrapping executable, such as a console app, winforms app or webforms app (if possible). That way you can easily adapt the interface as needed and simply route input and output to and from the class library. Edit: I realize this isn't a very indepth answer, but I hope it helps to get started at least, together with any other answer that may arrive.
C# Making a Frontend to a Console Program?
[ "", "c#", "console", "frontend", "" ]
On Mac OS X 10.5 with Java 1.5, I have this code snippet. ``` public static void main(String[] args) { String name = "Алексей"; System.out.println("name = " + name); } ``` The output is: ``` name = ??????? ``` I expected to see: ``` name = Алексей ``` How can I make this happen?
Thanks to all the helpful ideas. It turns out the key to my problem was this sentence: > On **Mac OS X 10.5** with Java 1.5, I have this code snippet The IDE I'm using, IntelliJ IDEA was explicitly setting the file encoding to MacRoman. By changing the encoding for the project to UTF-8, the problem was solved without any code changes.
There are two potential problems here. First, you have Cyrillic characters in your source code. This means that you have to ensure the encoding that you used to store the file is the same as that used by the compiler. Check out the *javac* manpage to see what its default encoding is, and/or how to specify a specific encoding. Or, use Unicode escapes within your string. Second possibility is that your terminal font doesn't display the Cyrillic characters. I don't think this is what's happening, however, since (1) you're able to see the characters in the source code, and (2) I believe missing glyphs render as blocks, incorrect encodings render as question marks. To test, simply replace your string with the correct Unicode escapes, and verify that the characters render on your screen.
How can I make a String with cyrillic characters display correctly?
[ "", "java", "macos", "character-encoding", "" ]
I am just getting started using any DI/IoC toolset and have a very basic question. I am using Unity as we will also be using a number of the Enterprise Library blocks throughout the application. The question that I have is around the dependencies to .NET framework classes. For instance, in one of the classes that I am working on currently, I need to create DirectoryInfo classes. According to my understanding, one of the best practices in DI is to never use the "new" keyword - as this introduces a hard dependency. So how should I get a new DirectoryInfo? Add it as an item to the container and have the container a dependency of the class? This seems that it would be impratical in real life usage as I would end up with the container being configurated with literally hudreds to thousands of framework classes. I would consider that to be a maintance nightmare.
The way I see it, the majority of classes in the BCL (base class library) are utiity classes, and generally don't have a ton of other dependancies other than straight up call graphs. DI is designed to flatten the call graphs and prevent a lot of cross talk between classes. As such, and the fact that you can't do anything about the BCL chattiness, you might as well just accept them for what they are and go ahead and use new... The only reason why you wouldn't want to, is for testing purposes. You're not typically testing BCL classes, but you might want to replace a BCL class with a mocked version so that it doesn't actually do whatever it is the class does, only pretend to do so.. and you can use stuff like SystemWrapper to do that if necessary.
I would say that is a little over engineering. I would think that the path of the DirectoryInfo to create should be passed in or have some sort of configuration repository( or service) class passed in that holds (or gives you a way to get) that data.
Unity Best Practices with .NET Framework Classes
[ "", "c#", ".net", "dependency-injection", "inversion-of-control", "" ]
Where can I find the windows certificate store location on the hard drive for server 2003. I am coding a c# utility for managing few certificates we use to notify when they are expiring. So, I choose to store them in the windows certificate store. Instead of using any existing location(Personal...) that I see in MMC I would like to create another location with my application name and a place(eg: 'c:\certs') of my choice, so that I can back up.
I strongly suspect that you don't need to create your own location. Do you have a good reason for wanting one? Windows has APIs to manage certificates, and I would suggest looking into those. I am pretty sure you can do all reasonable things though the public API. If you use the APIs with the system store, you will likely have to write less code, and your resulting solution will be more secure, better integrated with the OS (and all the OTHER tooling built for dealing with certs on windows)
I know this kind of old question, but when I was looking for an answer to the similar question, I was able to find that certificate information is stored in the windows registry, not in the regular files: <http://technet.microsoft.com/en-us/library/cc787544(WS.10).aspx#w2k3tr_certs_tools_dgzz>
Windows certificate store
[ "", "c#", ".net", "windows", "ssl", "certificate", "" ]
This is a weird one. I am using the ExecWB method to create a PrintPreview window. Most of the time the print preview appears correctly. But sometimes it shows a blank page and that is all. Has anyone seen this before? The problem appears to be isolated to IE6. The problem is very hit and miss so it is difficult to determine what is going wrong. ``` function onBodyLoad() { if (document.getElementById("contentPanel") != null) { var editCloseCell = document.getElementById('editCloseCell'); editCloseCell.style.visibility = "hidden"; var OLECMDID = 7; // 7 == Print Preview var PROMPT = 1; // 2 == DONTPROMPTUSER document.getElementById('webBrowser').ExecWB(OLECMDID, PROMPT); editCloseCell.style.visibility = "visible"; ``` The 'webBroswer' element is an object. The contents of the control seem to be displaying correctly. Could it be that the execWB method is being called before the control is populated?? Any insite on this would be helpful. Thanks!
The problem appears to be JQuery.. believe it or not. On the same page where I am using the ExecWB() method I am also including the JQuery library to do some non-related POSTS to my webservice. I tried removing the JQuery from this page and it seems to have fixed the issue. My first thought was that there must be some conflict with the $. So I included the jQuery.noConflicts() and changed my POST method to jQuery.Ajax. The same issue arises. So I reluctantly had to remove my JQuery reference and refactor the Ajax call. IE6 is not cool... not cool at all.
I have noticed that zooming seems to fix the preview. I wonder if anyone has seen this?
ExecWB Print Preview Sometimes shows blank pages
[ "", "javascript", "internet-explorer", "internet-explorer-6", "exec", "" ]
How can I read the track information (author, track title, length) for an Audio CD using C#?
There is an excellent tutorial at: <http://khason.net/dev/audio-cd-operation-including-cd-text-reading-in-pure-c/> I hope that will be enough, good luck.
hmmm maybe I'm wrong but I think that there is no such information in audio CD. Maybe u must use something like CDDB
Read audio CD track information
[ "", "c#", "audio", "cd-rom", "" ]
My SQLite is version 3.4.0: [image](http://www.picamatic.com/show/2009/05/30/03/33/3822461_343x44.jpg) However my phpinfo's PDO support for SQLitev3 is not enabled/listed: [image](http://www.picamatic.com/show/2009/05/30/03/32/3822444_630x115.jpg) How can I enable it? I installed my web server via XAMPP.
I think that the PDO driver for sqlite3 is called 'sqlite', so you already have it installed. The sqlite2 driver is older. > PDO\_SQLITE is a driver that > implements the PHP Data Objects (PDO) > interface to enable access to SQLite 3 > databases. > > In PHP 5.1, the SQLite extension also > provides a driver for SQLite 2 > databases; while it is not technically > a part of the PDO\_SQLITE driver, it > behaves similarly, so it is documented > alongside it. The SQLite 2 driver for > PDO is provided primarily to make it > easier to import legacy SQLite 2 > database files into an application > that uses the faster, more efficient > SQLite 3 driver. As a result, the > SQLite 2 driver is not as feature-rich > as the SQLite 3 driver. From <http://php.net/manual/en/ref.pdo-sqlite.php>
Go to your `php.ini` file and search for "sqlite". These are probably commented: ``` extension=php_pdo_sqlite.dll extension=php_sqlite.dll ``` Uncomment them, and restart Apache.
How to enable the PDO driver for sqlite3 in php?
[ "", "php", "sqlite", "pdo", "xampp", "" ]
How can I easily delete duplicates in a linked list in java?
I don't know if your requirements is to use a linked list but if not, use a Set instead of a List (you tagged the question as 'best-practices')
Use a [LinkedHashSet](http://java.sun.com/javase/6/docs/api/index.html?java/util/LinkedHashSet.html) instead, and then you won't have duplicates in the first place.
How can I easily delete duplicates in a linked list in java?
[ "", "java", "linked-list", "" ]
This is a bank simulation that takes into account 20 different serving lines with a single queue, customers arrive following an exponential rate and they are served during a time that follows a normal probability distribution with mean 40 and standard deviation 20. Things were working just fine till I decided to exclude the negative values given by the normal distribution using this method: ``` def getNormal(self): normal = normalvariate(40,20) if (normal>=1): return normal else: getNormal(self) ``` Am I screwing up the recursive call? I don't get why it wouldn't work. I have changed the getNormal() method to: ``` def getNormal(self): normal = normalvariate(40,20) while (normal <=1): normal = normalvariate (40,20) return normal ``` But I'm curious on why the previous recursive statement gets busted. This is the complete source code, in case you're interested. ``` """ bank21: One counter with impatient customers """ from SimPy.SimulationTrace import * from random import * ## Model components ------------------------ class Source(Process): """ Source generates customers randomly """ def generate(self,number): for i in range(number): c = Customer(name = "Customer%02d"%(i,)) activate(c,c.visit(tiempoDeUso=15.0)) validateTime=now() if validateTime<=600: interval = getLambda(self) t = expovariate(interval) yield hold,self,t #esta es la rata de generación else: detenerGeneracion=999 yield hold,self,detenerGeneracion class Customer(Process): """ Customer arrives, is served and leaves """ def visit(self,tiempoDeUso=0): arrive = now() # arrival time print "%8.3f %s: Here I am "%(now(),self.name) yield (request,self,counter),(hold,self,maxWaitTime) wait = now()-arrive # waiting time if self.acquired(counter): print "%8.3f %s: Waited %6.3f"%(now(),self.name,wait) tiempoDeUso=getNormal(self) yield hold,self,tiempoDeUso yield release,self,counter print "%8.3f %s: Completed"%(now(),self.name) else: print "%8.3f %s: Waited %6.3f. I am off"%(now(),self.name,wait) ## Experiment data ------------------------- maxTime = 60*10.5 # minutes maxWaitTime = 12.0 # minutes. maximum time to wait ## Model ---------------------------------- def model(): global counter #seed(98989) counter = Resource(name="Las maquinas",capacity=20) initialize() source = Source('Source') firstArrival= expovariate(20.0/60.0) #chequear el expovariate activate(source, source.generate(number=99999),at=firstArrival) simulate(until=maxTime) def getNormal(self): normal = normalvariate(40,20) if (normal>=1): return normal else: getNormal(self) def getLambda (self): actualTime=now() if (actualTime <=60): return 20.0/60.0 if (actualTime>60)and (actualTime<=120): return 25.0/60.0 if (actualTime>120)and (actualTime<=180): return 40.0/60.0 if (actualTime>180)and (actualTime<=240): return 30.0/60.0 if (actualTime>240)and (actualTime<=300): return 35.0/60.0 if (actualTime>300)and (actualTime<=360): return 42.0/60.0 if (actualTime>360)and (actualTime<=420): return 50.0/60.0 if (actualTime>420)and (actualTime<=480): return 55.0/60.0 if (actualTime>480)and (actualTime<=540): return 45.0/60.0 if (actualTime>540)and (actualTime<=600): return 10.0/60.0 ## Experiment ---------------------------------- model() ```
I think you want ``` return getnormal(self) ``` instead of ``` getnormal(self) ``` If the function exits without hitting a return statement, then it returns the special value None, which is a NoneType object - that's why Python complains about a 'NoneType.' The abs() function wants a number, and it doesn't know what to do with a None. Also, you could avoid recursion (and the cost of creating a new stack frame) by using ``` def getNormal(self): normal = 0 while normal < 1: normal = normalvariate(40,20) return normal ```
You need to have: ``` return getNormal(self) ``` instead of ``` getNormal(self) ``` Really though, there's no need for recursion: ``` def getNormal(self): normal = 0 while normal < 1: normal = normalvariate(40,20) return normal ```
Why is this recursive statement wrong?
[ "", "python", "recursion", "simpy", "" ]
When programming a CPU intensive or GPU intensive application on the iPhone or other portable hardware, you have to make wise algorithmic decisions to make your code fast. But even great algorithm choices can be slow if the language you're using performs more poorly than another. Is there any hard data comparing Objective-C to C++, specifically on the iPhone but maybe just on the Mac desktop, for performance of various similar language aspects? I am very familiar with [this article comparing C and Objective-C](https://stackoverflow.com/questions/826281/better-performance-with-libxml2-or-nsxmlparser-on-the-iphone), but this is a larger question of comparing two object oriented languages to each other. For example, is a C++ vtable lookup really faster than an Obj-C message? How much faster? Threading, polymorphism, sorting, etc. Before I go on a quest to build a project with duplicate object models and various test code, I want to know if anybody has already done this and what the results where. This type of testing and comparison is a project in and of itself and can take a considerable amount of time. Maybe this isn't one project, but two and only the outputs can be compared. I'm looking for **hard data**, not evangelism. Like many of you I love and hate both languages for various reasons. Furthermore, if there is someone out there actively pursuing this same thing I'd be interesting in pitching in some code to see the end results, and I'm sure others would help out too. My guess is that they both have strengths and weaknesses, my goal is to find out precisely what they are so that they can be avoided/exploited in real-world scenarios.
Mike Ash has some hard numbers for performance of various Objective-C method calls versus C and C++ in his post ["Performance Comparisons of Common Operations"](http://www.mikeash.com/?page=pyblog/performance-comparisons-of-common-operations.html). Also, [this post](http://savoysoftware.com/blog/?p=114) by Savoy Software is an interesting read when it comes to tuning the performance of an iPhone application by using Objective-C++. I tend to prefer the clean, descriptive syntax of Objective-C over Objective-C++, and have not found the language itself to be the source of my performance bottlenecks. I even tend to do things that I know sacrifice a little bit of performance if they make my code much more maintainable.
Yes, well written C++ is considerably faster. If you're writing performance critical programs and your C++ is not as fast as C (or within a few percent), something's wrong. If your ObjC implementation is as fast as C, then something's *usually* wrong -- i.e. the program is likely a bad example of ObjC OOD because it probably uses some 'dirty' tricks to step below the abstraction layer it is operating within, such as direct ivar accesses. The Mike Ash 'comparison' is very misleading -- I would never recommend the approach to compare execution times of programs you have written, or recommend it to compare C vs C++ vs ObjC. The results presented are provided from a test with compiler optimizations *disabled*. A program compiled with optimizations disabled is rarely relevant when you are measuring execution times. To view it as a benchmark which compares C++ against Objective-C is flawed. The test also compares individual features, rather than entire, real world optimized implementations -- individual features are combined in very different ways with both languages. This is far from a realistic performance benchmark for optimized implementations. Examples: With optimizations *enabled*, `IMP` cache is as slow as virtual function calls. Static dispatch (as opposed to dynamic dispatch, e.g. using `virtual`) and calls to known C++ types (where dynamic dispatch may be bypassed) may be optimized aggressively. This process is called devirtualization, and when it is used, a member function which is declared `virtual` may even be `inline`d. In the case of the Mike Ash test where many calls are made to member functions which have been declared `virtual` and have empty bodies: these calls are optimized away *entirely* when the type is known because the compiler sees the implementation and is able to determine dynamic dispatch is unnecessary. The compiler can also eliminate calls to `malloc` in optimized builds (favoring stack storage). So, enabling compiler optimizations in any of C, C++, or Objective-C can produce dramatic differences in execution times. That's not to say the presented results are entirely useless. You could get some useful information about external APIs if you want to determine if there are measurable differences between the times they spend in `pthread_create` or `+[NSObject alloc]` on one platform or architecture versus another. Of course, these two examples will be using optimized implementations in your test (unless you happen to be developing them). But for comparing one language to another in programs you compile… the presented results are useless with optimizations disabled. **Object Creation** Consider also object creation in ObjC - every object is allocated dynamically (e.g. on the heap). With C++, objects may be created on the stack (e.g. approximately as fast as creating a C struct and calling a simple function in many cases), on the heap, or as elements of abstract data types. Each time you allocate and free (e.g. via malloc/free), you may introduce a lock. When you create a C struct or C++ object on the stack, no lock is required (although interior members may use heap allocations) and it often costs just a few instructions or a few instructions plus a function call. As well, ObjC objects are reference counted instances. The actual need for an object to be a `std::shared_ptr` in performance critical C++ is very rare. It's not necessary or desirable in C++ to make every instance a shared, reference counted instance. You have much more control over ownership and lifetime with C++. **Arrays and Collections** Arrays and many collections in C and C++ also use strongly typed containers and contiguous memory. Since the address of the next element's members are often known, the optimizer can do much more, and you have great cache and memory locality. With ObjC, that's far from reality for standard objects (e.g. `NSObject`). **Dispatch** Regarding methods, many C++ implementations use few virtual/dynamic calls, particularly in highly optimized programs. These are static method calls and fodder for the optimizers. With ObjC methods, each method call (objc message send) is dynamic, and is consequently a firewall for the optimizer. Ultimately, that results in many restrictions or inconveniences regarding what you can and cannot do to keep performance at a minimum when writing performance critical ObjC. This may result in larger methods, IMP caching, frequent use of C. Some realtime applications cannot use **any** ObjC messaging in their render paths. None -- audio rendering is a good example of this. ObjC dispatch is simply not designed for realtime purposes; Allocations and locks may happen behind the scenes when messaging objects, making the complexity/time of objc messaging unpredictable enough that the audio rendering may miss its deadline. **Other Features** C++ also provides generics/template implementations for many of its libraries. These optimize very well. They are typesafe, and a lot of inlining and optimizations may be made with templates (consider it polymorphism, optimization, and specialization which takes place at compilation). C++ adds several features which just are not available or comparable in strict ObjC. Trying to directly compare langs, objects, and libraries which are very different is not so useful -- it's a very small subset of actual realizations. It's better to expand the question to a library/framework or real program, considering many aspects of design and implementation. **Other Points** C and C++ symbols can be more easily removed and optimized away in various stages of the build (stripping, dead code elimination, inlining and early inlining, as well as Link Time Optimization). The benefits of this include reduced binary sizes, reduced launch/load times, reduced memory consumption, etc.. For a single app, that may not be such a big deal; but if you reuse a lot of code, and you should, then your shared libraries could add a lot of unnecessary weight to the program, if implemented ObjC -- unless you are prepared to jump through some flaming hoops. So scalability and reuse are also factors in medium/large projects, and groups where reuse is high. **Included Libraries** ObjC library implementors also optimize for the environment, so its library implementors can make use of some language and environment features to offer optimized implementations. Although there are some pretty significant restrictions when writing an optimized program in pure ObjC, some highly optimized implementations exist in Cocoa. This is one of Cocoa's strong points, although the C++ standard library (what some people call the STL) is no slouch either. Cocoa operates at a much higher level of abstraction than C++ -- if you don't know well what you're doing (or should be doing), *operating closer to the metal can really cost you*. Falling back on to a good library implementation if you are not an expert in some domain is a good thing, unless you are really prepared to learn. As well, Cocoa's environments are limited; you can find implementations/optimizations which make better use of the OS. If you're writing optimized programs and have experience doing so in both C++ and ObjC, *clean* C++ implementations will often be twice as fast or faster than *clean* ObjC (yes, you can compare against Cocoa). If you know how to optimize, you can often do better than higher level, general purpose abstractions. Although, some optimized C++ implementations will be as fast as or slower than Cocoa's (e.g. my initial attempt at file I/O was slower than Cocoa's -- primarily because the C++ implementation initializes its memory). A lot of it comes down to the language features you are familiar with. I use both langs, they both have different strengths and models/patterns. They complement each other quite well, and there are great libraries for both. If you're implementing a complex, performance critical program, correct use of C++'s features and libraries will give you much more control and provide significant advantages for optimization, such that in the right hands, "several times faster" is a good default expectation (don't expect to win every time, or without some work, however). Remember, it takes years to understand C++ well enough to really reach that point. I keep the majority of my performance critical paths as C++, but also recognize that ObjC is also a very good solution for some problems, and that there are some very good libraries available.
Will my iPhone app take a performance hit if I use Objective-C for low level code?
[ "", "c++", "iphone", "objective-c", "performance", "optimization", "" ]
What is the biggest software development team that uses Python? I am wondering how well the dynamic type system scales to large development teams. It's pretty clear that at Google they have C++ and Java codebases with thousands of developers; their use of Python is much smaller. Are there some huge companies that develop primarily in Python?
[Youtube](http://www.youtube.com) is probably the biggest user after Google (and subsequently bought by them). [Reddit](http://www.reddit.com), a digg-like website, is written in Python. [Eve](http://www.eveonline.com/faq/faq_07.asp), an MMO with a good chunk written in Python is pretty impressive as well. <https://en.wikipedia.org/wiki/Python_(programming_language)#Uses> <https://en.wikipedia.org/wiki/List_of_Python_software>
Among many other Python-centered companies, beyond the ones already mentioned by Unknown, I'd mention big pharma firms such as Astra-Zeneca, film studios such as Lucasfilm, and research places such as NASA, Caltech, Lawrence Livermore NRL. Among the sponsors of Pycon Italia Tre (next week in Firenze, IT -- see www.pycon.it) are Qt/Trolltech (a wholly owned subsidiary of Nokia), Google of course, Statpro, ActiveState, Wingware -- besides, of course, several Italian companies. Among the sponsors of Pycon US in Chicago in March were (of course) Google, as well as Sun Microsystems, Microsoft, Slide.com, Walt Disney Animation Studios, Oracle, Canonical, VMWare -- these are all companies who thought it worthwhile to spend money in order to have visibility to experienced Pythonistas, so presumably ones making significant large-scale use of Python (and in most cases trying to hire experienced Python developers in particular).
Biggest python projects
[ "", "python", "" ]
How can I check if a `DataGridView` contains column "x" and column "x" is visible? All I have so far is below. ``` if (Dgv.Columns.Contains("Address") & .... ``` Thanks
The straightforward method: ``` if (dgv.Columns.Contains("Address") && dgv.Columns["Address"].Visible) { // do stuff } ```
Firstly verify if the column exists and then you verify its visibility. Calling the column's property for a column that does not exist will crash. ``` if (dgv.Columns.Contains("Address") { if ( dgv.Columns["Address"].Visible ) { } } ```
How can I check if a DataGridView contains column "x" and column "x" is visible?
[ "", "c#", "winforms", "datagridview", "" ]
I have an XmlTextWriter writing to a file and an XmlWriter using that text writer. This text writer is set to output tab-indented XML: ``` XmlTextWriter xtw = new XmlTextWriter("foo.xml", Encoding.UTF8); xtw.Formatting = Formatting.Indented; xtw.IndentChar = '\t'; xtw.Indentation = 1; XmlWriter xw = XmlWriter.Create(xtw); ``` --- Changed per Jeff's MSDN link: ``` XmlWriterSettings set = new XmlWriterSettings(); set.Indent = true; set.IndentChars = "\t"; set.Encoding = Encoding.UTF8; xw = XmlWriter.Create(f, set); ``` This does not change the end result. --- Now I'm an arbitrary depth in my XmlWriter and I'm getting a string of XML from elsewhere (that I cannot control) that is a single-line, non-indented XML. If I call xw.WriteRaw() then that string is injected verbatim and does not follow my indentation I want. ``` ... string xml = ExternalMethod(); xw.WriteRaw(xml); ... ``` Essentially, I want a WriteRaw that will parse the XML string and go through all the WriteStartElement, etc. so that it gets reformatted per the XmlTextWriter's settings. My preference is a way to do this with the setup I already have and to do this without having to reload the final XML just to reformat it. I'd also prefer not to parse the XML string with the likes of XmlReader and then mimic what it finds into my XmlWriter (very very manual process). At the end of this I'd rather have a simple solution than one that follows my preferences. (Best solution, naturally, would be simple and follows my preferences.)
How about using a XmlReader to read the xml as xml nodes? ``` string xml = ExternalMethod(); XmlReader reader = XmlReader.Create(new StringReader(xml)); xw.WriteNode(reader, true); ```
You shouldn't use [`XmlTextWriter`](http://msdn.microsoft.com/en-us/library/system.xml.xmltextwriter.aspx), as indicated in MSDN where it states: > In the .NET Framework version 2.0 > release, the recommended practice is > to create XmlWriter instances using > the XmlWriter.Create method and the > XmlWriterSettings class. This allows > you to take full advantage of all the > new features introduced in this > release. For more information, see > Creating XML Writers. Instead, you should use [XmlWriter.Create](http://msdn.microsoft.com/en-us/library/system.xml.xmlwriter.create.aspx) to get your writer. You can then use the [`XmlWriterSettings`](http://msdn.microsoft.com/en-us/library/system.xml.xmlwritersettings.aspx) class to specify things like indentation. ``` XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; settings.IndentChars = "\t"; ``` ### Update I think you can just use WriteNode. You take your xml string and load it into an XDocument or XmlReader and then use the node from that to write it into your XmlWriter.
XML indenting when injecting an XML string into an XmlWriter
[ "", "c#", ".net", "xml", "" ]
I have the following table of TIME datatypes clarification: I am representing hours/mins/seconds of videos and want to figure out how long the videos will be. ``` runtime ---------------- 01:27:19.0000000 01:26:09.0000000 01:00:56.0000000 01:09:59.0000000 01:25:43.0000000 01:16:01.0000000 01:27:12.0000000 01:22:00.0000000 01:17:47.0000000 01:31:07.0000000 01:36:23.0000000 01:13:29.0000000 01:20:12.0000000 01:03:24.0000000 00:58:42.0000000 ``` I want to get the SUM of all of these times.
I haven't used 2008 much yet and I don't have an instance handy where I am to check this, but something like this might work: ``` SELECT DATEADD(ms, SUM(DATEDIFF(ms, '00:00:00.000', my_time)), '00:00:00.000') FROM dbo.My_Table ``` As le dorfier points out, adding times is a bit meaningless, because they are supposed to represent a time of day. I'm going under the assumption that you are using them to indicate hours/minutes/seconds. Oh, and I have no idea what will happen with the above if it goes over 24 hours.
The best way I can think of is to parse the time spans into hour, minute, second and millisecond components, convert it all into milliseconds (by adding and multiplying), then adding them and using modulos and subtraction to turn it back into a timespan. For example ``` create function dbo.GetMilliseconds (@timespan varchar (16)) returns int as begin declare @ms int declare @seconds int declare @min int declare @hour int set @ms = cast(substring(@timespan, 10, 7) as int) set @seconds = cast(substring(@timespan, 7, 2) as int) set @min = cast(substring(@timespan, 4,2) as int) set @hour = cast(substring(@timespan, 1, 2) as int) return @ms + (@seconds * 1000) + (@min * 60000) + (@hour * 3600000) end go create function dbo.ParseMilliseconds (@timespan int) returns varchar (16) as begin declare @hour int declare @min int declare @seconds int declare @ms int declare @leftover int set @hour = @timespan / 3600000 /* this will round down */ set @leftover = @timespan % 3600000 set @min = @leftover / 60000 set @leftover = @leftover % 60000 set @seconds = @leftover / 1000 set @ms = @leftover % 1000 return 'You''ll have to the string conversion yourself' end go ``` And then `SELECT dbo.ParseMilliseconds(sum(dbo.GetMilliseconds(timespan))) as added_timespan` I haven't tested all of this, and there may be simpler ways, but I know this will work.
Get the SUM of TIME datatypes (MSSQL08) from a table
[ "", "sql", "sql-server", "t-sql", "sql-server-2008", "" ]
If I have an ajax call off fetching (with a callback) and then some other code running in the meantime. How can I have a third function that will be called when both of the first 2 are done. I'm sure it is easy with polling (setTimeout and then check some variables) but I'd rather a callback. Is it possible?
You could just give the same callback to both your AJAX call and your other code running in the meantime, use a variable to track their combined progress, then link them to a callback like below: ``` // Each time you start a call, increment this by one var counter = 0; var callback = function() { counter--; if (counter == 0) { // Execute code you wanted to do once both threads are finished. } } ```
Daniel's solution is the proper one. I took it and added some extra code so you don't have to think too much ;) ``` function createNotifier() { var counter = 2; return function() { if (--counter == 0) { // do stuff } }; } var notify = createNotifier(); var later = function() { var done = false; // do stuff and set done to true if you're done if (done) { notify(); } }; function doAjaxCall(notify) { var ajaxCallback = function() { // Respond to the AJAX callback here // Notify that the Ajax callback is done notify(); }; // Here you perform the AJAX call action } setInterval(later, 200); doAjaxCall(notify); ```
Join 2 'threads' in javascript
[ "", "javascript", "jquery", "ajax", "multithreading", "join", "" ]
hi im new to c# and was trying to code but getting error can anybody help me with this what am i doing wrong? ``` using System; using System.Collections.Generic; using System.Text; namespace hodder { class Program { public static void Main() { isHodder(3); } static int isHodder(int n) { int k = n; for (int i = 2; i <= n / 2;i++ ) { if ((n % 1) == 0) { return 0; } else { for (int j = 2; j <= k;j++ ) { if (n == (2^ j) - 1) { return 1; } else { return 0; } k=(2^j)-1; } } } } } } ``` im getting error on " static int isHodder(int n) " 'hodder.Program.isHodder(int)': not all code paths return a value and "Unreachable code detected " on "k=(2^j)-1"
The first error, "not all code paths return a value" means there is a path that the code could follow where no value would be returned (ie: calling isHodder(1)). You need to return some value outside of the for loop. Additionally, since you have an if/else block inside the second for loop the line ``` k=(2^j)-1; ``` Will never be executed. ``` static int isHodder(int n) { int k = n; for (int i = 2; i <= n / 2; i++) { if ((n % 1) == 0) { return 0; } else { for (int j = 2; j <= k; j++) { if (n == (2 ^ j) - 1) { return 1; } else { return 0; } k = (2 ^ j) - 1; } } } return 0; } ```
This line is highly suspect: ``` if ((n % 1) == 0) ```
Why am I getting this error: not all code paths return a value?
[ "", "c#", ".net", "visual-studio-2005", "console-application", "" ]
I have an application where I am taking a bitmap and compressing it using a GZipStream and sending it over a socket, all in memory. I have tracked down the dirty scumbag memory leak to the following line: ``` frame.Save(inStream, jpegCodec, parameters); ``` Browsing around the good ol' information superhighway I have found numerous topics about the Image class leaking memory in the save method on various codecs. Problem is there aren't really any fixes out there that I could find. So my questions are as follows: 1. What causes this 2. How can I fix this Here is my full Write() method in my FrameStream class where the leak is located. ``` /// <summary> /// Writes a frame to the stream /// </summary> /// <param name="frame">The frame to write</param> public void Write(Bitmap frame) { using (EncoderParameter qualityParameter = new EncoderParameter(Encoder.Quality, 50L)) { using (EncoderParameters parameters = new EncoderParameters(1)) { parameters.Param[0] = qualityParameter; ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); ImageCodecInfo jpegCodec = null; foreach (ImageCodecInfo codec in codecs) { if (codec.MimeType == "image/jpeg") { jpegCodec = codec; break; } } using (MemoryStream inStream = new MemoryStream()) { frame.Save(inStream, jpegCodec, parameters); // HUUUGE Memory Leak Byte[] buffer = new Byte[inStream.Length]; inStream.Read(buffer, 0, buffer.Length); using (MemoryStream outStream = new MemoryStream()) { using (GZipStream gzipStream = new GZipStream(outStream, CompressionMode.Compress)) { gzipStream.Write(buffer, 0, buffer.Length); } Byte[] frameData = outStream.ToArray(); Byte[] packet = new Byte[15 + frameData.Length]; Byte[] frameLength = BitConverter.GetBytes(frameData.Length); Array.Copy(frameLength, 0, packet, 0, frameLength.Length); Array.Copy(frameData, 0, packet, 15, frameData.Length); m_Socket.Send(packet); } } } } } ```
I suggest running your code under CLR Profiler to locate the source of the leak. If it's a managed object of any type (even an unmanaged resource), as long as the bug isn't due to a managed type leaking an unmanaged handle, you'll be able to see where the leak is. If it's in framework code, you can probably work around it using reflection and P/Invoke. For example, the `Icon` type leaks Win32 `HICON`s in some circumstances. The workaround for this is to manually dispose the `HICON` by PInvoking the `DeleteObject` function, using the handle exposed by the `Icon`.
Okay, after trying everyones ideas and thoughts and numerous other methods. I finally tried the simple: ``` using (frame) { frame.Save(outStream, jpegCodec, parameters); } ``` And well, this worked and the memory leak is fixed.. I tried forcefully invoking the garbage collector, disposing the bitmap manually, using P/Invoke DeleteObject, nothing worked, but using a using statement did. So this makes me wonder what happens underthehood on a using statement that I'm missing out on....
Bitmap.Save, Huge Memory Leak
[ "", "c#", "memory-leaks", "bitmap", "" ]
I'm partial to using member initializer lists for my constructors, but I've long since forgotten the reasons behind this. Do you use member initializer lists in your constructors? If so, why? If not, why not?
For [trivial type](https://stackoverflow.com/q/4178175/5740428) data members, it makes no difference, it's just a matter of style. For class members which are classes, then it avoids an unnecessary call to a default constructor. Consider: ``` class A { public: A() { x = 0; } A(int x_) { x = x_; } int x; }; class B { public: B() { a.x = 3; } private: A a; }; ``` In this case, the constructor for `B` will call the default constructor for `A`, and then initialize `a.x` to `3`. A better way would be for `B`'s constructor to directly call `A`'s constructor in the initializer list: ``` B() : a(3) {} ``` This would only call `A`'s `A(int)` constructor and not its default constructor. In this example, the difference is negligible, but imagine if you will that `A`'s default constructor did more, such as allocating memory or opening files. You wouldn't want to do that unnecessarily. Furthermore, if a class doesn't have a default constructor, or you have a `const` or reference data member, you *must* use an initializer list: ``` class A { public: A(int x_) { x = x_; } int x; }; class B { public: // 'a' and 'y' MUST be initialized in an initializer list; // it is an error not to do so. B() : a(3), y(2) {} private: A a; const int y; }; ```
Apart from the performance reasons mentioned above, if your class stores references to objects passed as constructor parameters or your class has const variables then you don't have any choice except using initializer lists.
Why should I prefer to use member initializer lists?
[ "", "c++", "oop", "constructor", "initialization", "object-construction", "" ]
I already have code which lazy loads scripts on request. My issue now is waiting to execute certain code until the object becomes available. I can't use a setTimeout() because it does not block execution. So what is a good way to 'wait' for a load, without locking the browser? Again, can't use raw setTimeout().
Assuming you control the contents of your script, you can put some code to execute at the bottom of your lazy loaded script to indicate to the main page that the script has loaded. For example, in your page you can do something like this: ``` var loadingScripts = 0; var loadScript = function() { // Do what you need to do to load the script... loadingScripts++; } var loadedScript = function() { loadingScripts--; if (loadingScripts == 0) { // Kick off execution of code that requires the lazy loaded scripts. } } ``` Then in your script, you'd add this code to the bottom: ``` loadedScript(); ``` You can spice this example up with an array instead of an integer (to keep track of which specific scripts have loaded). You could also use an object instead to associate particular function calls with the completion of particular scripts. I kept my example simple, but ask if you want me to show how to do extend the code. --- Here is how you can use a callback to continue execution of specific code upon loading of a script (again, assuming you control the scripts themselves). ``` var scriptCallbacks = {} var loadScript = function(scriptname, callback) { // Do what you need to load scriptname scriptCallbacks[scriptname] = callback; } var loadedScript = function(scriptname) { (scriptCallbacks[scriptname])(); } ``` Then when you want to load a script, you do something like this... ``` var callback = function() { // Write exactly what you want executed once your script is loaded } loadScript("MyScript.js", callback); ``` And again, in your lazy loaded script, just add this code to the bottom to inform your callback to fire: ``` loadedScript("MyScript.js"); ```
I'd actually do it differently than Daniel mentioned. All elements fire a load event when they have loaded, and a Javascript file is loaded after it has evaluated the content. So you can set an event handler to continue execution after their available: ``` var loadScript = function(fileName, callback) { var head = document.getElementsByTagName('head')[0]; var script = document.createElement('script'); script.type = 'text/javascript'; script.src = fileName; script.onload = callback; script.onreadystatechange = function() { if(this.readyState == 'complete') { callback(); } }; head.appendChild(script); }; ``` And an example usage: ``` var bar = function() { Foo.baz(); }; if(!window.Foo) { loadScript('Foo.js',bar); } else { bar(); } ```
Waiting on Lazy Loaded objects without lockup?
[ "", "javascript", "lazy-loading", "" ]
Hey all. Is there a way to copy only a portion of a single (or better yet, a two) dimensional list of strings into a new temporary list of strings?
Even though LINQ does make this easy and more general than just lists (using `Skip` and `Take`), `List<T>` has the [`GetRange`](http://msdn.microsoft.com/en-us/library/21k0e39c.aspx) method which makes it a breeze: ``` List<string> newList = oldList.GetRange(index, count); ``` (Where `index` is the index of the first element to copy, and `count` is how many items to copy.) When you say "two dimensional list of strings" - do you mean an array? If so, do you mean a jagged array (`string[][]`) or a rectangular array (`string[,]`)?
I'm not sure I get the question, but I would look at the **Array.Copy** function (**if by lists of strings you're referring to arrays**) Here is an example using C# in the .NET 2.0 Framework: ``` String[] listOfStrings = new String[7] {"abc","def","ghi","jkl","mno","pqr","stu"}; String[] newListOfStrings = new String[3]; // copy the three strings starting with "ghi" Array.Copy(listOfStrings, 2, newListOfStrings, 0, 3); // newListOfStrings will now contains {"ghi","jkl","mno"} ```
Copying a portion of a list to a new list
[ "", "c#", "list", "string", "" ]
So I'm using WCF, and want to document my interface(s) and services to give to another company for an internal app. What's the best way to document those interfaces? I'd prefer having the documentation inline with the code, and then have something prettify to output HTML, but am not sure if there's a recommended way to do it.
Do use XML docs for that. There are a lot of smart meta-tags that will allow you to put code samples in them, references between operations, thrown exceptions etc. Then you can use Sandcastle (+ some GUI you can find on Codeplex) to generate either chm, or html documentation.
We use WCFExtras (<http://www.codeplex.com/WCFExtras>) for that. Among other features it allows live exporting of your code xml comments into the generated WSDL, for example check how these xml comments: ``` /// <summary> /// Retrieve the tickets information for the specified order /// </summary> /// <param name="orderId">Order ID</param> /// <returns>Tickets data</returns> [OperationContract] TicketsDto GetTickets(int orderId); ``` get reflected in the WSDL of that interface: ``` <wsdl:operation name="GetTickets"> <wsdl:documentation> <summary> Retrieve the tickets information for the specified order </summary> <param name="orderId">Order ID</param> <returns>Tickets data</returns> </wsdl:documentation> <wsdl:input wsaw:Action="xxxx" message="tns:PartnerAPI_GetTickets_InputMessage"/> <wsdl:output wsaw:Action="xxxx" message="tns:PartnerAPI_GetTickets_OutputMessage"/> </wsdl:operation> ``` An excerpt from their docs: Adding WSDL Documentation from Source Code XML Comments This extension allows you to add WSDL documentation (annotaiton) directly from XML comments in your source file. These comments will be published as part of the WSDL and are available for WSDL tools that know how to take advantage of them (e.g. Apache Axis wsdl2java and others). Release 2.0 also includes a client side WSDL importer that will turn those WSDL comments to XML comments in the generated proxy code.
Best way to document WCF interface?
[ "", "c#", ".net", "xml", "wcf", "documentation", "" ]
What are some video tutorials/podcasts for Java and J2ME?
Stanford's YouTube channel has a very good introductory course on Java: *[Programming Methodology (CS106A)](http://www.youtube.com/view_play_list?p=84A56BC7F4A1F852)* Other video tutorials * <http://www.javaomatic.com/> * <http://www.javavideotutes.com/index/lessons/>
I generally found the podcasts [Parley's](http://www.parleys.com/display/PARLEYS/Home) or [InfoQ](http://www.infoq.com/) to be helpful. Anything from Joshua Bloch or Neal Gafter (even though they disagree about closures) to be of top notch quality.
Free video podcasts/tutorials for Java beginner
[ "", "java", "podcast", "" ]
I've developed an application that populates a treeview from hierachical data in a database. I've designed it to use lazy-loading so it only gets the child nodes when a node is expanded. My problem is that obviously I don't know if a node has children unless I make a call to the database and look. Currently I have implemented a dummy child node, so that the [+] icon appears for all nodes, I then remove this dummy node and get the real child nodes in the `BeforeExpand` event. This means I get a [+] icon for nodes that don't have child nodes, so the user clicks the expand icon and there's nothing show which looks a bit shoddy. What is the preffrred method for handling child nodes in a lazy-load treeview? If I make a call to the database to see if there are child nodes then I might as well just load the child nodes and forget about lazy loading right? One thought I had was to store a 'HasChildren' flag in the database, so I can selectively create my dummy child node only for the nodes that actually *do* have child nodes. Sorry for rambling on, I'm very interested to see what other people think...
When you make a call, check for children along with the node data: ``` SELECT tp.*, ( SELECT 1 FROM table tc WHERE tc.parent = tp.id LIMIT 1 ) AS has_children FROM table tp ``` You don't have to count, it may be long. Just check that at least one child exists.
change your initial query to return all the same data, but also a count of children. when the children count is not zero show the [+]. post your schema and query for help getting the count
How to only display a TreeView expand sign [+] if children exist
[ "", "sql", "database", "treeview", "lazy-loading", "" ]
I'm trying to get eclipse to work with MinGW. I've done the following: * Downloaded CDT for eclipse. * Installed MinGW. * Added C:\MinGW\bin to my path. Opening a command prompt (CMD) and typing g++ or alike works fine. * I run eclipse, create a "New C++ Project", and only get the option saying "other toolchains". There's a **MILLION** tutorials out there saying eclipse should identify MinGW on its own. It doesn't, and I don't know what to do. I've tried reinstalling everying in just about every order posible. Still no luck. I've also noted some tutorials say something about creating a "Managed C++ Project". I've no such option, all I get is "C++ Project" and "C Project" edit: I have eclipse ganymede, windows x86\_64, version 3.4.2 <http://download.eclipse.org/eclipse/downloads/drops/R-3.4.2-200902111700/index.php> Running the "Eclipse IDE for C/C++ developers" fails, since there's no x64 version for windows. The x86 version requires x86 JAVA installed as well, and installing two versions of java, gave nothing but trouble in the past.
The distinction between managed make projects and makefile project was removed in CDT 4.x, I think. Now there is only one type of project, but you can select different builders. CDT includes an internal builder which does not use makefiles and another one which does. First, save yourself the effort of "reinstalling in every order possible". That is also known as trial-and-error, and will only make you more frustrated. Apply the normal problem-solving skills you have as a programmer. Given that you have MinGW installed, what happens if you download "[Eclipse IDE for C/C++ developers](http://www.eclipse.org/downloads/download.php?file=/technology/epp/downloads/release/ganymede/SR2/eclipse-cpp-ganymede-SR2-win32.zip)", start eclipse.exe, and try to create a C++-project with a MinGW toolchain? EDIT: remember: the **key** in getting help with problems like these is to produce a **minimal** example which fails. Also, it would help if you provided URLs to the packages you installed (MinGW, Eclipse, etc.). EDIT: I just installed CDT using the Ganymede update site, downloaded and installed MinGW from [here](http://sourceforge.net/project/downloading.php?group_id=2435&filename=MinGW-5.1.4.exe&a=95543156), and restarted Eclipse, and everything worked fine. I know that doesn't help you, but it does prove that the toolchain detection isn't completely broken. Something is weird on your side.
The instructions for setting up MinGW in Ganymede are located [here](http://help.eclipse.org/ganymede/topic/org.eclipse.cdt.doc.user/concepts/cdt_c_before_you_begin.htm). > The following are instructions and > links on how to install the current > version of MinGW. Note that these > links may become inaccurate over time > as new versions of MinGW components > are introduced. Please check the MinGW > File Release section for the latest > versions. > > 1. Download and run the MinGW setup program, MinGW-5.1.3.exe. > 2. Select download and install the MinGW base tools and the g++ compiler. > You may select the Current or > Candidate version of these tools. You > may also install any of the other > available compilers as well. > > Do not install the MinGW Make feature as the MSYS version of make > from step 5 is a more complete > implementation of make. > 3. The MinGW setup program currently does not install the gdb > debugger. To install the debugger, > download the file from the following > location: gdb-6.6.tar.bz2 > 4. Extract the contents of the file gdb-6.6.tar.bz2 to the same location > where you installed MinGW. > 5. If you want to use Makefile projects, download and run the setup > program from the following location: > MSYS-1.0.10.exe. MSYS provides an > implementation of make and related > command line tools. This is not > required for other types of projects > with the MinGW toolchain, which use > CDT's internal build tools to perform > the build. Following this process resolved any problems I had.
Eclipse Ganymede and MinGW in Windows
[ "", "c++", "windows", "eclipse", "mingw", "" ]
Not sure if this belongs in community wiki... Can somebody give some general guidelines on how to successfully build an ASP.NET site that isn't dependent on JavaScript? My understanding is that I should build a functional site initially without JavaScript, and use it to enhance the user experience. That is easier said than done... how can I make sure my site works without JavaScript short of disabling JavaScript and trying it? Or is this something that comes with experience?
I've built working ASP.Net sites with little or no JavaScript, so it's definitely possible (just a royal pain.) The trick, and this sounds silly, is to use as few `<ASP:>` type tags as possible. Those all spawn various levels of JavaScript. Regular old-school HTML elements work just fine with no scripting. So, on the extreme end, you write, say, your form using all plain-vanilla HTML elements, and then you have that form submit point at another page that accepts the form submit and hands it off to your server-side scripting. To put it another way, pretend that all you get with ASP.NET is a snazzy server-side programming language and you're writing HTML in 1998. Now, having done this, I can tell you that what this ends up as is a classic ASP webpage with cleaner programming syntax. ;) Most of the features that make ASP.NET "better" than classic ASP hang on JavaScript, so writing a JavaScript-free ASP.NET system is an exercise in shooting oneself in the foot repeatedly. However, the one thing you should absolutely do is make sure the first page or two do work without JavaScript. Unlike 10 years ago you can safely assume that any browser hitting your page has JavaScript, and unlike about 8 years ago, your visitors probably don't have JavaScript turned off for speed reasons, *but* they very well might have something like the NoScript plugin for Firefox dialed all the way to 11. So, your first couple of pages need to work well enough to a) tell the new visitor that they need JavaScript, and b) still look and work good enough to make it look like adding your site to the white list is worth it. (In my experience, most people get the first one done, but in such as way as to totally drop the ball on the second. To put it another way - if your super fancy web 2.0 mega site starts looking like craigslist if noScript is fired up, I'm probably not going to bother letting you run scripts on my machine.)
Try ASP.NET MVC! sure most of the examples use JavaScript for the AJAX functionality, but it's easy to build a fully functioning site that doesn't use JavaScript. Since ASP.NET MVC doesn't use server controls with all their embedded JavaScript, it's a great way to build a site with very minimal and lightweight HTML, while still writting your data access and business logic in C#, VB.NET, or any other .NET language.
Tips for developing an ASP.NET application that doesn't depend on JavaScript
[ "", "asp.net", "javascript", "" ]
Why is it better to use '!=" than '<' in a vector loop? I just can't see the difference.
Because you're using iterators, and it'll make the loop look exactly the same as other containers, should you choose to switch to other container types, such as set, list, unordered\_set, etc. where < has no meaning.
I'll assume that you mean the use of `!=vector.end()` rather than `<vector.size()` as that was not clear from your question. One reason to prefer the end() version is that what you are really trying to do is to check whether you reached the end. The idiom for doing this sort of checks for arrays in C was to check the index compared to the size, but that is a "legacy" behavior. In was then spread in the world of Java (as <`array.length`) until such time that people realized that arrays are evil and that Java finally supports generics. In C++, however, there is no reason to use this idiom when you have a good collection class such as vector to work with. It's more readable, and more maintainable. For example, it makes it easier to switch to other collections if necessary, as you are still talking about the end.
Why is it better to use '!=" than '<' in a vector loop? (C++)
[ "", "c++", "vector", "loops", "" ]
how can i get elements uniquely from an array
Using LINQ can solve your problem easily: ``` class Program { static string[] ar = new[] { "a", "b", "c", "d", "a", "a", "f", "g", "d", "i", "j", "a","d", "c", "g" }; static void Main(string[] args) { var dist = (from a in ar select a).Distinct();// distinct; foreach (var v in dist) Console.Write(v); Console.ReadLine(); } } ``` It produces this output: ``` abcdfgij ```
``` using System.Linq; class Program { static void Main() { var array = new int[] { 1, 2, 2, 3 }; var distinctArray = array.Distinct().ToArray(); } } ```
how can i get elements uniquely from an array
[ "", "c#", "" ]
If I use `TextRenderer.DrawText()` using the `Graphics` object provided in the `OnPaintBackground` my text looks perfect. If I create my own `Bitmap` and use the `Graphics` object obtained from my `Bitmap` my text looks terrible. It looks like it is anti-aliasing the text using black, not the bitmap's background color. I can avoid this problem if I use `Graphics.DrawString()`, but this method has horrible kerning problems. What should I do? How can I get `TextRenderer.DrawText()` to anti-alias properly using the Bitmap's contents? **Looks terrible:** ``` Bitmap bmp = new Bitmap(100, 100, PixelFormat.Format32bppArgb); using (Graphics g = Graphics.FromImage(bmp)) { g.Clear(Color.Red); TextFormatFlags tf = TextFormatFlags.Left; TextRenderer.DrawText(g, @"C:\Development\Testing\blag", font, clip, Color.White, Color.Transparent, tf); } ``` **Looks good, but I want to render this onto a bitmap, NOT onto the control's surface:** ``` protected override void OnPaintBackground(PaintEventArgs e) { e.Graphics.Clear(Color.Red); TextFormatFlags tf = TextFormatFlags.Left; TextRenderer.DrawText(e.Graphics, @"C:\Development\Testing\blag", font, clip, Color.White, Color.Transparent, tf); } ``` What is the difference?
The answer is not to use `TextRenderer`. TextRenderer is a wrapper for the GDI (not GDI+) implementation of text rendering, which has lots of features, but doesn't interoperate well with in-memory DCs as you have discovered. Use `Graphics.DrawString` & `Graphics.MeasureString`, but remember to pass it StringFormat.GenericTypographic to get accurate size and positioning. The reason TextRenderer was introduced initially was that GDI+ didn't support all the complex scripts that GDI's Uniscribe engine did. Over time however GDI+ support for complex scripts has been expanded, and these days there aren't any good reasons left to use TextRenderer (it's not even the faster of the two anymore, in fact quite the opposite it appears). Really, though, unless you are running into serious, measurable performance issues just use `Graphics.DrawString`.
I believe the problem is that the clear type text rendering doesn't work if the background is transparent. A few possible solutions. Option 1. Fill the background of your bitmap with a color. If you do this (as Tim Robinson did above in his code example by using g.Clear(Color.Red)) clear type will do the right thing. But your bitmap won't be completely transparent which might not be acceptable. If you use Graphics.MeasureText, you can fill just the rectangle around your text, if you like. Option 2. Set TextRenderingHint = TextRenderingHintAntiAliasGridFit This appears to turn off clear type. The text will be rendered at a lower quality than clear type on a background, but much better than the mess clear type on no background creates. Option 3. Fill the text rectangle with white, draw the text and then find all the non-text pixels and put them back to transparent. ``` using (Bitmap bmp = new Bitmap(someWidth, someHeight)) { using (Graphics g = Graphics.FromImage(bmp)) { // figure out where our text will go Point textPoint = new Point(someX, someY); Size textSize = g.MeasureString(someText, someFont).ToSize(); Rectangle textRect = new Rectangle(textPoint, textSize); // fill that rect with white g.FillRectangle(Brushes.White, textRect); // draw the text g.DrawString(someText, someFont, Brushes.Black, textPoint); // set any pure white pixels back to transparent for (int x = textRect.Left; x <= textRect.Left + textRect.Width; x++) { for (int y = textRect.Top; y <= textRect.Top + textRect.Height; y++) { Color c = bmp.GetPixel(x, y); if (c.A == 255 && c.R == 255 && c.G == 255 && c.B == 255) { bmp.SetPixel(x, y, Color.Transparent); } } } } } ``` I know, it's a horrible hack, but it appears to work.
TextRenderer.DrawText in Bitmap vs OnPaintBackground
[ "", "c#", "textrenderer", "" ]
How should I get the number of characters in a string in C++?
If you're using a `std::string`, call [`length()`](http://en.cppreference.com/w/cpp/string/basic_string/size): ``` std::string str = "hello"; std::cout << str << ":" << str.length(); // Outputs "hello:5" ``` If you're using a c-string, call [`strlen()`](http://en.cppreference.com/w/cpp/string/byte/strlen). ``` const char *str = "hello"; std::cout << str << ":" << strlen(str); // Outputs "hello:5" ``` Or, if you happen to like using Pascal-style strings (or f\*\*\*\*\* strings as Joel Spolsky [likes to call them](http://www.joelonsoftware.com/articles/fog0000000319.html) when they have a trailing NULL), just dereference the first character. ``` const char *str = "\005hello"; std::cout << str + 1 << ":" << *str; // Outputs "hello:5" ```
# For Unicode Several answers here have addressed that `.length()` gives the wrong results with multibyte characters, but there are 11 answers and none of them have provided a solution. ## The case of Z͉̳̺ͥͬ̾a̴͕̲̒̒͌̋ͪl̨͎̰̘͉̟ͤ̀̈̚͜g͕͔̤͖̟̒͝ͅo̵̡̡̼͚̐ͯ̅ͪ̆ͣ̚ First of all, it's important to know what you mean by "length". For a motivating example, consider the string "Z͉̳̺ͥͬ̾a̴͕̲̒̒͌̋ͪl̨͎̰̘͉̟ͤ̀̈̚͜g͕͔̤͖̟̒͝ͅo̵̡̡̼͚̐ͯ̅ͪ̆ͣ̚" (note that some languages, notably Thai, actually use combining diacritical marks, so this isn't *just* useful for 15-year-old memes, but obviously that's the most important use case). Assume it is encoded in **UTF-8**. There are 3 ways we can talk about the length of this string: ### 95 bytes ``` 00000000: 5acd a5cd accc becd 89cc b3cc ba61 cc92 Z............a.. 00000010: cc92 cd8c cc8b cdaa ccb4 cd95 ccb2 6ccd ..............l. 00000020: a4cc 80cc 9acc 88cd 9ccc a8cd 8ecc b0cc ................ 00000030: 98cd 89cc 9f67 cc92 cd9d cd85 cd95 cd94 .....g.......... 00000040: cca4 cd96 cc9f 6fcc 90cd afcc 9acc 85cd ......o......... 00000050: aacc 86cd a3cc a1cc b5cc a1cc bccd 9a ............... ``` ### 50 codepoints ``` LATIN CAPITAL LETTER Z COMBINING LEFT ANGLE BELOW COMBINING DOUBLE LOW LINE COMBINING INVERTED BRIDGE BELOW COMBINING LATIN SMALL LETTER I COMBINING LATIN SMALL LETTER R COMBINING VERTICAL TILDE LATIN SMALL LETTER A COMBINING TILDE OVERLAY COMBINING RIGHT ARROWHEAD BELOW COMBINING LOW LINE COMBINING TURNED COMMA ABOVE COMBINING TURNED COMMA ABOVE COMBINING ALMOST EQUAL TO ABOVE COMBINING DOUBLE ACUTE ACCENT COMBINING LATIN SMALL LETTER H LATIN SMALL LETTER L COMBINING OGONEK COMBINING UPWARDS ARROW BELOW COMBINING TILDE BELOW COMBINING LEFT TACK BELOW COMBINING LEFT ANGLE BELOW COMBINING PLUS SIGN BELOW COMBINING LATIN SMALL LETTER E COMBINING GRAVE ACCENT COMBINING DIAERESIS COMBINING LEFT ANGLE ABOVE COMBINING DOUBLE BREVE BELOW LATIN SMALL LETTER G COMBINING RIGHT ARROWHEAD BELOW COMBINING LEFT ARROWHEAD BELOW COMBINING DIAERESIS BELOW COMBINING RIGHT ARROWHEAD AND UP ARROWHEAD BELOW COMBINING PLUS SIGN BELOW COMBINING TURNED COMMA ABOVE COMBINING DOUBLE BREVE COMBINING GREEK YPOGEGRAMMENI LATIN SMALL LETTER O COMBINING SHORT STROKE OVERLAY COMBINING PALATALIZED HOOK BELOW COMBINING PALATALIZED HOOK BELOW COMBINING SEAGULL BELOW COMBINING DOUBLE RING BELOW COMBINING CANDRABINDU COMBINING LATIN SMALL LETTER X COMBINING OVERLINE COMBINING LATIN SMALL LETTER H COMBINING BREVE COMBINING LATIN SMALL LETTER A COMBINING LEFT ANGLE ABOVE ``` ### 5 graphemes ``` Z with some s**t a with some s**t l with some s**t g with some s**t o with some s**t ``` ## Finding the lengths using [ICU](http://site.icu-project.org/) There are C++ classes for ICU, but they require converting to UTF-16. You can use the C types and macros directly to get some UTF-8 support: ``` #include <memory> #include <iostream> #include <unicode/utypes.h> #include <unicode/ubrk.h> #include <unicode/utext.h> // // C++ helpers so we can use RAII // // Note that ICU internally provides some C++ wrappers (such as BreakIterator), however these only seem to work // for UTF-16 strings, and require transforming UTF-8 to UTF-16 before use. // If you already have UTF-16 strings or can take the performance hit, you should probably use those instead of // the C functions. See: http://icu-project.org/apiref/icu4c/ // struct UTextDeleter { void operator()(UText* ptr) { utext_close(ptr); } }; struct UBreakIteratorDeleter { void operator()(UBreakIterator* ptr) { ubrk_close(ptr); } }; using PUText = std::unique_ptr<UText, UTextDeleter>; using PUBreakIterator = std::unique_ptr<UBreakIterator, UBreakIteratorDeleter>; void checkStatus(const UErrorCode status) { if(U_FAILURE(status)) { throw std::runtime_error(u_errorName(status)); } } size_t countGraphemes(UText* text) { // source for most of this: http://userguide.icu-project.org/strings/utext UErrorCode status = U_ZERO_ERROR; PUBreakIterator it(ubrk_open(UBRK_CHARACTER, "en_us", nullptr, 0, &status)); checkStatus(status); ubrk_setUText(it.get(), text, &status); checkStatus(status); size_t charCount = 0; while(ubrk_next(it.get()) != UBRK_DONE) { ++charCount; } return charCount; } size_t countCodepoints(UText* text) { size_t codepointCount = 0; while(UTEXT_NEXT32(text) != U_SENTINEL) { ++codepointCount; } // reset the index so we can use the structure again UTEXT_SETNATIVEINDEX(text, 0); return codepointCount; } void printStringInfo(const std::string& utf8) { UErrorCode status = U_ZERO_ERROR; PUText text(utext_openUTF8(nullptr, utf8.data(), utf8.length(), &status)); checkStatus(status); std::cout << "UTF-8 string (might look wrong if your console locale is different): " << utf8 << std::endl; std::cout << "Length (UTF-8 bytes): " << utf8.length() << std::endl; std::cout << "Length (UTF-8 codepoints): " << countCodepoints(text.get()) << std::endl; std::cout << "Length (graphemes): " << countGraphemes(text.get()) << std::endl; std::cout << std::endl; } void main(int argc, char** argv) { printStringInfo(u8"Hello, world!"); printStringInfo(u8"หวัดดีชาวโลก"); printStringInfo(u8"\xF0\x9F\x90\xBF"); printStringInfo(u8"Z͉̳̺ͥͬ̾a̴͕̲̒̒͌̋ͪl̨͎̰̘͉̟ͤ̀̈̚͜g͕͔̤͖̟̒͝ͅo̵̡̡̼͚̐ͯ̅ͪ̆ͣ̚"); } ``` This prints: ``` UTF-8 string (might look wrong if your console locale is different): Hello, world! Length (UTF-8 bytes): 13 Length (UTF-8 codepoints): 13 Length (graphemes): 13 UTF-8 string (might look wrong if your console locale is different): หวัดดีชาวโลก Length (UTF-8 bytes): 36 Length (UTF-8 codepoints): 12 Length (graphemes): 10 UTF-8 string (might look wrong if your console locale is different): Length (UTF-8 bytes): 4 Length (UTF-8 codepoints): 1 Length (graphemes): 1 UTF-8 string (might look wrong if your console locale is different): Z͉̳̺ͥͬ̾a̴͕̲̒̒͌̋ͪl̨͎̰̘͉̟ͤ̀̈̚͜g͕͔̤͖̟̒͝ͅo̵̡̡̼͚̐ͯ̅ͪ̆ͣ̚ Length (UTF-8 bytes): 95 Length (UTF-8 codepoints): 50 Length (graphemes): 5 ``` [Boost.Locale](https://www.boost.org/doc/libs/1_69_0/libs/locale/doc/html/index.html) wraps ICU, and might provide a nicer interface. However, it still requires conversion to/from UTF-16.
How to get the number of characters in a std::string?
[ "", "c++", "string", "stdstring", "string-length", "" ]
Here's the situation: I would like to iterate through a table with input controls, collect up the values and then submit them to an ASP.NET `PageMethod` to save the data to the database. I have the collection all figured out but am getting an error that the string can't be converted to a `Dictionary<string, object>`. So I end up with something like this being passed to a method with the below signature ``` [ { 'id': '383840923', 'name': 'fred', 'car':'honda' }, { 'id': '243', 'name': 'joe', 'car':'honda' }, { 'id': '4323423', 'name': 'paul', 'car':'honda' }, { 'id': '38384234230923', 'name': 'ted', 'car':'honda' }, ] public static bool SaveData(Dictionary<string, object>[] items) {...} ``` I know that I can pass whole class objects back and forth if properly declared and ASP.NET will handle the conversions for me, but I don't need the whole class being passed, only a couple of the properties. Edit: I'm using jQuery to do the post back to the server. What am I doing wrong here?
I figured out what the problem was. I was wrapping the array in quotes before sending it in as part of the `$.ajax` call so it was being treated as a string instead of an array. ``` $.ajax({ type: "POST", url: "<%= Response.ApplyAppPathModifier(Request.Path) %>/UpdateAcademicItems", dataType: "json", contentType: "application/json; charset=utf-8", data: "{'items': **'**" + $.toJSON(items) + "**'**}", success: function(data) { if(false != data.d) { alert('we did it'); } else { alert ('flop'); } }, error: function() { alert('Failed to save Program Items'); } }); ```
[ASP.NET AJAX will automatically deserialize that for you if you use a DTO](http://encosia.com/2009/04/07/using-complex-types-to-make-calling-services-less-complex/). Something like this on the server-side would match the JSON array you're sending in: ``` public class PeopleAndCarsDTO { public int id { get; set; } public string name { get; set; } public string car { get; set; } } public static bool SaveData(List<PeopleAndCarsDTO> items) {...} ```
Pass Array of JavaScript objects to PageMethod
[ "", "asp.net", "javascript", "pagemethods", "" ]
Is there any difference between these tow pieces of code & which approach is better. ``` try { using() { //Do stuff } } catch { //Handle exception } using() { try { //Do stuff } catch { //Handle exception } } ```
There are differences, but it namely boils down to the fact that a using block creates it own try and scope blocks. ``` try { using(IDisposable A = GetDisposable()) { //Do stuff } } catch { //Handle exception // You do NOT have access to A } using(IDisposable A = GetDisposable()) //exception here is uncaught { try { //Do stuff } catch { //Handle exception // You DO have access to A } } ```
There's a difference between these blocks. In the second case the exception won't be caught if it is thrown in the using() line (for example instantiating an IDisposable object and the constructor throws an exception). Which one is better will depend on your specific needs.
Catch exceptions within a using block vs outside the using block - which is better?
[ "", "c#", "c#-3.0", "" ]
The following code is generating an error on the variable `con2` saying `"non-static variable con2 cannot be referenced from a static context Error."` I Googled for a resolution and they are suggesting the variable isn't initalized yet to make the methods available. Am I initializing this incorrectly? I also tried changing things to public but that didn't help either. ``` import java.io.*; import java.net.*; import java.sql.*; import java.sql.CallableStatement; import java.sql.ResultSet; import java.sql.PreparedStatement; import net.sourceforge.jtds.jdbcx.JtdsDataSource; import net.sourceforge.jtds.jdbc.Driver; class testconnect { private java.sql.Connection con2 = null; private final String url2 = "jdbc:jtds:sqlserver://"; private final String serverName= "SQL01"; private final String portNumber = "2677"; private final String databaseName= "App"; private final String userName = "bob"; private final String password = "boob"; private final String selectMethod = "cursor"; private String getConnectionUrl2(){ System.out.println("initalizing jtds"); //String returnVal = url+serverName+":"+portNumber+";databaseName="+databaseName+";user="+userName+";password="+password+";instance="+instance+";"; String returnVal = url2+serverName+":"+portNumber+"/"+databaseName+";user="+userName+";password="+password; System.out.println("url2: " + returnVal); return returnVal; } public static void main (String[] args) { con2 = java.sql.DriverManager.getConnection(getConnectionUrl2()); } } //end class ```
No, actually, you must declare your con2 field static: ``` private static java.sql.Connection con2 = null; ``` Edit: Correction, that won't be enough actually, you will get the same problem because your getConnection2Url method is also not static. A better solution may be to instead do the following change: ``` public static void main (String[] args) { new testconnect().run(); } public void run() { con2 = java.sql.DriverManager.getConnection(getConnectionUrl2()); } ```
You probably want to add "static" to the declaration of con2. In Java, things (both variables and methods) can be properties of the class (which means they're shared by all objects of that type), or they can be properties of the object (a different one in each object of the same class). The keyword "static" is used to indicate that something is a property of the class. "Static" stuff exists all the time. The other stuff only exists after you've created an object, and even then each individual object has its own copy of the thing. And the flip side of this is key in this case: static stuff can't access non-static stuff, because it doesn't know which object to look in. If you pass it an object reference, it can do stuff like "thingie.con2", but simply saying "con2" is not allowed, because you haven't said which object's con2 is meant.
java : non-static variable cannot be referenced from a static context Error
[ "", "java", "jtds", "" ]
So I've been sharing some thoughts on the above topic title on my website about fast, unsafe pixel access. A gentlemen gave me a rough example of how he'd do it in C++, but that doesn't help me in C# unless I can interop it, and the interop is fast as well. I had found a class in the internet that was written using MSDN help, to unsafely access pixels. The class is exceptionally fast, but it's not fast enough. Here's the class: ``` using System; using System.Collections.Generic; using System.Text; using System.Drawing; using System.Drawing.Imaging; namespace DCOMProductions.Desktop.ScreenViewer { public unsafe class UnsafeBitmap { Bitmap bitmap; // three elements used for MakeGreyUnsafe int width; BitmapData bitmapData = null; Byte* pBase = null; public UnsafeBitmap(Bitmap bitmap) { this.bitmap = new Bitmap(bitmap); } public UnsafeBitmap(int width, int height) { this.bitmap = new Bitmap(width, height, PixelFormat.Format32bppArgb); } public void Dispose() { bitmap.Dispose(); } public Bitmap Bitmap { get { return (bitmap); } } private Point PixelSize { get { GraphicsUnit unit = GraphicsUnit.Pixel; RectangleF bounds = bitmap.GetBounds(ref unit); return new Point((int)bounds.Width, (int)bounds.Height); } } public void LockBitmap() { GraphicsUnit unit = GraphicsUnit.Pixel; RectangleF boundsF = bitmap.GetBounds(ref unit); Rectangle bounds = new Rectangle((int)boundsF.X, (int)boundsF.Y, (int)boundsF.Width, (int)boundsF.Height); // Figure out the number of bytes in a row // This is rounded up to be a multiple of 4 // bytes, since a scan line in an image must always be a multiple of 4 bytes // in length. width = (int)boundsF.Width * sizeof(Pixel); if (width % 4 != 0) { width = 4 * (width / 4 + 1); } bitmapData = bitmap.LockBits(bounds, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); pBase = (Byte*)bitmapData.Scan0.ToPointer(); } public Pixel GetPixel(int x, int y) { Pixel returnValue = *PixelAt(x, y); return returnValue; } public void SetPixel(int x, int y, Pixel colour) { Pixel* pixel = PixelAt(x, y); *pixel = colour; } public void UnlockBitmap() { bitmap.UnlockBits(bitmapData); bitmapData = null; pBase = null; } public Pixel* PixelAt(int x, int y) { return (Pixel*)(pBase + y * width + x * sizeof(Pixel)); } } ``` } Basically what I am doing is copying the entire screen and comparing each pixel to and old copy. On a 1680x1050 bitmap, this takes approximately 300 milliseconds using the following code. ``` private Bitmap GetInvalidFrame(Bitmap frame) { Stopwatch sp = new Stopwatch(); sp.Start(); if (m_FrameBackBuffer == null) { return frame; } Int32 pixelsToRead = frame.Width * frame.Height; Int32 x = 0, y = 0; UnsafeBitmap unsafeBitmap = new UnsafeBitmap(frame); UnsafeBitmap unsafeBuffBitmap = new UnsafeBitmap(m_FrameBackBuffer); UnsafeBitmap retVal = new UnsafeBitmap(frame.Width, frame.Height); unsafeBitmap.LockBitmap(); unsafeBuffBitmap.LockBitmap(); retVal.LockBitmap(); do { for (x = 0; x < frame.Width; x++) { Pixel newPixel = unsafeBitmap.GetPixel(x, y); Pixel oldPixel = unsafeBuffBitmap.GetPixel(x, y); if (newPixel.Alpha != oldPixel.Alpha || newPixel.Red != oldPixel.Red || newPixel.Green != oldPixel.Green || newPixel.Blue != oldPixel.Blue) { retVal.SetPixel(x, y, newPixel); } else { // Skip pixel } } y++; } while (y != frame.Height); unsafeBitmap.UnlockBitmap(); unsafeBuffBitmap.UnlockBitmap(); retVal.UnlockBitmap(); sp.Stop(); System.Diagnostics.Debug.WriteLine(sp.Elapsed.Milliseconds.ToString()); sp.Reset(); return retVal.Bitmap; } ``` Is there any possible method/means/approach that I could speed this up to about 30ms? I can copy the screen in about 30ms using Graphics.CopyFromScreen(), so that produces approximately 30 frames each second. However, a program only runs as fast as its slower counterpart, so the 300ms delay in GetInvalidFrame, slows this down to about 1 - 3 frames each second. This isn't good for a meeting software. Any advice, approaches, pointers in the right direction would be absolutely wonderful! Also, the code that is used to draw the bitmap on the client-side is below as well. To comment on Dmitriy's answer/comment: ``` #region RootWorkItem private ScreenClient m_RootWorkItem; /// <summary> /// Gets the RootWorkItem /// </summary> public ScreenClient RootWorkItem { get { if (m_RootWorkItem == null) { m_RootWorkItem = new ScreenClient(); m_RootWorkItem.FrameRead += new EventHandler<FrameEventArgs>(RootWorkItem_FrameRead); } return m_RootWorkItem; } } #endregion private void RootWorkItem_FrameRead(Object sender, FrameEventArgs e) { if (e.Frame != null) { if (uxSurface.Image != null) { Bitmap frame = (Bitmap)uxSurface.Image; Graphics g = Graphics.FromImage(frame); g.DrawImage(e.Frame, 0, 0); // Draw only updated pixels uxSurface.Image = frame; } else { uxSurface.Image = e.Frame; // Draw initial, full image } } else { uxSurface.Image = null; } } ```
Unsafe approach with usage of integers instead of Pixels and single loop: ``` private static Bitmap GetInvalidFrame(Bitmap oldFrame, Bitmap newFrame) { if (oldFrame.Size != newFrame.Size) { throw new ArgumentException(); } Bitmap result = new Bitmap(oldFrame.Width, oldFrame.Height, oldFrame.PixelFormat); Rectangle lockArea = new Rectangle(Point.Empty, oldFrame.Size); PixelFormat format = PixelFormat.Format32bppArgb; BitmapData oldData = oldFrame.LockBits(lockArea, ImageLockMode.ReadOnly, format); BitmapData newData = newFrame.LockBits(lockArea, ImageLockMode.ReadOnly, format); BitmapData resultData = result.LockBits(lockArea, ImageLockMode.WriteOnly, format); int len = resultData.Height * Math.Abs(resultData.Stride) / 4; unsafe { int* pOld = (int*)oldData.Scan0; int* pNew = (int*)newData.Scan0; int* pResult = (int*)resultData.Scan0; for (int i = 0; i < len; i++) { int oldValue = *pOld++; int newValue = *pNew++; *pResult++ = oldValue != newValue ? newValue : 0 /* replace with 0xff << 24 if you need non-transparent black pixel */; // *pResult++ = *pOld++ ^ *pNew++; // if you can use XORs. } } oldFrame.UnlockBits(oldData); newFrame.UnlockBits(newData); result.UnlockBits(resultData); return result; } ``` I think you really can use XORed frames here and I hope that this can have better performance on both sides. ``` private static void XorFrames(Bitmap leftFrame, Bitmap rightFrame) { if (leftFrame.Size != rightFrame.Size) { throw new ArgumentException(); } Rectangle lockArea = new Rectangle(Point.Empty, leftFrame.Size); PixelFormat format = PixelFormat.Format32bppArgb; BitmapData leftData = leftFrame.LockBits(lockArea, ImageLockMode.ReadWrite, format); BitmapData rightData = rightFrame.LockBits(lockArea, ImageLockMode.ReadOnly, format); int len = leftData.Height * Math.Abs(rightData.Stride) / 4; unsafe { int* pLeft = (int*)leftData.Scan0; int* pRight = (int*)rightData.Scan0; for (int i = 0; i < len; i++) { *pLeft++ ^= *pRight++; } } leftFrame.UnlockBits(leftData); rightFrame.UnlockBits(rightData); } ``` You can use this procedure on both sides in following way: On server side you need to evaluate difference between old and new frame, send it to client and replace old frame by new. The server code should look something like this: ``` XorFrames(oldFrame, newFrame); // oldFrame ^= newFrame Send(oldFrame); // send XOR of two frames oldFrame = newFrame; ``` On client side you need to update your current frame with xor frame recieved from server: ``` XorFrames((Bitmap)uxSurface.Image, e.Frame); ```
Yes, you can do so by using `unsafe` code. ``` BitmapData d = l.LockBits(new Rectangle(0, 0, l.Width, l.Height), ImageLockMode.ReadOnly,l.PixelFormat); IntPtr scan = d.Scan0; unsafe { byte* p = (byte*)(void*)scan; //dostuff } ``` Check out <http://www.codeproject.com/KB/GDI-plus/csharpgraphicfilters11.aspx> for some basic examples of this kind of stuff. My code is based on that. Note: One of the reasons this will be much faster than yours is that you are separately comparing each channel instead of just comparing the entire byte using one operation. Similarly, changing PixelAt to give you a byte to facilitate this would probably give you an improvement.
Unsafe Per Pixel access, 30ms access for 1756000 pixels
[ "", "c#", "performance", "gdi+", "" ]
I am a programmer and need a practical approach to storing street address structures of the world in a database. So which is the best and common database design for storing street addresses? It should be simple to use, fast to query and dynamic to store all street addresses of the world.
It is possible to represent addresses from lots of different countries in a standard set of fields. The basic idea of a named access route (thoroughfare) which the named or numbered buildings are located on is fairly standard, except in China sometimes. Other near universal concepts include: naming the settlement (city/town/village), which can be generically referred to as a locality; naming the region and assigning an alphanumeric postcode. Note that postcodes, also known as zip codes, are purely numeric only in some countries. You will need lots of fields if you really want to be generic. The Universal Postal Union (UPU) provides address data for lots of countries in a [standard format](https://upu.int/en/Postal-Solutions/Programmes-Services/Addressing-Solutions). Note that the UPU format holds all addresses (down to the available field precision) for a whole country, it is therefore relational. If storing customer addresses, where only a small fraction of all possible addresses will be stored, its better to use a single table (or flat format) containing all fields and one address per row. A reasonable format for storing addresses would be as follows: * Address Lines 1-4 * Locality * Region * Postcode (or zipcode) * Country Address lines 1-4 can hold components such as: * Building * Sub-Building * Premise number (house number) * Premise Range * Thoroughfare * Sub-Thoroughfare * Double-Dependent Locality * Sub-Locality Frequently only 3 address lines are used, but this is often insufficient. It is of course possible to require more lines to represent all addresses in the official format, but commas can always be used as line separators, meaning the information can still be captured. Usually analysis of the data would be performed by locality, region, postcode and country and these elements are fairly easy for users to understand when entering data. This is why these elements should be stored as separate fields. However, don't force users to supply postcode or region, they may not be used locally. Locality can be unclear, particularly the distinction between map locality and postal-locality. The postal locality is the one deemed by a postal authority which may sometimes be a nearby large town. However, the postcode will usually resolve any problems or discrepancies there, to allow correct delivery even if the official post-locality is not used.
Have a look at [Database Answers](http://www.databaseanswers.org/data_models/customers_and_addresses/index.htm). Specifically, this covers many cases: (All variable length character datatype) ``` AddressId Line1 Line2 Line3 City ZipOrPostcode StateProvinceCounty CountryId OtherAddressDetails ``` [![enter image description here](https://i.stack.imgur.com/VGzMy.gif)](https://i.stack.imgur.com/VGzMy.gif)
Is there common street addresses database design for all addresses of the world?
[ "", "sql", "database-design", "street-address", "postal-code", "" ]
Is there any difference or associated risk opening with the following PHP variations? ``` <? echo "hello world!"; ?> <?php echo "hello world!"; ?> <?="hello world!"?> ``` Also, is it necessary to close all scripts with `?>`
The difference is that some servers might have the first and last examples disabled via [`short_open_tag`](http://www.php.net/ini.core). So if you want your code to be as portable as possible you should use the full `<?php`, otherwise when you move your code to a new server you might find it doesn't work as expected. Also using the short tags can cause clashes if you try doing `<?xml` type declarations. As far as security, using short tags can theoretically be dangerous if someone decides to turn `short_open_tag` off; code using that tag would then be plain-text and broadcast to all (check the comments for more) As for your other question, omitting the closing tags is to prevent whitespace from being accidentally outputted to the browser, as this would mess some scripts up, particularly those trying to output headers of any kind. This is why the [Zend Programming Guide](http://framework.zend.com/manual/en/coding-standard.php-file-formatting.html) recommends not closing your PHP tags. Now that I got all that out of the way, unless I'm working on something that is open source I *personally* use short open tags and I close all of my PHP tags. This is because I am usually in control of my environment and I'm of the opinion that a) `<?=` is just too handy, and b) if you open something you ought to close it. The "best practices", however, don't really agree with that.
Portability can be important when you don't control the hosting. For example, when I wrote some PHP programs that were hosted on my college's hosting, they worked fine until they changed the configuration to disallow the syntax they broke a bunch of pages. Even if it works at the time, if you aren't in control of the hosting there are no guarantees.
What is the "correct" way to start and close a PHP statement?
[ "", "php", "" ]
I was wondering is there a way in PHP that you could tell where a form was submitted without using hidden fields or anything of the like where the user would only need to tamper with the html a little? For example i am trying to work out if a form that was submitted was actually on my website or whether the form was saved offline and submitted that way.
An hidden field is not easily spoofed if it contains a UID (if you encrypt a time stamp you will be able to tell how long the user has been on the page) Of course the user can enter whatever he wants in the field, but unless he can generate a valid UID, he can't make your php script believe it came from somewhere else. You can also track a user's visited pages through $\_SESSION and use that instead of the HTTP referrer (store each visited page in an array inside $\_SESSION, and when your script is called, you simply check whether the last page was yours? Variation of that are possible depending on what you need).
You can attempt to use the referral header set in HTTP requests, do note however that not all browsers set these correctly, or users have them turned off, or that they are very easily spoofed. Without a hidden field containing an unique identifier that is used to identify the form for that one single submission there is no good way of identifying whether the form is being forged or not.
How to know where a form came from?
[ "", "php", "forms", "" ]
There is simple cipher that translates number to series of **.** **(** **)** In order to *encrypt* a number (0 .. 2147483647) to this representation, I (think I) need: * prime factorization * for given *p* (*p* is Prime), order sequence of p (ie. **PrimeOrd(2)** == **0**, **PrimeOrd(227)** == **49**) ### Some examples ``` 0 . 6 (()()) 1 () 7 (...()) 2 (()) 8 ((.())) 3 (.()) 9 (.(())) 4 ((())) 10 (().()) 5 (..()) 11 (....()) 227 (................................................()) 2147483648 ((..........())) ``` ### My source code for the problem ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; static class P { static List<int> _list = new List<int>(); public static int Nth(int n) { if (_list.Count == 0 || _list.Count < n) Primes().Take(n + 1); return _list[n]; } public static int PrimeOrd(int prime) { if (_list.Count == 0 || _list.Last() < prime) Primes().First(p => p >= prime); return (_list.Contains(prime)) ? _list.FindIndex(p => p == prime) : -1; } public static List<int> Factor(int N) { List<int> ret = new List<int>(); for (int i = 2; i ≤ N; i++) while (N % i == 0) { N /= i; ret.Add(i); } return ret; } public static IEnumerable<int> Primes() { _list = new List<int>(); _list.Add(2); yield return 2; Func<int, bool> IsPrime = n => _list.TakeWhile(p => p ≤ (int)Math.Sqrt(n)).FirstOrDefault(p => n % p == 0) == 0; for (int i = 3; i < Int32.MaxValue; i += 2) { if (IsPrime(i)) { _list.Add(i); yield return i; } } } public static string Convert(int n) { if (n == 0) return "."; if (n == 1) return "()"; StringBuilder sb = new StringBuilder(); var p = Factor(n); var max = PrimeOrd(p.Last()); for (int i = 0; i ≤ max; i++) { var power = p.FindAll((x) => x == Nth(i)).Count; sb.Append(Convert(power)); } return "(" + sb.ToString() + ")"; } } class Program { static void Main(string[] args) { string line = Console.ReadLine(); try { int num = int.Parse(line); Console.WriteLine("{0}: '{1}'", num, P.Convert(num)); } catch { Console.WriteLine("You didn't entered number!"); } } } ``` **The problem is SLOWNESS of procedure PrimeOrd. Do you know some FASTER solution for finding out order of prime in primes?** ## Heading ### If You know how to speed-up finding order of prime number, please, suggest something. :-) ## Thank You. --- P.S. The biggest prime less than 2,147,483,648 is **2,147,483,647** and it's **105,097,565th** prime. There is no need to expect bigger number than 2^31.
You should cache the primes to \_list and then use it for both Factor and PrimeOrd. Additionally avoid operators LINQ operators like TakeWhile that create values that you throw away. Here's an optimized version: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; static class P { private static List<int> _list = new List<int>(); public static int Nth(int n) { if (_list.Count == 0 || _list.Count <= n) { GenerateNextPrimes().First(p => _list.Count >= n); } return _list[n]; } public static int PrimeOrd(int prime) { var primes = GrowPrimesTo(prime); return primes.IndexOf(prime); } public static List<int> Factor(int N) { List<int> ret = new List<int>(); GrowPrimesTo(N); for (int ixDivisor = 0; ixDivisor < _list.Count; ixDivisor++) { int currentDivisor = _list[ixDivisor]; while (N % currentDivisor == 0) { N /= currentDivisor; ret.Add(currentDivisor); } if (N <= 1) { break; } } return ret; } private static List<int> GrowPrimesTo(int max) { if (_list.LastOrDefault() >= max) { return _list; } GenerateNextPrimes().First(prime => prime >= max); return _list; } private static IEnumerable<int> GenerateNextPrimes() { if (_list.Count == 0) { _list.Add(2); yield return 2; } Func<int, bool> IsPrime = n => { // cache upperBound int upperBound = (int)Math.Sqrt(n); for (int ixPrime = 0; ixPrime < _list.Count; ixPrime++) { int currentDivisor = _list[ixPrime]; if (currentDivisor > upperBound) { return true; } if ((n % currentDivisor) == 0) { return false; } } return true; }; // Always start on next odd number int startNum = _list.Count == 1 ? 3 : _list[_list.Count - 1] + 2; for (int i = startNum; i < Int32.MaxValue; i += 2) { if (IsPrime(i)) { _list.Add(i); yield return i; } } } public static string Convert(int n) { if (n == 0) return "."; if (n == 1) return "()"; StringBuilder sb = new StringBuilder(); var p = Factor(n); var max = PrimeOrd(p.Last()); for (int i = 0; i <= max; i++) { var power = p.FindAll(x => x == Nth(i)).Count; sb.Append(Convert(power)); } return "(" + sb.ToString() + ")"; } } class Program { static void Main(string[] args) { string line = Console.ReadLine(); int num; if(int.TryParse(line, out num)) { Console.WriteLine("{0}: '{1}'", num, P.Convert(num)); } else { Console.WriteLine("You didn't entered number!"); } } } ```
This is not something you should be doing at run-time. A better option is to pre-calculate all these primes and then put them in your program somehow (a static array, or a file to be read in). The slow code is then run as part of the development process (which is slow anyway :-), *not* at the point where you need your speed. Then it's just a matter of a lookup of some sort rather than calculating them every time you need them.
n-th prime number problem, need to speed it up a bit
[ "", "c#", "optimization", "performance", "primes", "prime-factoring", "" ]
I'm working on a small and simple XNA game and I'm noticing I'm spending way too much time implementing basic UI functionality like menus, (rich) text rendering including wrapping and basic UI lay-out such as alignment of elements. This is a fairly common problem, and I was wondering whether anyone knows of a library to handle these things. I know there are some good skinnable options available to windows programmers (Crazy Eddie's GUI comes to mind), but as I'm targeting the Xbox 360 I would like to find a pure managed solution.
[**xWinForms**](http://sourceforge.net/projects/xwinforms/) is easily the most complete and actively maintained GUI system for XNA. [**Window System for XNA** (WSX)](http://wsx.codeplex.com/) had some good progress in the past (I was working on it for a while), and is still a decent system, though it hasn't been maintained for over a year now. The best option is definitely to go with xWinForms, at least until [WPF interoperability comes along](https://stackoverflow.com/questions/43596/how-well-does-wpf-blend-with-xna-in-real-life) (next version of WPF/XNA?) and makes all the other options effectively obsolete.
There's [XNA Simple Gui](http://www.codeplex.com/simplegui) and [xWinForms](http://www.ziggyware.com/news.php?readmore=374). They provide some basic GUI elements. Haven't seen any menu components, though.
UI library for XNA
[ "", "c#", "user-interface", "xna", "xbox360", "" ]
Can anyone advise on what is the best PHP function for displaying an image stored in a filesystem - `file_get_contents` or `readfile`. We are switching from displaying images stored in the database so we still need to call the images through a PHP file and cannot link directly to the filesystem. I've seen people recommending both functions but I'm inclined towards using `readfile`. Would appreciate any input on this.
If you don't need to manipulate the images (resizing, adding watermarks,...) [`readfile()`](https://www.php.net/readfile) will be the best choice as it writes the file directly to the output buffer. [`file_get_contents()`](https://www.php.net/manual/en/function.file-get-contents.php) will read the file into memory instead - requiring a lot of memory with large files.
Be sure to take **caching** into account when writing scripts like this! A webserver serving a static image will do negotiation with the client when the image is re-requested on the next page visit, and if the server determines that the cached copy of the image at the client side is still valid, the image will not be retransmitted. Since the naive script does not do this negotiation, the image will be retransmitted to the client on every page request, costing you a lot more bandwidth than necessary. There are three mechanisms for this. I can't tell you exactly how to write the optimal script, as I've never had to do this before and I'm not sure how the different caching headers interoperate and on what HTTP version, but I encourage you to research into this further. The three mechanisms that I know of: **Expires** (HTTP/1.0) The simplest one. This header tells the client that the image will definitely be valid until the given moment in time. The client will not even do a request to the script until this time has passed, so setting this appropriately can save you (some) CPU cycles on the server and image loading latency in your web app. How you should set this depends entirely on your application; are your images changing rapidly or rarely? If the image changes before the Expires time you've sent to the client, the client will not see the new image. Example: ``` header("Expires: " . gmdate('D, d-M-Y H:i:s \G\M\T', time() + 60)); // Valid for a minute ``` (Note: Expires seems to have been superseded by **Cache-Control** in HTTP/1.1) **If-Modified-Since** (HTTP/1.1) An HTTP/1.1 client can send this header if it already has a copy of the image, and notes what time the copy dates from. You can then determine in your database if the current version of the image was changed at an earlier or later time. If the version of the client is still the right one, simply send a "304 Not Modified" response and quit (thereby preventing having to transfer the image). Example: ``` $cache_time = parse_browsers_date_time_format($_SERVER["IF-MODIFIED-SINCE"]); $actual_time = get_current_resource_time_from_db(); if ($actual_time <= $cache_time) { header("HTTP/1.1 304 Not Modified"); die; } // ... Produce and output resource here ``` (Note: clients may only actually send the **If-Modified-Since** if you also send **Last-Modified** in the original response. I'm not sure about that, research for yourself.) **ETag/If-None-Match** (HTTP/1.1) This method is similar to the **If-Modified-Since** negotiation, but instead of times it uses a hash of the image as to see if the content has changed. It works as follows: the server calculates some hash for the image, and sends this hash the first time the image is requested in the **ETag** header. On subsequent requests, the server will send the hash back in the request field **If-None-Match**. If the hash of the client is the same as the current hash of the image, the image was not changed in between and the script can suffice by simply sending "304 Not Modified". Since ETags seem to be actually intended to be used to prevent concurrency issues in client requests with side effects (i.e., POST and PUT), and because calculating a hash is a costly operation, I think the If-Modified-Since approach will be a better fit for most file-serving applications.
file_get_contents or readfile for displaying filesystem image
[ "", "php", "function", "" ]
I am using ASP.NET2.0. I have created a download form with some input fields and a download button. When the download button is clicked, I want to redirect the user to a "Thank you for downloading..." page and immediately offer him/her the file to save. I have this following code to show the savefile dialog: ``` public partial class ThankYouPage : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { Response.Clear(); Response.AddHeader("Content-Disposition", "attachment; filename=\"downloadedFile.zip\""); Response.ContentType = "application/x-zip-compressed"; Response.BinaryWrite(this.downloadedFileByteArray); Response.Flush(); Response.End(); } } ``` Obviously, this code does not allow to display any "Thank you" message. Is there an "AfterRender" event or something similar of the Page where, I could move this download code and give a chance for the page to render the "thank you" message to the user? After all, I am truely thankful to them, so I do want to express that.
You could reference a download page from your thank you page using an IFrame ``` <iframe src="DownloadFile.aspx" style="display:none;" /> ``` In this case, DownloadFile.aspx would have the code behind from your example.
Use a META REFRESH tag in the head of your thank-you page: ``` <META http-equiv="refresh" content="1;URL=http://site.com/path/to/downloadedFile.zip"> ``` Alternatively, you might use a body onLoad function to replace the current location with the download URL. ``` <body onLoad="document.location='http://site.com/path/to/downloadedFile.zip'"> ``` In this case the redirection will start *after* the current page has finished loading and only if the client has JavaScript enabled, so remember to include a link with a download link ("If your download doesn't start in a few seconds..." and so on). You may also use an IFRAME as suggested by Phil, or even a FRAME or a full-blown pop-up (blockable, mind you). Your mileage may vary.
Redirecting to a "Thank you" page and offering the save dialog of downloaded file immediately
[ "", "c#", "asp.net", "redirect", "download", "" ]
Is there any (hopefully free/open source) code available that does native TLS/SSL communication? I do not speak about the HTTPListener/Client and WebRequest classes. I'd like to do raw TLS communication in my C# code. Thanks in advance, Max
[Here's an article on codeproject](http://www.codeproject.com/KB/IP/sslclasses.aspx), it also includes code for using OpenSSL. Do you mind if I ask what you're trying to achieve? Just curious really; there's lots of high-level wrapper classes for this kind of thing so you don't normally need to work at this level (not that there's anything wrong with that :-)
<http://www.mentalis.org/soft/projects/ssocket/> - been using this in a commercial product for the last 5 years in .net 1.0, 2.0 and now 3.0. Very reliable, simple to use and stable.
TLS/SSL in .net
[ "", "c#", "sockets", "ssl", "" ]
I started messing around with FXCop against some of my assemblies and noticed something interesting that I'm trying to wrap my head around. > "Types that declare disposable members > should also implement IDisposable. If > the type does not own any unmanaged > resources, do not implement a > finalizer on it." I have my own class that contains some controls that in turn inherit from System.Web.UI.WebControls.Button. It's not complaining about my inherited buttons, but the class that wraps them is. What's the impact or danger here?
What's the nature of the class that contains the buttons? Normally I would only expect a class that's a composite control to have other controls as members. Such a class would normally inherit directly or indirectly from System.Web.UI.CompositeControl or System.Web.UI.WebControl, and the controls you have as members should be added to the Controls collection. Doing so will ensure they are disposed properly and should get rid of the FxCop warning. Post more details of the class in question if this doesn't help.
If your class contains IDisposable types, but your class is not IDisposable, then it is possible that the IDisposable types within your class are not disposed / freed on time, when an instance of your class is no longer needed. Dispoble types should be disposed as soon as you no longer need them, so that resources are freed. If you do not do that, you'll have to wait until the GC kicks in, then the resources will be freed as well.
FXCop: "Types that own disposable fields should be disposable"
[ "", "c#", "fxcop", "" ]
My workplace consists of a lot of cowboy coders. Many of them are junior. Which coincidentally contributes to a lot of code quality issues. I'm looking for suggestions on how to best wane my team into using TDD (we can start with Unit tests, and move into regression tests, and later more automated testing). Ultimately, I want us to learn more quickly from our mistakes, and produce better code and breed better developers. I'm hoping there are some practical suggestions for how to introduce TDD to a team. Specifically, what tools are best to choose in the LAMP (php) stack. Sorry if this question is too open-ended.
After going through this process four times now, I've found that any introduction of TDD will fail without some level of enforcement. Programmers do not want to switch style and will not write their first unit test and suddenly see the light. You can enforce on a management level, but this is time-consuming for all involved. Some level of this is necessary at the beginning anyway, but ultimately you will need automatic enforcement. The answer to this is to introduce Continuous Integration. I've found that a CI Server is the ultimate keystone to any TDD environment. Unless developers know that something bad will happen if they don't write the tests, you'll always have cowboys who feel it's beneath them.
Make writing tests **easy** and the results **visible**. * Use a TestFramework with good documentation. like [SimpleTest](http://simpletest.sf.net) * If test depend on database contents, create a reference database that will be dropped and created at the beginning of a script. * Make a script that runs all test and shows the results on a standalone monitor or something that will make the test visible / easily accessable. (Running a command prompt is not an option) I personally don't write test for every chunk of code in the application. Focus on the domain objects in the application. In my case these are "price-calculation" and "inventory-changes" Remind them that they are probably already writing tests, but that they delete their work just after creation. Example: During the development of a function you'll have a page/testscript in with an *echo* or *var\_dump*() the result. After a manual validation of the result you'll modify the parameters of the function and check again. With some extra effort these tests could be automated in a UnitTest. And which programmer doesn't like to automate stuff?
Introducing Test Driven Development in PHP
[ "", "php", "testing", "process", "tdd", "testing-strategies", "" ]
Say I have a stored procedure, ProcA. It calls ProcB some of the time, ProcC all of the time and ProcD if it hits an error. ProcB calls ProcE every time. ProcC calls ProcF if it hits an error. How could I automate getting the text of ProcA along with the text of all the procs that it calls and regress all the way down the tree (A down to F)? This would help a lot with finding errors in complex sql procs. My first thought here is get the text of ProcA, regex through it and find any calls to other procs, wash rinse repeat, at the end spit out a text (file or to UI) that looks like this: ``` ProcA definition ... ProcB definition ... ... ProcF definition ``` But I'm open to suggestion, perhaps there's an easier way. If there's a tool that does this already lemme know. I have no idea what to put into google on this one.
In SQL Server you have [`sys.sysdepends`](http://msdn.microsoft.com/en-us/library/ms190325.aspx) and [`sys.syscomments`](http://msdn.microsoft.com/en-us/library/ms190325.aspx). `INFORMATION_SCHEMA.ROUTINES` can be useful in the general SQL case, but it has a limit to the size of the text returned on SQL Server, so I avoid it.
this is highly database dependent, because the best way (if possible) would be to query the database's internal tables.
how would you go about automating finding all the procs that a proc calls, along with their text?
[ "", "sql", "sql-server", "" ]
I'm working on a very large project that has associated class files in multiple directories, all stemming from the root dir \src. I'm trying to compile a file in src\solution\ (called Console.java) that uses imports from other directories in the src, which are still uncompiled. So if I want to compile Console.java outside of an IDE, how do I go about doing that? Oh yeah, I also have some external JARs which need to be included in the build. Thanks! I appreciate it!
I would look at using [Ant](http://ant.apache.org/) to create a build script. It's a little bit of work now but it'll pay off over the lifetime of your project.
javac comes with two options, that might help you her: ``` -c path/to/one/jar;path/to/another/jar ``` for libraries and ``` -s path/to/src/solution/java;path/to/src/test/java ``` for sourcefiles. It's worth a try.
Can I use JAVAC to compile a project with multiple files and directories?
[ "", "java", "eclipse", "ide", "javac", "" ]
I've started on a project graphing [Tomcat](http://en.wikipedia.org/wiki/Apache_Tomcat) logs using [gnuplot-py](http://gnuplot-py.sourceforge.net/), specifically correlating particular requests with memory allocation and garbage collection. What is the collective wisdom on gnuplot-py vs [Matplotlib](http://matplotlib.sourceforge.net/) for Python graphing. Are there better graphing libraries out there I haven't heard of? My general considerations are: * While gnuplot has large amounts of documentation, gnuplot-py doesn't. How good is documentation community for Matplotlib? * Are there things which gnuplot can do, but gnuplot-py can't? * Does Matplotlib have better Python support? * Are there are big show stopping bugs in either? Annoyances? * Currently gnuplot is graphing 100,000's of points, I'm planning on scaling this up to millions. Should I expect problems? How well does Matplotlib handle this? * Ease of use, turnaround time for gnuplot vs Matplotlib? * How easy would it be to port existing gnuplot-py code to Matplotlib? How would you approach this task?
* You can check [matplotlib's documentation](http://matplotlib.sourceforge.net/contents.html) yourself. I find it quite comprehensive. * I have very little experience with gnuplot-py, so I can not say whether it can do all gnuplot can. * Matplotlib is written in and designed specifically for Python, so it fits very nicely with Python idioms and such. * Matplotlib is a mature project. NASA uses it for some stuff. * I've plotted tens of millions of points in Matplotlib, and it still looked beautiful and responded quickly. * Beyond the object-oriented way of using Matplotlib is the pylab interface, which makes plotting as easy as it is in MATLAB -- that is, very easy. * As for porting from gnuplot-py to matplotlib, I have no idea.
## Matplotlib = ease of use, Gnuplot = (slightly better) performance --- I know this post is old and answered but I was passing by and wanted to put my two cents. Here is my conclusion: if you have a not-so-big data set, you should use Matplotlib. It's easier and looks better. However, if you *really* need performance, you could use Gnuplot. I've added some code to test it out on your machine and see for yourself if it makes a real difference (this is not a real performance benchmark but should give a first idea). The following graph represents the required time (in seconds) to: * Plot a random scatter graph * Save the graph to a png file ![Gnuplot VS Matplotlib](https://i.stack.imgur.com/zfCmR.png) Configuration: * gnuplot: 5.2.2 * gnuplot-py: 1.8 * matplotlib: 2.1.2 I remember the performance gap being much wider when running on an older computer with older versions of the libraries (~30 seconds difference for a large scatter plot). Moreover, as mentionned in the comments, you can get equivalent quality of plots. But you will have to put more sweat into that to do it with Gnuplot. --- [Here's the code to generate the graph](https://gist.github.com/7hibault/5d7b9a6fa29b61653974e381248073b0) if you want to give it a try on your machine: ``` # -*- coding: utf-8 -*- from timeit import default_timer as timer import matplotlib.pyplot as plt import Gnuplot, Gnuplot.funcutils import numpy as np import sys import os def mPlotAndSave(x, y): plt.scatter(x, y) plt.savefig('mtmp.png') plt.clf() def gPlotAndSave(data, g): g("set output 'gtmp.png'") g.plot(data) g("clear") def cleanup(): try: os.remove('gtmp.png') except OSError: pass try: os.remove('mtmp.png') except OSError: pass begin = 2 end = 500000 step = 10000 numberOfPoints = range(begin, end, step) n = len(numberOfPoints) gnuplotTime = [] matplotlibTime = [] progressBarWidth = 30 # Init Gnuplot g = Gnuplot.Gnuplot() g("set terminal png size 640,480") # Init matplotlib to avoid a peak in the beginning plt.clf() for idx, val in enumerate(numberOfPoints): # Print a nice progress bar (crucial) sys.stdout.write('\r') progress = (idx+1)*progressBarWidth/n bar = "▕" + "▇"*progress + "▁"*(progressBarWidth-progress) + "▏" + str(idx) + "/" + str(n-1) sys.stdout.write(bar) sys.stdout.flush() # Generate random data x = np.random.randint(sys.maxint, size=val) y = np.random.randint(sys.maxint, size=val) gdata = zip(x,y) # Generate string call to a matplotlib plot and save, call it and save execution time start = timer() mPlotAndSave(x, y) end = timer() matplotlibTime.append(end - start) # Generate string call to a gnuplot plot and save, call it and save execution time start = timer() gPlotAndSave(gdata, g) end = timer() gnuplotTime.append(end - start) # Clean up the files cleanup() del g sys.stdout.write('\n') plt.plot(numberOfPoints, gnuplotTime, label="gnuplot") plt.plot(numberOfPoints, matplotlibTime, label="matplotlib") plt.legend(loc='upper right') plt.xlabel('Number of points in the scatter graph') plt.ylabel('Execution time (s)') plt.savefig('execution.png') plt.show() ```
gnuplot vs Matplotlib
[ "", "python", "matplotlib", "gnuplot", "graphing", "" ]
It seems pretty simple but I can't find a good way to do it. Say in the first page I create a variable ``` $myVariable = "Some text"; ``` And the form's action for that page is "Page2.php". So in Page2.php, how can I have access to that variable? I know I can do it with sessions but I think it's too much for a simple string, and I do only need to pass a simple string (a file name). How can I achieve this? Thanks!
HTML / HTTP is stateless, in other words, what you did / saw on the previous page, is completely unconnected with the current page. *Except* if you use something like sessions, cookies or GET / POST variables. Sessions and cookies are quite easy to use, with session being by far more secure than cookies. More secure, but not completely secure. **Session:** ``` //On page 1 $_SESSION['varname'] = $var_value; //On page 2 $var_value = $_SESSION['varname']; ``` Remember to run the `session_start();` statement on both these pages before you try to access the `$_SESSION` array, and also before any output is sent to the browser. **Cookie:** ``` //One page 1 $_COOKIE['varname'] = $var_value; //On page 2 $var_value = $_COOKIE['varname']; ``` The big difference between sessions and cookies is that the value of the variable will be stored on the server if you're using sessions, and on the client if you're using cookies. I can't think of any good reason to use cookies instead of sessions, except if you want data to persist between sessions, but even then it's perhaps better to store it in a DB, and retrieve it based on a username or id. **GET and POST** You can add the variable in the link to the next page: ``` <a href="page2.php?varname=<?php echo $var_value ?>">Page2</a> ``` This will create a GET variable. Another way is to include a hidden field in a form that submits to page two: ``` <form method="get" action="page2.php"> <input type="hidden" name="varname" value="var_value"> <input type="submit"> </form> ``` And then on page two: ``` //Using GET $var_value = $_GET['varname']; //Using POST $var_value = $_POST['varname']; //Using GET, POST or COOKIE. $var_value = $_REQUEST['varname']; ``` Just change the method for the form to `post` if you want to do it via post. Both are equally insecure, although GET is easier to hack. The fact that each new request is, except for session data, a totally new instance of the script caught me when I first started coding in PHP. Once you get used to it, it's quite simple though.
Thanks for the answers above. Here's how I did it, I hope it helps those who follow. I'm looking to pass a registration number from one page to another, hence *regName* and *regValue*: Create your first page, call it **set\_reg.php**: ``` <?php session_start(); $_SESSION['regName'] = $regValue; ?> <form method="get" action="get_reg.php"> <input type="text" name="regName" value=""> <input type="submit"> </form> ``` Create your second page, call it **get\_reg.php**: ``` <?php session_start(); $regValue = $_GET['regName']; echo "Your registration is: ".$regValue."."; ?> <p><a href="set_reg.php">Back to set_reg.php</a> ``` Although not as comprehensive as the answer above, for my purposes this illustrates in simple fashion the relationship between the various elements.
PHP Pass variable to next page
[ "", "php", "variables", "session", "" ]
I'm creating something that includes a file upload service of sorts, and I need to store data compressed with zlib's compress() function. I send it across the internet already compressed, but I need to know the uncompressed file size on the remote server. Is there any way I can figure out this information without uncompress()ing the data on the server first, just for efficiency? That's how I'm doing it now, but if there's a shortcut I'd love to take it. By the way, why is it called uncompress? That sounds pretty terrible to me, I always thought it would be decompress...
The zlib format doesn't have a field for the original input size, so I doubt you will be able to do that without simulating a decompression of the data. The [gzip format](http://www.gzip.org/zlib/rfc-gzip.html#header-trailer) has a "input size" (`ISIZE`) field, that you could use, but maybe you want to avoid changing the compression format or having the clients sending the file size. But even if you use a different format, if you don't trust the clients you would still need to run a more expensive check to make sure the uncompressed data is the size the client says it is. In this case, what you can do is to make the *uncompress-to-/dev/null* process less expensive, making sure zlib doesn't write the output data anywhere, as you just want to know the uncompressed size.
I doubt it. I don't believe this is something the underlying zlib libraries provide from memory (although it's been a good 7 or 8 years since I used it, the up-to-date docs don't seem to indicate this feature has been added). One possibility would be to transfer another file which contained the uncompressed size (e.g., transfer both `file.zip` and `file.zip.size`) but that seems fraught with danger, especially if you get the size wrong. Another alternative is, if the server uncompressing is time-expensive but doesn't have to be done immediately, to do it in a lower-priority background task (like with `nice` under Linux). But again, there may be drawbacks if the size checker starts running behind (too many uploads coming in). And I tend to think of decompression in terms of "explosive decompression", not a good term to use :-)
Get size of uncompressed data in zlib?
[ "", "php", "c", "compression", "size", "zlib", "" ]
I'm trying to get the php executable to parse scripts, but it's not working. i run something like this: > php c:\test.php and test.php contains this: ``` <? echo 'hello!'; ?> ``` and that is exactly what running the command returns. It returns the raw code. How can I get it to actually parse the code and return "hello!" instead?
Make sure you have the [short\_open\_tag](https://www.php.net/ini.core#ini.short-open-tag) setting enabled in your php.ini. Failing that, use the ever-so-slightly longer `<?php` to start your script.
Another option might be to try using the -f command line option. ``` php -f c:\test.php ```
Why Doesnt PHP Parse My Scripts?
[ "", "php", "parsing", "executable", "" ]
Today at work someone tried to convince me that: ``` {$obj->getTableInfo()} ``` is fine for smarty/mvc/templating because it is using an objects method. I argued that because it makes a call to the database it has no place being there and it should be in the controller (we don't actually use MVC). Am I right in my understanding of the logical separations that are used in MVC and generally in templating? Or is there something that I am missing?
You're right. He's wrong. Database calls, no matter in what form, should live in the controller if you want to do MVC right. Obviously people piss all over what it *should* be and do stuff like that, but it's not the correct way.
Well, there are no "official" rules or anything, but I think something like that belongs in the controller. I don't do anything in my view code except display variables, nothing more complex than an `if` or a `foreach`-type loop is allowed. Certainly not calling functions that access the database. That should all be loaded by the controller, the view should only decide whether it needs to display it or not.
Database calls in Smarty/views/templates
[ "", "php", "model-view-controller", "smarty", "templating", "" ]
I have read everywhere that unsigned Java applets are not allowed to make network connections to any server but the one which originated the applet. This is OK for my application since my applet only needs to talk to the server. However, when I wrote a test applet to try opening a socket to communicate with a process on my development machine, it throws the following exception: ``` Error establishing socket connection: java.security.AccessControlException: access denied (java.net.SocketPermission 127.0.0.1:11000 connect,resolve) ``` The code which caused the exception: ``` private void sendMsg(String msg) { Socket s = null; try { s = new Socket("localhost", 11000); } catch (Exception e) { System.err.println("Error establishing socket connection:"); e.printStackTrace(); return; } try { OutputStream out = s.getOutputStream(); out.write(msg.getBytes()); out.flush(); s.shutdownOutput(); s.close(); } catch (Exception e) { System.err.println("Error in writing to the socket:"); e.printStackTrace(); } ``` At first I thought it was a problem in my code that my inexperience had caused me to miss. However, I get the same exception when trying to run the [Talk Server](http://java.sun.com/docs/books/tutorial/deployment/applet/workaround.html "Using a Server to Work Around Security Restrictions") example from the official Java Tutorials. This leads me to believe that I actually have a setup problem, or a misunderstanding of the default security restrictions. Does the default security manager prevent you from opening sockets to the machine running the applet even if it is also the machine serving the applet? If so, that is a problem for me because the deployed system will need to allow a user logged in on the actual server to use the same applet that a remote user would use. Is there a way around the exception I'm getting that doesn't involve signing the applet? I don't want to go to the trouble if not necessary. **NOTE:** I know it would be better not to have users access the applet from the server. That wasn't the original design, but practical considerations unfortunately forced this implementation compromise on me. *UPDATE:* Viewing the applet's page from a webserver solves the problem. Even if the server is localhost. The security update in Java 1.6.0\_11 only applies to applets loaded directly from the local file system.
This is due to a change in the PlugIn introduced in a recent security update. Sorry! Applets loaded from the local file system are no longer granted socket permissions to localhost. [Solution 246387 : A Security Vulnerability in the Java Runtime Environment may Allow Code Loaded From the Local Filesystem to Access LocalHost](http://sunsolve.sun.com/search/document.do?assetkey=1-66-246387-1) > The Java Runtime Environment (JRE) > allows code loaded from the local > filesystem to access localhost. This > may allow code that is maliciously > placed on the local filesystem and > then subsequently run, to have network > access to localhost that would not > otherwise be allowed if the code were > loaded from a remote host. This may be > leveraged to steal cookies and hijack > sessions (for domains that map a name > to the localhost).
I suspect you're running the applet from a local HTML file (eg applet.html), which brings up the error Tom Hawtin mentions. Instead run a webserver (eg [Tomcat](http://tomcat.apache.org/)) on your machine and access the file through `http://localhost/applet.html` It would be probably be better to open the socket port from a servlet in your webserver too. This way your webserver manages your whole system, and it can be simpler to transfer between machines. I use the same setup regularly with socket connection between applet and servlet on both localhost and live.
Socket connection to originating server of an unsigned Java applet
[ "", "java", "security", "applet", "" ]
I want to execute some Python code, typed at runtime, so I get the string and call > exec(pp, globals(), locals()) where **pp** is the string. It works fine, except for recursive calls, e. g., for example, this code is OK: ``` def horse(): robot.step() robot.step() robot.turn(-1) robot.step() while True: horse() ``` But this one is not: ``` def horse(): robot.step() robot.step() robot.turn(-1) robot.step() horse() horse() ``` > NameError: global name 'horse' is not > defined Is there a way to run recursive code as well? UPDATE ``` a = """\ def rec(n): if n > 10: return print n return rec(n+1) rec(5)""" exec(a) ``` Works if put on the top-level. But if moved inside a function: ``` def fn1(): a = """\ def rec(n): if n > 10: return print n return rec(n+1) rec(5)""" exec(a) fn1() ``` the same error occurs: NameError: global name 'rec' is not defined
It works for me: ``` a = """\ def rec(n): if n > 10: return print n return rec(n+1) rec(5)""" exec(a) 5 6 7 8 9 10 ``` All I can say is that there is probably a bug in your code. **Edit** Here you go ``` def fn1(): glob = {} a = """\ def rec(n): if n > 10: return print n return rec(n+1) rec(5)""" exec(a, glob) fn1() ```
This surprised me too at first, and seems to be an odd corner case where exec is acting neither quite like a top-level definition, or a definition within an enclosing function. It looks like what is happening is that the function definition is being executed in the locals() dict you pass in. However, the defined function does not actually have access to this locals dict. Normally, if you define a function at the toplevel, locals and globals are the same, so functions are visible within because they can see the function in the globals. When a function is defined within another function's scope, python will notice that it is accessed within the function, and create a closure so that "horse" maps to the binding in the outer scope. Here, it's a weird halfway case. exec is acting as if the definitions are at top-level, so no closures are created. However, since locals is not the same as globals, the definition doesn't go where the function can access it - its defined only in the inaccessible outer locals dict. There are a couple of things you could do: 1. Use the same dictionary for both locals and globals. ie "`exec s in locals(),locals()`" (or better, just use your own dict). Providing only a globals() dict has the same effect - ie "`exec s in mydict`" # 2. Put the func inside its own function, so that a closure is created. eg ``` s=""" def go(): def factorial(x): if x==0: return 1 return x*factorial(x-1) print factorial(10) go()""" ``` 3. Force the function to go into globals() rather than locals by putting a "global funcname" directive, as suggested by [stephan's answer](https://stackoverflow.com/questions/871887/using-exec-with-recursive-functions/871983#871983)
Using exec() with recursive functions
[ "", "python", "recursion", "exec", "" ]
when ever a function has a object passed by value it uses either copy constructor or bit wise copy to create a temporary to place on stack to use inside the function,How about some object returned from function ? ``` //just a sample code to support the qn rnObj somefunction() { return rnObj(); } ``` and also explain how the return value is taken to the called function.
As can be judged by the other answers - the compiler can optimize this. A concrete example generated using MSVC, to explain *how* this is possible (as asked in one of the comments) - Take a class - ``` class AClass { public: AClass( int Data1, int Data2, int Data3 ); int GetData1(); private: int Data1; int Data2; int Data3; }; ``` With the following trivial implementation - ``` AClass::AClass( int Data1, int Data2, int Data3 ) { this->Data1 = Data1; this->Data2 = Data2; this->Data3 = Data3; } int AClass::GetData1() { return Data1; } ``` And the following calling code - ``` AClass Func( int Data1, int Data2, int Data3 ) { return AClass( Data1, Data2, Data3 ); } int main() { AClass TheClass = Func( 10, 20, 30 ); printf( "%d", TheClass.GetData1() ); } ``` (the printf() added just to make sure the compiler doesn't optimize everything away...). In a non-optimized code, we would expect Func() to create a local AClass on its stack, construct it there and copy it as its return variable. However, the generated assembly actually looks like (removing unneeded lines) - ``` _TEXT SEGMENT ___$ReturnUdt$ = 8 ; size = 4 _Data1$ = 12 ; size = 4 _Data2$ = 16 ; size = 4 _Data3$ = 20 ; size = 4 mov eax, DWORD PTR _Data3$[esp-4] mov ecx, DWORD PTR _Data2$[esp-4] mov edx, DWORD PTR _Data1$[esp-4] push esi mov esi, DWORD PTR ___$ReturnUdt$[esp] push eax push ecx push edx mov ecx, esi call ??0AClass@@QAE@HHH@Z ; AClass::AClass mov eax, esi pop esi ret 0 ``` The 3 function variables are extracted from the stack and placed into eax, ecx and edx. Another forth value is placed into esi (and passed on to ecx). The constructor is called with the 3 parameters on the stack, and ecx still containing the forth value. Let's take a look in the constructor - ``` _TEXT SEGMENT _Data1$ = 8 ; size = 4 _Data2$ = 12 ; size = 4 _Data3$ = 16 ; size = 4 mov edx, DWORD PTR _Data2$[esp-4] mov eax, ecx mov ecx, DWORD PTR _Data1$[esp-4] mov DWORD PTR [eax], ecx mov ecx, DWORD PTR _Data3$[esp-4] mov DWORD PTR [eax+4], edx mov DWORD PTR [eax+8], ecx ret 12 ; 0000000cH ``` The 3 constructor parameters are read into offsets of eax - eax being a copy of ecx, the forth parameter from the call above. So, the constructor builts the object where it is told to - the forth parameter of Func(). And, you guessed it, the forth parameter of Func() is actually the real single place in the entire program where a constructed AClass exists. Let's look at the relevant part of main() - ``` _TEXT SEGMENT _TheClass$ = -12 ; size = 12 _main PROC sub esp, 12 push 30 push 20 lea eax, DWORD PTR _TheClass$[esp+20] push 10 push eax call ?Func@@YA?AVAClass@@HHH@Z ; Func ``` 12 bytes are reserved for an AClass and the three arguments to Func() are passed, along with the forth one - pointing to those 12 bytes. This is a specific example with a specific compiler. Other compilers do this differently. But that's the spirit of things.
The C++ Standard states that the compiler can choose to create a temporary object, using the copy constructor, or it can choose to optimise away the temporary. There is a wikipedia article on the subject, with numerous references [here](http://en.wikipedia.org/wiki/Return_value_optimization).
Is there any temporary created while returning an object from function?
[ "", "c++", "function", "" ]
I need to create a class which calculates the distance between two points. I am stuck and I am a total beginner. Here are my classes: ``` package org.totalbeginner.tutorial; public class Point { public double x; public double y; Point(double xcoord, double ycoord){ this.x = xcoord; this.y = ycoord; } public double getX() { return x; } public double getY() { return y; } } ``` The second class. ``` package org.totalbeginner.tutorial; public class Line { double x; double y; Point p1 = new Point(2.0,2.0); Point p2 = new Point(4.0,4.0); Point mp = new Point(x,y); public void midpoint() { x = (p1.getX() + p2.getX()) / 2; y = (p1.getY() + p2.getY()) / 2; } } ``` I am not sure how to get a point object (the middle point) between both defined points. I can create point objects but I am not sure how to return a point object through my `midpoint()` method that lies between those two point objects.
The distance between two points (x1,y1) and (x2,y2) on a flat surface is: ``` ____________________ / 2 2 \/ (y2-y1) + (x2-x1) ``` But, if all you want is the midpoint of your two points, you should change your midpoint function to: ``` public Point midpoint (Point p1, Point p2) { return new Point ((p1.getX() + p2.getX()) / 2, (p1.getY() + p2.getY()) / 2); } ``` This will return a brand new point object with the points set to the middle of the given two points (without having to concern yourself with any other math). And, since your second class is a line, you only need the two end points to describe it, so I'd make some minor changes. First `Point.java`: ``` class Point { double x, y; Point (double xcoord, double ycoord) { this.x = xcoord; this.y = ycoord; } public double getX() { return x; } public double getY() { return y; } } ``` Then `Line.java`: ``` public class Line { Point p1, p2; Line (Point point1, Point point2) { this.p1 = point1; this.p2 = point2; } public Point midpoint() { return new Point ((p1.getX()+p2.getX())/2, (p1.getY()+p2.getY())/2); } public double abstand() { return Math.sqrt( (p1.getX() - p2.getX()) * (p1.getX() - p2.getX()) + (p1.getY() - p2.getY()) * (p1.getY() - p2.getY()) ); } static public void main (String args[]) { Line s = new Line (new Point(2.0, 2.0), new Point(5.0, 6.0)); Point mp = s.midpoint(); System.out.println ("Midpoint = (" + mp.getX() + "," + mp.getY() + ")"); double as = s.abstand(); System.out.println ("Length = " + as); } } ``` These two files, when compiled and run with the endpoints `2,2` and `5,6` (the hypotenuse of a classic 3/4/5 right-angled triangle), generate the correct: ``` Midpoint = (3.5,4.0) Length = 5.0 ```
Simple Pythag... root(dx^2 + dy^2) ``` Math.sqrt(Math.pow((p2.getX() - p1.getX()), 2) + Math.pow((p2.getY() - p1.getY()), 2)) ```
Calculating the distance between two points
[ "", "java", "" ]
What’s the best/standard way of merging two associative arrays in JavaScript? Does everyone just do it by rolling their own `for` loop?
with jquery you can call `$.extend` ``` var obj1 = {a: 1, b: 2}; var obj2 = {a: 4, c: 110}; var obj3 = $.extend(obj1, obj2); obj1 == obj3 == {a: 4, b: 2, c: 110} // Pseudo JS ``` (assoc. arrays are objects in js) look here: <http://api.jquery.com/jQuery.extend/> --- **edit:** Like rymo suggested, it's better to do it this way: ``` obj3 = $.extend({}, obj1, obj2); obj3 == {a: 4, b: 2, c: 110} ``` As here obj1 (and obj2) remain unchanged. --- **edit2:** In 2018 the way to do it is via `Object.assign`: ``` var obj3 = Object.assign({}, obj1, obj2); obj3 === {a: 4, b: 2, c: 110} // Pseudo JS ``` If working with ES6 this can be achieved with the [Spread Operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax): ``` const obj3 = { ...obj1, ...obj2 }; ```
Now in 2016 I would say the best/standard way is **Object.assign()** Pure Javascript. No jQuery is needed. ``` obj1 = {a: 1, b: 2}; obj2 = {a: 4, c: 110}; obj3 = Object.assign({},obj1, obj2); // Object {a: 4, b: 2, c: 110} ``` More information, examples and polyfill here: <https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/assign>
Merging objects (associative arrays)
[ "", "javascript", "object", "" ]
I'm having terrible trouble trying to understand python scoping rules. With the following script: ``` a = 7 def printA(): print "Value of a is %d" % (a) def setA(value): a = value print "Inside setA, a is now %d" %(a) print "Before setA" printA() setA(42) print "After setA" printA() ``` Gives the unexpected (to me) output of: ``` Before setA Value of a is 7 Inside setA, a is now 42 After setA Value of a is 7 ``` Where I would expect the last printing of the value of a to be 42, not 7. What am I missing about Python's scope rules for the scoping of global variables?
Global variables are special. If you try to assign to a variable `a = value` inside of a function, it creates a new local variable inside the function, even if there is a global variable with the same name. To instead access the global variable, add a [`global` statement](http://docs.python.org/reference/simple_stmts.html#the-global-statement) inside the function: ``` a = 7 def setA(value): global a # declare a to be a global a = value # this sets the global value of a ``` See also [Naming and binding](http://docs.python.org/reference/executionmodel.html#naming-and-binding) for a detailed explanation of Python's naming and binding rules.
The trick to understanding this is that when you assign to a variable, using =, you also declare it as a local variable. So instead of changing the value of the global variable a, setA(value) actually sets a local variable (which happens to be called a) to the value passed in. This becomes more obvious if you try to print the value of a at the start of setA(value) like so: ``` def setA(value): print "Before assignment, a is %d" % (a) a = value print "Inside setA, a is now %d" % (a) ``` If you try to run this Python will give you a helpful error: ``` Traceback (most recent call last): File "scopeTest.py", line 14, in setA(42) File "scopeTest.py", line 7, in setA print "Before assignment, a is %d" % (a) UnboundLocalError: local variable 'a' referenced before assignment ``` This tells us that Python has decided that the setA(value) function has a local variable called a, which is what you alter when you assign to it in the function. If you don't assign to a in the function (as with printA()) then Python uses the global variable A. To mark a variable as global you need to use the global keyword in Python, *in the scope that you want to use the global variable*. In this case that is within the setA(value) function. So the script becomes: ``` a = 7 def printA(): print "Value of a is %d" % (a) def setA(value): global a a = value print "Inside setA, a is now %d" %(a) print "Before setA" printA() setA(42) print "After setA" printA() ``` This one line addition tells Python that when you use the variable a in the setA(value) function that you are talking about the global variable, not a local variable.
Why does assigning to my global variables not work in Python?
[ "", "python", "global-variables", "scope", "" ]
I have a .net 2.0 c# ClickOnce app and it connects to its data via Web Services. I've been told that one way to potentially speed up the application is to generate a serialization assembly beforehand. I have several questions on this front. 1. The default setting to whether to generate a serialization assembly is Auto. What criteria does VS2005 use to decide whether to generate a serialization assembly or not? It seems like it does not generate under Debug configuration, but it does under Release configuration, but I can't tell for sure and can't the information anywhere. 2. Does serialization assembly actually improve the startup of the application? Specifically what does it improve? Do I actually need a serialization assembly?
It is really asking "Shall I pre-generate the serialization assemblies and include it in the deployed project or shall I fall back on the default of generating the assemblies on the fly?" Generally that won't hurt too much after the first hit perf-wise. Where it can play in is that the serialization assemblies are generated in `%SYSTEMROOT%\TEMP`. Which, in some cases, the process can't access, leading to fatal exceptions in most cases.
This is not relevant to your situation, but there's another good reason for pre-generating the serialization assembly - it's necessary when hosting your code in SQL Server (i.e. SQLCLR). SQL Server doesn't allow these assemblies to be generated dynamically, so your serialization code would fail inside SQL Server.
Serialization Assembly. Is it needed or not?
[ "", "c#", "web-services", "serialization", "assemblies", "clickonce", "" ]
I'm building a C# application, and I want to identify users by their username. For example, if I logged onto the domain mydomain as the user myusername I'd want to get the mydomain\myusername so I can identify the user. How can I do this with C#?
It's very simple indeed: ``` Environment.UserName ``` From the [MSDN page](http://msdn.microsoft.com/en-us/library/system.environment.username.aspx): > The UserName property provides part of > the credentials associated with > computer domain names, as returned by > the UserDomainName property. This > information is typically represented > as DOMAIN\username. > > This property can be used to identify > the current user to the system and > application for security or access > purposes. It can also be used to > customize a particular application for > each user. You can also get the domain name using [`Environment.UserDomainName`](http://msdn.microsoft.com/en-us/library/system.environment.userdomainname.aspx).
try **User.Identity.Name** or **Environment.UserName**. EDIT: Environment.UserDomainName - Domain Environment.UserName - UserName
How can I get the users network login name?
[ "", "c#", "windows", "networking", "" ]
I use these sentence in C# to retrieve data from tables DetalleContenido and Archivo: ``` var detallesContenido = from contenido in guiaContext.Contenido where contenido.PuntoInteres.id_punto == puntoInteresID from dc in contenido.DetalleContenido where dc.Idioma.ds_idioma == idiomaCliente select dc; ``` The relationship between tables is this: [![DataBase Model](https://i.stack.imgur.com/r7gBr.png)](https://i.stack.imgur.com/r7gBr.png) I use puntoInteresID and idiomaCliente to retrieve all rows from DetalleContenido and Archivo that are part of PuntoInteres but whith this sentence Archivo is allways null!! The sql sentece equivalence is: ``` Select dc.ds_nomDetContenido, dc.ds_descDetContenido, ar.archivo from Contenido c, DetalleContenido dc, Archivo ar, Idioma i where c.id_punto = puntoInteresID and c.id_contenido = dc.id_contenido and dc.id_idioma = i.id_idioma and i.ds_idioma = idiomaCliente and dc.id_archivo = ar.id_archivo; ``` How can I retrieve Archivo too? Thank you!
You can also do ``` .Load() ``` on the "reference" properity of the selected object (when you are using them). But as for your query, it seems your Archivo table is a 1 to many and you cannot "include" or "load" the "many" side of the equasion. You would have to do a "select dc.Archivo" I would think.
My solution: ``` var detallesContenido = from contenido in guiaContext.Contenido where contenido.PuntoInteres.id_punto == puntoInteresID from detalleContenido in contenido.DetalleContenido where detalleContenido.Idioma.ds_idioma == idiomaCliente select new { detalleContenido, detalleContenido.Archivo }; ``` Thank you!
Ado.Net entity framework, linq: select multiples tables
[ "", "c#", "entity-framework", "ado.net", "linq-to-entities", "" ]
HI, I need to write multiple statements inside a conditional operator. What will be the equivalent of this if condition with conditional operator ``` var name; var age; var passed; if ( arg == "first" ) { name = "John"; age = "25"; passed = false; } else { name = "Peter"; age = "29"; passed = true; } ```
If you're in a situation where you need to execute statements based on a boolean condition, you should really use if-else. The conditional operator is really meant to return a value from an expression, not to execute full statements. By using the conditional operator, you make your code harder to read and more perilous to debug. If you insist on using the conditional operator, alamar's solution appears to fit your need quite nicely. However, I recommend you vigorously comment your code. The next time you need to modify your code, that comment could be the difference between taking 60 seconds to understand and taking 0.6 seconds to understand. And if you do comment it, there's really no bandwidth savings in using the character-wise shorter conditional operator over the if-else statement.
hmhm, do you mean ternary operator? ``` var passed = arg == "first" ? (name = "John", age = "25", false) : (name = "Peter", age = "29", true); ``` My quick check with embedjs shows that it does more or less work. But why? Why would you need that? It would qualify as a major WTF.
Multiple statements inside a conditional operator
[ "", "javascript", "" ]
How can I `UPDATE` a field of a table with the result of a `SELECT` query in Microsoft Access 2007. Here's the Select Query: ``` SELECT Min(TAX.Tax_Code) AS MinOfTax_Code FROM TAX, FUNCTIONS WHERE (((FUNCTIONS.Func_Pure)<=[Tax_ToPrice]) AND ((FUNCTIONS.Func_Year)=[Tax_Year])) GROUP BY FUNCTIONS.Func_ID; ``` And here's the Update Query: ``` UPDATE FUNCTIONS SET FUNCTIONS.Func_TaxRef = [Result of Select query] ```
Well, it looks like Access can't do aggregates in UPDATE queries. But it can do aggregates in SELECT queries. So create a query with a definition like: ``` SELECT func_id, min(tax_code) as MinOfTax_Code FROM Functions INNER JOIN Tax ON (Functions.Func_Year = Tax.Tax_Year) AND (Functions.Func_Pure <= Tax.Tax_ToPrice) GROUP BY Func_Id ``` And save it as YourQuery. Now we have to work around another Access restriction. UPDATE queries can't operate on queries, but they can operate on multiple tables. So let's turn the query into a table with a Make Table query: ``` SELECT YourQuery.* INTO MinOfTax_Code FROM YourQuery ``` This stores the content of the view in a table called MinOfTax\_Code. Now you can do an UPDATE query: ``` UPDATE MinOfTax_Code INNER JOIN Functions ON MinOfTax_Code.func_id = Functions.Func_ID SET Functions.Func_TaxRef = [MinOfTax_Code].[MinOfTax_Code] ``` Doing SQL in Access is a bit of a stretch, I'd look into Sql Server Express Edition for your project!
I wrote about some of the [limitations of correlated subqueries](http://ewbi.blogs.com/develops/2004/07/accessjet_sql_u.html) in Access/JET SQL a while back, and noted the syntax for joining multiple tables for SQL UPDATEs. Based on that info and some quick testing, I don't believe there's any way to do what you want with Access/JET in a single SQL UPDATE statement. If you could, the statement would read something like this: ``` UPDATE FUNCTIONS A INNER JOIN ( SELECT AA.Func_ID, Min(BB.Tax_Code) AS MinOfTax_Code FROM TAX BB, FUNCTIONS AA WHERE AA.Func_Pure<=BB.Tax_ToPrice AND AA.Func_Year= BB.Tax_Year GROUP BY AA.Func_ID ) B ON B.Func_ID = A.Func_ID SET A.Func_TaxRef = B.MinOfTax_Code ``` Alternatively, Access/JET will sometimes let you get away with saving a subquery as a separate query and then joining it in the UPDATE statement in a more traditional way. So, for instance, if we saved the SELECT subquery above as a separate query named FUNCTIONS\_TAX, then the UPDATE statement would be: ``` UPDATE FUNCTIONS INNER JOIN FUNCTIONS_TAX ON FUNCTIONS.Func_ID = FUNCTIONS_TAX.Func_ID SET FUNCTIONS.Func_TaxRef = FUNCTIONS_TAX.MinOfTax_Code ``` However, this still doesn't work. I believe the only way you will make this work is to move the selection and aggregation of the minimum Tax\_Code value out-of-band. You could do this with a VBA function, or more easily using the Access DLookup function. Save the GROUP BY subquery above to a separate query named FUNCTIONS\_TAX and rewrite the UPDATE statement as: ``` UPDATE FUNCTIONS SET Func_TaxRef = DLookup( "MinOfTax_Code", "FUNCTIONS_TAX", "Func_ID = '" & Func_ID & "'" ) ``` Note that the DLookup function prevents this query from being used outside of Access, for instance via JET OLEDB. Also, the performance of this approach can be pretty terrible depending on how many rows you're targeting, as the subquery is being executed for each FUNCTIONS row (because, of course, it is no longer correlated, which is the whole point in order for it to work). Good luck!
Use SELECT inside an UPDATE query
[ "", "sql", "ms-access-2007", "sql-update", "" ]
I need to select by date in a SQL query, for example ``` SELECT * FROM foo WHERE date = '2009-09-09' ``` That query works in my Hypersonic test database, but not Oracle, which seems to requires: ``` SELECT * FROM foo WHERE date = TO_DATE('2009-09-09', 'yyyy-mm-dd') ``` Is there a way to select by date uniformly across these two databases?
I found the answer - you can create the TO\_DATE function in HyperSonic and then the second query works in both. For example, make the class: ``` public class Date { public static String toDate( String value, String format ) { return value; } } ``` And the query ``` SELECT * FROM foo WHERE date = TO_DATE('2009-09-09', 'yyyy-mm-dd') ``` works in both.
You could try H2 database as your in memory database ([<http://www.h2database.com>](http://www.h2database.com)). It should have decent [Oracle compablity mode](http://www.h2database.com/html/features.html).
Oracle vs. Hypersonic SQL
[ "", "sql", "database", "oracle", "hsqldb", "" ]
Below I present you some code which has completely been butchered by me. ``` $(".gig").hover(function() { var id = $(this).attr("id"); var time = $(this).attr("title"); function () { if (time > 0) { var answer = $('<div class="roll">Are you attending? <a href="' + id + '">Yes</a></div>').hide(); } else { var answer = $('<div class="roll">Did you attend?<a href="' + id + '">Yes</a> </div>').hide(); } answer.appendTo($(this)).fadeIn("fast"); } function () { $(this).find("div:last").fadeOut("fast", function() { $(this).remove() }); } }); ``` I know, it is terrible. It basically is like pseudocode now. Could anyone help me to re-write my mess into actually functioning code? Basically for every class named div, it should append the variable answer onto the end of this div, and on mouseout, remove the variable answer. The variable time will be fetched from the title of the rollover div, and thus affect what is shown in the new div that is added. The id of the .gig should simply be passed into the url. The hover answer add/remove functions work on their own, but I am unable to place them into the new function with the if and new variables. Thank you so much.
This part jumped out at me: `. id .` - You don't concantenate strings with `.` in Javascript, you use `+`. The fact you posted this code with that mistake tells me that A) you have a lackluster editor, and/or B) you don't debug your Javascript using a tool like [Firebug](http://www.getfirebug.com). You should probably get on that. :) You are also trying to use the hover's two function arguments incorrectly, as you put all your code in one huge function and then just declare two anonymous functions (I'm not even sure that syntax works??) Below is a correct (*as far as syntax* and what I *think* the logic is) version of your code. Give it a whirl. ``` $(".gig").hover(function () { var id = $(this).attr("id"); if (time > 0) { var answer = $('<div class="roll">Are you attending? <a href="' + id + '">Yes</a></div>').hide(); } else { var answer = $('<div class="roll">Did you attend?<a href="' + id + '">Yes</a> </div>').hide(); } answer.appendTo($(this)).fadeIn("fast"); }, function () { $(this).find("div:last").fadeOut("fast", function() { $(this).remove() }); }); ```
**EDIT** You have editted your question. I think this should do what you want: ``` $(".gig").hover(function() { var $this = $(this); var id = $this.attr("id"); var time = $this.attr("title"); var a = $('<a />').text('Yes').attr('href', id); var div = ('<div />').addClass('roll'); if(time > 0){ div.text('Are you attending?'); } else { div.text('Did you attend?'); } var answer = div.append(a).hide(); answer.appendTo( this ).fadeIn('fast'); }, function(){ $(this).find("div.roll:last").fadeOut("fast", function() { $(this).remove() }); }); ``` You could improve it using some caching for the DOM node creation though, something like this: ``` $(".gig").hover(function() { var $this = $(this); if(typeof $this.data('attendingLink') === 'undefined'){ var id = $this.attr("id"); var time = $this.attr("title"); var a = $('<a />').text('Yes').attr('href', id); var div = ('<div />').addClass('roll'); if(time > 0){ div.text('Are you attending?'); } else { div.text('Did you attend?'); } var answer = div.append(a); $this.data('attendingLink', answer); } else { var answer = $this.data('attendingLink'); } answer.hide(); answer.appendTo( this ).fadeIn('fast'); }, function(){ $(this).find("div.roll:last").fadeOut("fast", function() { $(this).remove() }); }); ``` That will however only improve preformance when the user hovers over the .gig elements a lot.
jQuery problems
[ "", "javascript", "jquery", "" ]
I need to load an image from a web in a simple Java stand alone aplication. Any Ideas?
``` URL url = new URL("http://host/theimage.jpg"); URLConnection conn = url.openConnection(); InputStream in = conn.getInputStream(); ``` is that enough to start you? Don't know what you want to do from there.
You can load an image using ``` BufferedImage img = ImageIO.read(new URL("http://stackoverflow.com/content/img/so/logo.png")); ``` For methods how to display the loaded image, see the Sun ["Working with images" tutorial](http://java.sun.com/docs/books/tutorial/2d/images/index.html).
how to load a image from web in java
[ "", "java", "image", "" ]
Okay I'm trying to go for a more pythonic method of doing things. How can i do the following: ``` required_values = ['A','B','C'] some_map = {'A' : 1, 'B' : 2, 'C' : 3, 'D' : 4} for required_value in required_values: if not required_value in some_map: print 'It Doesnt Exists' return False return True ``` I looked at the builtin function `all`, but I cant really see how to apply that to the above scenario. Any suggestions for making this more pythonic?
``` all(value in some_map for value in required_values) ```
``` return set(required_values).issubset(set(some_map.keys())) ```
Checking to See if a List Exists Within Another Lists?
[ "", "python", "list", "" ]
My question is broader than merely expanding language specific skills. I'm wondering what sort of advice anyone might offer to someone with a desire for knowledge, but a lack of direction. Feel free to skip down to the question. **Background:** I've taken a single computer science course in java at my University, but i'm planning on majoring in Computer Science and Electrical Computer Engineering (ECE). My java class was quite rudimentary. We were provided with a framework and merely edited/created a few methods and classes to perform a simple task. We made a version of Breakout, and created an AI for a simple connect-four game. Although I'm somewhat familiar with big O notation, I haven't actually studied it in class (My next CS class covers this). In my introductory ECE course we also programmed BOE-Bots in PBASIC to compete in an obstacle course of sorts. As an engineering student, I was also introduced to matlab, although I've only used it for linear algebra homework. In summary, I don't have much programming background, but I've loved pretty much everything I've done so far, and I'm looking for ways to build a more valuable skill set. **Steps Taken:** After paying more attention to the programming section of reddit, I found a link to [Project Euler](http://projecteuler.net). This summer I've been hacking away at those problems (finished my 42nd solution yesterday), but I'm looking for some more direction. I've been reading blog entries and SO heavily. I'd like to learn something about php, and perhaps create a dynamic webpage, but fundamentally I want to do anything in my power do to improve myself and prepare for the working world. **Question:** *What would direction would you recommend for me? Should I learn a new language? Keep attacking Project Euler? Read some books on programming? Start a coding project(I wouldn't even know where to begin)? Wait until school? Learn about more fundamental programming principles?* I guess with all the paths available, I'm just a little overwhelmed, and I don't want to fall into a path that might be detrimental to my career opportunities. I'm also really bad at making decisions. Your advice would be greatly appreciated!
Most everyone is suggesting doing more programming. Whilst that's obviously important, I think it's important to understand the environments that your programs work in. I would investigate how operating system work (how they allocate resources for you, how they schedule programs and threads), how networks work (routing, TCP/UDP behaviours and limitations etc.), and some database theory. I see a lot of junior programmers with great language knowledge, but beyond the sandbox of their program they don't have a clue how the computer/network enables their stuff to run. Knowing something of the above will make you a better programmer in terms of how you write your programs, and how you understand how they'll work (and indeed, how to debug them or analyse their failures)
The word quickly worries me... I suggest you read [Teach Yourself Programming in Ten Years - Why is everyone in such a rush?](http://norvig.com/21-days.html) ~~ Peter Norvig Forgive yourself if you're not setting the world on fire three weeks after sitting down at the keyboard... maybe you're destined to be a late bloomer? ;-)
How can I quickly improve my abilities as a programmer?
[ "", "java", "" ]
This is related to my previous [question](https://stackoverflow.com/questions/929001/how-do-i-adapt-this-program-to-comply-with-the-online-judge) I'm solving UVA's Edit Step Ladders and trying to make the online judge comply with my answer. I have used the method ReadLn() to adapt my textfile-reading program to this: ``` import java.io.*; import java.util.*; class LevenshteinParaElJuez implements Runnable{ static String ReadLn(int maxLength){ // utility function to read from stdin, // Provided by Programming-challenges, edit for style only byte line[] = new byte [maxLength]; int length = 0; int input = -1; try{ while (length < maxLength){//Read untill maxlength input = System.in.read(); if ((input < 0) || (input == '\n')) break; //or untill end of line ninput line [length++] += input; } if ((input < 0) && (length == 0)) return null; // eof return new String(line, 0, length); }catch (IOException e){ return null; } } public static void main(String args[]) // entry point from OS { LevenshteinParaElJuez myWork = new LevenshteinParaElJuez(); // Construct the bootloader myWork.run(); // execute } public void run() { new myStuff().run(); } } class myStuff implements Runnable{ public void run(){ ArrayList<String> theWords = new ArrayList<String>(); try { /// PLACE YOUR JAVA CODE HERE String leido=LevenshteinParaElJuez.ReadLn(100); //System.out.println("lo leido fue "+leido); while (!leido.equals(" ")){ theWords.add(leido); leido=LevenshteinParaElJuez.ReadLn(100); } }catch(Exception e){ System.out.println("El programa genero una excepcion"); } int maxEdit=0; int actualEdit=0; int wordsIndex1 =0, wordsIndex2=0; while (wordsIndex1<= theWords.size()) { while (wordsIndex2<= theWords.size()-1){ actualEdit=Levenshtein.computeLevenshteinDistance(theWords.get(wordsIndex1),theWords.get(wordsIndex2)); if (actualEdit>maxEdit){maxEdit=actualEdit;} wordsIndex2++; } wordsIndex1++; } System.out.println(maxEdit+1); } } class Levenshtein { private static int minimum(int a, int b, int c) { if(a<=b && a<=c) return a; if(b<=a && b<=c) return b; return c; } public static int computeLevenshteinDistance(String str1, String str2) { return computeLevenshteinDistance(str1.toCharArray(), str2.toCharArray()); } private static int computeLevenshteinDistance(char [] str1, char [] str2) { int [][]distance = new int[str1.length+1][str2.length+1]; for(int i=0;i<=str1.length;i++) distance[i][0]=i; for(int j=0;j<=str2.length;j++) distance[0][j]=j; for(int i=1;i<=str1.length;i++) for(int j=1;j<=str2.length;j++) distance[i][j]= minimum(distance[i-1][j]+1, distance[i][j-1]+1, distance[i-1][j-1]+ ((str1[i-1]==str2[j-1])?0:1)); return distance[str1.length][str2.length]; } } ``` I'm supposed to read the whole of the online judge's input as it were written via keyboard, but when I run the above program I can't make it stop reading. It goes something like: ``` abc cba aba cca ``` without being able to stop the console reading. How do I get around this?? I suspect the problem is in my loop's conditional: ``` String leido=LevenshteinParaElJuez.ReadLn(100); //System.out.println("lo leido fue "+leido); while (!leido.equals(" ")){ theWords.add(leido); leido=LevenshteinParaElJuez.ReadLn(100); } ``` I have also used: ``` while (!leido.equals(null)){ theWords.add(leido); leido=LevenshteinParaElJuez.ReadLn(100); } ``` and gotten stuck as well. Edit: the declaration was actually: ``` while (leido != null)){ theWords.add(leido); leido=LevenshteinParaElJuez.ReadLn(100); } ``` I don't get why it's failing. I want the reading of input via keyboard to stop when the first blank line is entered. Edit: thanks to rodion's answer, the ReadLn method is now changed to: ``` if ((input < 0) || (length == 0)) return null; // eof ``` instead of: ``` if ((input < 0) && (length == 0)) return null; // eof ``` Now, it's reading two blank space before producing the integer output. How can I change it just to read one?
The problem is that the input will not be <0 when it reaches the line that returns null, so do: ``` while (leido.length() != 0) { .... } ```
I am not really sure if I understand your problem correctly. If you merely want your program to stop reading from the console, you can "close" the console by hitting Ctrl+D (Linux) or Ctrl+Z (Windows). This causes System.in.read() to return -1, so that ReadLn method would return null. Check for null as Nathaniel suggested. **Edit**: (based on your comment) The problem is with this condition in the ReadLn method ``` if ((input < 0) && (length == 0)) return null; ``` If you enter a blank line, length will be 0, input will be > 0 though (whatever your system uses to denote a newline). If you change it to ``` if ((input < 0) || (length == 0)) return null; ``` the method will return null if either the input stream is closed or a blank line is entered.**strong text**
Problem processing input for online judge
[ "", "java", "" ]
I need to write a a query that gets a set of information from a table, but if there is no information for that specific client, then use the default set. I was wondering if there is a way to avoid query duplication in an if(exists()) statement. For example: ``` IF( EXISTS( SELECT * FROM UserTable WHERE Name = @UserName)) BEGIN SELECT * FROM UserTable WHERE Name = @UserName)) END ELSE BEGIN SELECT * FROM UserTable WHERE Name = 'Jon Skeet')) END ``` The first two selects (exists and the true part of the if) are the exact same. I want to avoid running the same query twice if the statement is true. I know the exists stops once the first true condition is met but that is still O(n) worst case. Another option I know of, is put the information in a temp table and check if information is there, if not return the default information. Both ways would work but what is the best way to do it? Are there other ways to do this? Is there some way to do this in the WHERE clause since that's the only thing that is different? Edit: Fixed example to return a row not just a single item. So the answers of dumping the select to a single variable would be equal to a temp table I assume. Also, to not anger Jon Skeet, spelled his name right
You could do this: ``` SELECT TOP 1 UserID FROM UserTable WHERE Name IN (@UserName, 'John Skeet') ORDER BY CASE WHEN Name = 'John Skeet' THEN 2 ELSE 1 END ``` (or use LIMIT or whatever the method is for your RDBMS) Or you could do this: ``` DECLARE @UserID INT SELECT @UserID = UserID FROM UserTable WHERE Name = @UserName IF (@UserID IS NULL) SELECT @UserID = UserID FROM UserTable WHERE Name = 'John Skeet' SELECT @UserID AS UserID ``` Or this: ``` SELECT COALESCE(T2.UserID, T1.UserID) FROM UserTable T1 LEFT OUTER JOIN UserTable T2 ON T2.Name = @UserName WHERE T1.Name = 'John Skeet' ``` Or this: ``` SELECT UserID FROM UserTable WHERE Name = @UserName IF (@@ROWCOUNT = 0) -- MS SQL Server specific, your RDBMS method will vary SELECT UserID FROM UserTable WHERE Name = 'John Skeet' ```
How about: ``` DECLARE @UserID int; SELECT @UserID = UserID FROM UserTable WHERE Name = @UserName IF(@UserID IS NULL) BEGIN SELECT @UserID=UserID FROM UserTable WHERE Name = 'Jon Skeet')) END SELECT @UserID ```
SQL if( exists()) query duplication
[ "", "sql", "" ]
In testing document.location.href, I have observed that when the user initiates an action that results in javascript that assigns to document.location.href, the new URL is added to the history. However, if the call is initiated by javascript that is result of, say, state change of an XMLHTTPRequest, the entry for the current page in the history is over-written. Have I characterized this correctly? Is there a way to get the page change to be reflected in the history in this latter case?
I was facing the same problem and found this workaround which worked for me instead of ``` function onAjaxCallback(evt){ location.href=newLocation; } ``` i wrapped the location.href call around a setTimeout. Seems to do the trick. My history's behaving fine now. Hope that helps ``` function onAjaxCallback(evt){ setTimeout(function(){ location.href=newLocation; },0) } ```
You could change the location without having the browser display a Back button like this: ``` window.location.replace(new_url); ``` However, the original address remains in the browser's history and may be accessed using something like `CTRL`+`H` Reference: * <https://developer.mozilla.org/en/DOM/window.location#replace> * <https://developer.mozilla.org/En/DOM/Window.history#Notes>
Assigning to document.location.href without clobbering history
[ "", "javascript", "" ]
I feel stupid for asking, but there must be a one liner that does the equivalent or near equivalent of the code below in c#... so can you tell me what it is? ``` public static string[] ToStringArray(int[] i) { if (i==null) return null; string[] result = new string[i.Length]; for (int n= 0; n< result.Length; n++) result[n] = i[n].ToString(); return result; } ```
How about an extension method? ``` public static string[] ToStringArray<T>(this IEnumerable<T> items) { return items.Select(i => i.ToString()).ToArray(); } ```
Using LINQ: ``` int[] ints = { 1, 2, 3 }; string[] strings = ints.Select(i => i.ToString()).ToArray(); ```
c# one liner for .ToString() across entire array
[ "", "c#", "shortcut", "" ]
There is a good generalized method for defining private and protected properties and methods in Javascript, [here on the site](https://stackoverflow.com/questions/55611/javascript-private-methods). However, the current version of Prototype (1.6.0) doesn't have a built-in way to define them through its [`Class.create()`](http://www.prototypejs.org/learn/class-inheritance) syntax. I'm curious what the best practices are when developers want to define private and protected properties and methods when using Prototype. Is there a better way than the generic one?
What you can do is using local variables in your constructor function (initialize) for prototype and then creating a closure that will access/expose this variable to your public methods. Here's a code example: ``` // properties are directly passed to `create` method var Person = Class.create({ initialize: function(name) { // Protected variables var _myProtectedMember = 'just a test'; this.getProtectedMember = function() { return _myProtectedMember; } this.name = name; }, say: function(message) { return this.name + ': ' + message + this.getProtectedMember(); } }); ``` Here's Douglas crockford theory on the subject. <http://www.crockford.com/javascript/private.html>
There's a discussion [here](https://prototype.lighthouseapp.com/projects/8886/tickets/152-implement-private-variables-for-classes) in Prototype's lighthouse that shows that explains why you can't get this effect with Prototype's Class.create.
Using Prototype's Class.create to define private/protected properties and methods
[ "", "javascript", "oop", "private", "prototypejs", "protected", "" ]
Whats the best way to check if a username exists in a MySQL table?
``` SELECT COUNT(*) as count FROM users WHERE username='whatever' ``` read out the first result row - if the 'count' column is > 0 then the username exists. Alternatively, in php, you could use: ``` SELECT * FROM users WHERE username='whatever' ``` Then use mysql\_num\_rows (or the equivalent).
If you are trying to determine if a user exists in MySQL (i.e. a user name exists that can login to MySQL itself). ``` select user,host from mysql.user where user = 'username'; ``` If you need to filter by host: ``` select user,host from mysql.user where user = 'username' and host = 'localhost'; ``` These queries lets you see who has access to the MySQL database server and only is accessible if you are an administrator for a MySQL server.
Check If Username Exists
[ "", "php", "mysql", "" ]
How do I find out the current runtime directory from within a Python script?
Use [`os.getcwd`](http://docs.python.org/library/os.html#os.getcwd). This will tell you the *current working directory*. If you create a new file with ``` fp = open('a.txt', 'w') ``` then `a.txt` will be created in the current working directory. Use [`os.chdir`](http://docs.python.org/library/os.html#os.chdir) to change the working directory, if needed.
This is working for me. ``` os.path.dirname(__file__) ```
Runtime directory of Python
[ "", "python", "working-directory", "" ]