Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
Let's say I have a class Customer, which has a property customerType. I have another class called something like SpecialContract, which has a Customer and some other properties. If customer.customerType == SPECIAL, then there is a SpecialContract which has a reference to this particular Customer. Now I realize that this is a bit hoaky, but I do not want to maintain a relationship from Customer **to** SpecialContract for a few reasons, one being that most of the time when working with Customers we don't need to load up SpecialContracts and all of the other data associated with SpecialContracts. However, I do always want to know if a Customer has a SpecialContract, and this is achieved through its customerType property. Ok, here's the hard part. I don't want the client to be able to set customerType, because just doing so will not remove the SpecialContract that applies to the Customer, which would be required. I would rather force the client to call a service method to remove the SpecialContract, which would also set the customerType to NOTSPECIAL all in one transaction. How can I hide the customerType setter from clients, but still expose it to my service layer class that will be responsible for setting the correct value and also removing the SpecialContract? My service class is not in the same package as the Customer class.
You could create an `Interface` that `Customer` implements, and pass an instance of this `Interface` to the client. This `Interface` would not expose the `contentType` modifier to the client. Your service would deal with full-fledged `Customer` objects and could use the `setContentType` modifier as defined in the `Class`.
Maybe aspect-oriented programming can be of some use here. You can intercept a call to a Customer that passes a Contract, have the before method advice instantiate a Special Contract subclass given certain conditions, and pass that to the method. You just have to design the Contract hierarchy so that it strictly observes the Liskov substitution principle. AOP could turn this into a bloody impossible mess, but it's a different way to think about it. You can add as many rules as you'd like and turn them off or on declaratively.
Enforce service layer business rules on entity property changes, or hide entity property from clients but not service?
[ "", "java", "oop", "" ]
I'm using ASP.Net MVC, but this applies to any framework. I'm making an Ajax call to my server, which most of the time returns plain old HTML, however if there is an error, I'd like it to return a JSON object with a status message (and a few other things). There doesn't appear to be a way for the `dataType` option in the jQuery call to handle this well. By default it seems to parse everything as html, leading to a `<div>` being populated with `"{ status: 'error', message: 'something bad happened'}"`. [Edit] Ignoring the `dataType` object and letting jQuery figure out doesn't work either. It views the type of the result as a `string` and treats it as HTML. One solution I came up with is to attempt to parse the result object as JSON. If that works we know it's a JSON object. If it throws an exception, it's HTML: ``` $.ajax({ data: {}, success: function(data, textStatus) { try { var errorObj = JSON.parse(data); handleError(errorObj); } catch(ex) { $('#results').html(data); } }, dataType: 'html', // sometimes it is 'json' :-/ url: '/home/AjaxTest', type: 'POST' }); ``` However, using an Exception in that way strikes me as pretty bad design (and unintuitive to say the least). Is there a better way? I thought of wrapping the entire response in a JSON object, but in this circumstance, I don't think that's an option. Here's the solution that I got from Steve Willcock: ``` // ASP.NET MVC Action: [AcceptVerbs(HttpVerbs.Post)] public ActionResult AjaxTest(int magic) { try { var someVal = GetValue(); return PartialView("DataPage", someVal); } catch (Exception ex) { this.HttpContext.Response.StatusCode = 500; return Json(new { status = "Error", message = ex.Message }); } } // jQuery call: $.ajax({ data: {}, success: function(data, textStatus) { $('#results').html(data); }, error: function() { var errorObj = JSON.parse(XMLHttpRequest.responseText); handleError(errorObj); }, dataType: 'html', url: '/home/AjaxTest', type: 'POST' }); ```
For your JSON errors you could return a 500 status code from the server rather than a 200. Then the jquery client code can use the error: handler on the $.ajax function for error handling. On a 500 response you can parse the JSON error object from the responseText, on a 200 response you can just bung your HTML in a div as normal.
While Steve's idea is a good one, I'm adding this in for completeness. It appears that if you specify a dataType of json but return HTML, jQuery handles it fine. I tested this theory with the following code: ``` if($_GET['type'] == 'json') { header('Content-type: application/json'); print '{"test":"hi"}'; exit; } else { header('Content-type: text/html'); print '<html><body><b>Test</b></body></html>'; exit; } ``` The `$_GET['type']` is just so I can control what to return while testing. In your situation you'd return one or the other depending on whether things went right or wrong. Past that, with this jQuery code: ``` $.ajax({ url: 'php.php?type=html', // return HTML in this test dataType: 'json', success: function(d) { console.log(typeof d); // 'xml' } }); ``` Even though we specified JSON as the dataType, jQuery (1.3.2) figures out that its not that. ``` $.ajax({ url: 'php.php?type=json', dataType: 'json', success: function(d) { console.log(typeof d); // 'object' } }); ``` So you could take advantage of this (as far as I know) undocumented behavior to do what you want.
jQuery AJAX and handling different dataTypes
[ "", "javascript", "jquery", "ajax", "" ]
Let's say I have a class which, internally, stores a List of data: ``` import java.util.List; public class Wrapper { private List<Integer> list; public Wrapper(List<Integer> list) { this.list = list; } public Integer get(int index) { return list.get(index); } } ``` For the sake of this example, pretend it's a useful and necessary abstraction. Now, here's my concern: As a programmer who knows the underlying implementation of this class, should I be specific about which type of List I ask for in the constructor? To demonstrate, I've made this test: ``` import java.util.List; import java.util.ArrayList; import java.util.LinkedList; public class Main { public static void main(String[] args) { long start; List<Integer> list1 = new ArrayList<Integer>(); List<Integer> list2 = new LinkedList<Integer>(); Wrapper wrapper1, wrapper2; for(int i = 0; i < 1000000; i++) { list1.add(i); list2.add(i); } wrapper1 = new Wrapper(list1); wrapper2 = new Wrapper(list2); start = System.currentTimeMillis(); wrapper1.get(500000); System.out.println(System.currentTimeMillis() - start); start = System.currentTimeMillis(); wrapper2.get(500000); System.out.println(System.currentTimeMillis() - start); } } ``` As you most likely know, randomly accessing an element takes a bit more time with a linked list as opposed to an array. So, going back to the Wrapper constructor, should I be general and allow for any type of List, or should I specify that the user pass an ArrayList to ensure the best possible performance? While in this example, it may be easy for the user to guess as to what the underlying implementation of the method *get* is, you could imagine that this was something more complex. Thanks in advance!
The whole point of interfaces is to allow for agnosticism about the underlying implementation. The very use of the List type as opposed to LinkedList or ArrayList is to allow general operations without having to worry about this kind of problem. As long as your code can be written without having to rely upon methods not exposed by List you don't need to worry. It is likely a user of this class is writing code that has other requirements on the type of list they use, they might be appending lots into the middle of the list for instance where a LinkedList excels. As such you should accept the most generic type possible and assume the user has a good reason for using that type. This isn't however to stop you perhaps including a javadoc comment that the use of an ArrayList might be better if there is no difference in any other use of the application.
> *So, going back to the Wrapper constructor, should I be general and allow for any type of List?* Is the intention of the wrapper to support any type of list? or only ArrayList? > *...or should I specify that the user pass an ArrayList to ensure the best possible performance?* If you leave the general List it will be just fine. You let the "client" of that class to decide whether or not he may use ArrayList. Is up to the client. You may also use the [RandomAccess](http://java.sun.com/javase/6/docs/api/java/util/RandomAccess.html) interface to reflect your intention, but since it is only a marker interface probably it wont make much sense. So again, leaving it as general List will be enough.
When to Be Specific About the Type of List You Want
[ "", "java", "list", "performance", "oop", "linked-list", "" ]
I'm maintaining a multiuser Access 2000 DB linked to an MSSQL2000 database, not written by me. The database design is very poor, so you'll have to bear with me. On the 'Customer' form there's a 'Customer\_ID' field that by default needs to get the next available customer ID, but the user has the option of overriding this choice with an existing customer ID. Now, the Customer\_ID field is not the PK of the Customer table. It's also not unique. If a customer calls twice to submit a job, the table will get two records, each with the same customer information, and the same customer ID. If a user creates a new ticket, Access does a quick lookup for the next available customer ID and fills it in. But it doesn't save the record. Obviously a problem - two users editing have to keep track of each others' work so they don't dupe up a customer ID. So I want to modify the "new record" button so it saves the ticket right after creating a new one. Problem is, when I test the change, I get "This record has been changed by another user since you started editing it". Definitely no other users on the DB. The 'other user' was presumably my forced save. Any ideas?
Take a look at your linked table in SQL Server 2000. Does it have a field containing the bit datatype? Access will give you this error message in a linked table scenario if you have a bit field **which does not have a default value**. It might not be what's wrong in your case, but I've experienced the same in an Access 2007 database and tracked the problem to a bit field with no default value.
I have seen this behaviour before and this fixed it for me: Try to add a TimeStamp field to the table (just add this field and update your linked tables. You do not need to fill this field with any kind of data).
Linked Access DB "record has been changed by another user"
[ "", "sql", "ms-access", "linked-tables", "" ]
We are starting a new ASP.NET MVC application and want to use an jQuery Ajax grid. I came across following options: * jqGrid (better than Flexigrid because it supports editable cells) * Flexigrid (looks better than jqGrid) * tablesorter * Ingrid * jqGridView * OTHERS? **Which is the best choice for jQuery Ajax grid ?** Which is the most popular jQuery grid/table ?
For flat view-only grids I would simply use a tablesorter. Once you configure your CSS properly, it can look great, support sorting, alternating colors, etc. If you need editing, I would go with jqGrid. I experienced several issues with Flexigrid and (as you can see) it is not that actively maintained. **jqGrid**, on the other hand, is being actively developed and inline with the jQuery UI components including themes support.
I am a fan of [jQuery tablesorter](http://tablesorter.com/docs/), out of the options you listed.
jQuery Ajax grid
[ "", "javascript", "jquery", "" ]
In PHP it is possible to specify argument types although they call it type hinting. I am implementing an interface where one of the functions specifies an array as the argument type: ``` function myFunction(array $argument){ } ``` I'd like to define a class, an instance of which can be used as the argument for this function. In other words it would extend ArrayObject or implement ArrayAccess or something along those lines. Is there a built in interface or abstract class that will work for this? (ArrayObject doesn't)
There isn't, but I'd suggest two alternatives: 1. Remove the *array* specifier and rather check within the function using is\_array and instanceof ArrayObject 2. Use (array) $ArrayObject when calling the routine or as part of 1. above. Example for *soulmerge* :-) ``` function myFunction(array $argument){ echo var_export($argument,true); } $a = new ArrayObject(); $a[] = 'hello'; $a[] = 'and goodbye'; myFunction((array)$a); ``` outputs ``` array ( 0 => 'hello', 1 => 'and goodbye', ) ```
This isn't possible. `array()` is not an object of any class. Hence, it can't implement any interface (see [here](http://bugs.php.net/bug.php?id=41942)). So you can't use an object and an array interchangeably. The solution strongly depends on what you'd like to achieve. Why don't you change the function signature to allow only `ArrayObject`s, `ArrayIterator`s, `ArrayAccess`s, `IteratorAggregate`s, `Iterator`s or `Traversable`s (depending on what you'd like to do inside the function)? If you have to rely on interation-capabilities of the passed object you should use `Traversable` as the type-hint. This will ensure that the object can be used with `foreach()`. If you need array-like key-access to the object (e.g. `$test['test']`) you should use `ArrayAccess` as the type-hint. But if you need the passed object to be of a specific custom type, use the custom type as the type-hint. Another option would be to not use a type-hint at all and determine the type of the passed argument within the function body and process the argument accordingly (or throw an `InvalidArgumentException` or something like that). ``` if (is_array($arg)) { ... } else if ($arg instanceof Traversable) { ... } else if ($arg instanceof ArrayAccess) { ... } else { throw new InvalidArgumentException('...'); } ```
Implement PHP interface such that object instance can be passed as array type argument?
[ "", "php", "interface", "" ]
How can I get battery status through J2ME ?
Well, the only standard way of doing this is through JSR-256. The mobile Sensor API. You can read the specifications from <http://www.jcp.org/en/jsr/detail?id=256> Unfortunately it is very recent and not actually implemented in most retail phones yet. When it ships, the Sony Ericsson Satio (or Idou) will have it. Edit: Nokia N97 has JSR-256 and it can be installed on Nokia N85 and Nokia 5800. Edit: [Here's Attilah's other JSR-256 question with some code in the answer.](https://stackoverflow.com/questions/950172/jsr-256-battery-events/951223#951223)
I am not sure there is a generic way through J2ME alone. With [Nokia and its properties](http://wiki.forum.nokia.com/index.php/TSJ000306_-_MIDP:_System_properties), you can ([Get Battery Level in J2ME](http://discussion.forum.nokia.com/forum/showthread.php?t=132313)): ``` System.getProperty("com.nokia.mid.batterylevel"); ``` --- The generic property, [as illustrated here](http://www.discussweb.com/j2me/2430-there-possible-getting-battery-level-mobile-using-j2me.html), does not always work (can return null) > Some of the system properties may return null as they may not be supported on early devices and some system properties require the MIDlet to be trusted otherwise return null... ``` import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import javax.microedition.location.*; public class HelloMidp extends MIDlet implements CommandListener { private Command exitCommand; Display display; Form mainForm; public HelloMidp () { exitCommand = new Command("Exit", Command.EXIT, 1); mainForm = new Form ("HelloMidp"); String batt = System.getProperty("batterylevel"); mainForm.append (batt); } protected void startApp() { mainForm.addCommand(exitCommand); mainForm.setCommandListener(this); Display.getDisplay(this).setCurrent(mainForm); } protected void pauseApp() {} protected void destroyApp(boolean bool) {} public void commandAction(Command cmd, Displayable disp) { if (cmd == exitCommand) { destroyApp(false); notifyDestroyed(); } } } ```
Get battery status from J2ME
[ "", "java", "java-me", "" ]
Are there any preexisting Maven plugins or commands to update the dependencies in the POM? Example: (if this was in my POM) ``` <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.3</version> </dependency> ``` Is there a command or plugin I can run to get it to update the dependency to: ``` <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.4</version> </dependency> ```
Try the [maven-versions-plugin](http://www.mojohaus.org/versions-maven-plugin/), in particular, the [versions:use-latest-versions](http://www.mojohaus.org/versions-maven-plugin/use-latest-versions-mojo.html) goal.
I prefer using [mvn versions:display-dependency-updates](http://www.mojohaus.org/versions-maven-plugin/display-dependency-updates-mojo.html); this generates a report of which dependencies can be upgraded, but lets you modify the POMs yourself. There's also a *display-plugin-updates* command for plugins.
Maven update dependencies in POM
[ "", "java", "maven-2", "plugins", "command", "" ]
I'm dabbling in clojure and am having a little trouble trying to determine the clojure (and / or Lisp) equivalent of this common python idiom. The idiom is that at the bottom of a python module there is often a bit of test code, and then a statement which runs the code, for example: ``` # mymodule.py class MyClass(object): """Main logic / code for the library lives here""" pass def _runTests(): # Code which tests various aspects of MyClass... mc = MyClass() # etc... assert 2 + 2 == 4 if __name__ == '__main__': _runTests() ``` This is useful for simple, ad-hoc testing. One would normally use this module by writing `from mymodule import MyClass`, in which case `_runTests()` is never called, but with the snippet at the end, one can also run it by typing `python mymodule.py` directly from the command line. Is there an equivalent idiom in Clojure (and/or common lisp)? I'm not after a full-blown unit testing library (well, I am, but not in this question), I'd just like to include some code in a module which will only be run under some circumstances, so I can have a quick way to run code I've been working on but still allow my file to be imported like a normal module / namespace.
It's not idiomatic to run Clojure scripts over and over from the command line. The REPL is a better command line. Clojure being a Lisp, it's common to fire up Clojure and leave the same instance running forever, and interact with it rather than restart it. You can change functions in the running instance one at a time, run them and poke them as needed. Escaping the tedious and slow traditional edit/compile/debug cycle is a great feature of Lisps. You can easily write functions to do things like run unit tests, and just call those functions from the REPL whenever you want to run them and ignore them otherwise. It's common in Clojure to use `clojure.contrib.test-is`, add your test functions to your namespace, then use `clojure.contrib.test-is/run-tests` to run them all. Another good reason not to run Clojure from the commandline is that the startup time of the JVM can be prohibitive. If you really want to run a Clojure script from the command line, there are a bunch of ways you can do it. See [the Clojure mailing list](http://groups.google.com/group/clojure/browse_thread/thread/ca60d98fb4f7e71e/ddc68367d4fa1bc7) for some discussion. One way is to test for the presence of command line arguments. Given this `foo.clj` in the current directory: ``` (ns foo) (defn hello [x] (println "Hello," x)) (if *command-line-args* (hello "command line") (hello "REPL")) ``` You'll get different behavior depending how you start Clojure. ``` $ java -cp ~/path/to/clojure.jar:. clojure.main foo.clj -- Hello, command line $ java -cp ~/path/to/clojure.jar:. clojure.main Clojure 1.1.0-alpha-SNAPSHOT user=> (use 'foo) Hello, REPL nil user=> ``` See `src/clj/clojure/main.clj` in the Clojure source if you want to see how this is working. Another way is to compile your code into `.class` files and invoke them from the Java command line. Given a source file `foo.clj`: ``` (ns foo (:gen-class)) (defn hello [x] (println "Hello," x)) (defn -main [] (hello "command line")) ``` Make a directory to store the compiled `.class` files; this defaults to `./classes`. You must make this folder yourself, Clojure won't create it. Also make sure you set `$CLASSPATH` to include `./classes` and the directory with your source code; I'll assume `foo.clj` is in the current directory. So from the command line: ``` $ mkdir classes $ java -cp ~/path/to/clojure.jar:./classes:. clojure.main Clojure 1.1.0-alpha-SNAPSHOT user=> (compile 'foo) foo ``` In the `classes` directory you will now have a bunch of `.class` files. To invoke your code from the command line (running the `-main` function by default): ``` $ java -cp ~/path/to/clojure.jar:./classes foo Hello, command line. ``` There's a lot of information about compiling Clojure code on [clojure.org](http://clojure.org/compilation).
I'm very new to Clojure but I think [this discussion](http://groups.google.com/group/clojure/browse_thread/thread/d3c2c328787c328f/8c8c526fee2d6deb?lnk=gst&q=clojure+python+__name__#8c8c526fee2d6deb) on the Clojure groups may be a solution and/or workaround, specifically the post by Stuart Sierra on April 17th at 10:40 PM.
What is the clojure equivalent of the Python idiom "if __name__ == '__main__'"?
[ "", "python", "lisp", "clojure", "idioms", "" ]
I'm trying to use Twitter's API and OAuth to send status updates (new Tweets). I am using Shannon Whitley .NET code example <http://www.voiceoftech.com/swhitley/?p=681> (as recommended on the Twitter API docs). I can read (GET) using OAuth just fine, however when I try to send a status update via http ://twitter.com/statuses/update.xml (using a POST), it returns a 401 with the following XML: ``` <?xml version="1.0" encoding="UTF-8"?> <hash> <request>/statuses/update.xml</request> <error>Read-only application cannot POST</error> </hash> ``` I swear I have set up my application to use read and write, the authorise page at Twitter (http ://twitter.com/oauth/authorize) even says *"The application TweeVerbs.com (Development) by would like the ability to **access and update** your data on Twitter."* Yet it's still saying "Read-only application cannot POST". WTF!? I have googled this error message until I was blue in the face. I found somewhere that said to add the querystring paremeter *oauth\_access\_type=write* to the redirect URL which goes to the Twitter authorise page which I have done, but it still gives me a 401. --- If it helps, here is the data that is getting sent back and firth as per the OAuth workflow: **Request Authorise Token:** http ://twitter.com/oauth/request\_token?oauth\_consumer\_key=tViV8vAt4cqSKbGdPGWT7Q&oauth\_nonce=2790042&oauth\_signature\_method=HMAC-SHA1&oauth\_timestamp=1244567068&oauth\_version=1.0&oauth\_signature=KzxcXN%2bQ0AJoAJ%2flQfzs8SLjC%2fQ%3d **Generated Authorize Redirect URL:** http ://twitter.com/oauth/authorize?oauth\_token=EpyBg3nJGOmtmBjRUAsqqaGHARb2F2F2VcccqHkwio&oauth\_access\_type=write **Authorise Screen Message:** *"The application TweeVerbs.com (Development) by would like the ability to access and update your data on Twitter. This application plans to use Twitter for logging you in in the future. Sign out if you want to connect to an account other than Sironfoot."* **Get Access Token:** http ://twitter.com/oauth/access\_token?oauth\_consumer\_key=tViV8vAt4cqSKbGdPGWT7Q&oauth\_nonce=2016804&oauth\_signature\_method=HMAC-SHA1&oauth\_timestamp=1244567166&oauth\_token=EpyBg3nJGOmtmBjRUAsqqaGHARb2F2F2VcccqHkwio&oauth\_version=1.0&oauth\_signature=%2bEVQUxUPLT%2b%2bkfaG0Vq1YJZXcAw%3d **Status Update API call:** **URL** - http ://twitter.com/statuses/update.xml **POST data** - oauth\_consumer\_key=tViV8vAt4cqSKbGdPGWT7Q&oauth\_nonce=5707692&oauth\_signature\_method=HMAC-SHA1&oauth\_timestamp=1244567268&oauth\_token=19130957-nb89DjZhjCAzcbHUa96yRWHqlQFQIJ0AKyXpqnHt1&oauth\_version=1.0&status=HelloWorld&oauth\_signature=WqA%2bWY0IxveeSJ7G3Ewy3whh1sE%3d
I don't know what the problem was, but I deleted my Application registration on Twitter (You have to register apps in Twitter to get OAuth keys etc.), and then recreated it. Now it works fine. Weird, probably a problem with Twitter screwing up. I'm also using Tweetsharp (<http://tweetsharp.com/>), highly recommend it, it's got a nice fluent API. Note: switching over to Tweetsharp wasn't the fix, I had already switched over and had the same problem until I delete and recreated app registration on Twitter.
If you authorized your application to access your Twitter account when the application was set in "read only access" mode and you get the "Read-only application cannot POST" error after changing the application settings to be "read and write access" then you have to revoke access to the application on <https://twitter.com/settings/connections> and then reauthorize it. The "read only" access\_token tends to be sticky until you revoke it.
Twitter API + OAuth: Can't send status updates, getting 401
[ "", "c#", "asp.net", "oauth", "twitter", "" ]
I'm trying to find a practical unit testing framework for JSF. I know about JSFUnit, but this is very impractical to me. I need to include about 10 JARs to my project, and jump through many other hoops just to get it running. I realize that -- due to the need to simulate a platform and a client -- unit testing web applications is difficult. But is there a better way?
Have you thought about doing integration testing with [Selenium](http://seleniumhq.org/) or another tool? Selenium allows you to record and run tests directly in the browser. You can also run tests in multiple browsers and on multiple platforms with [Selenium Remote Control](http://seleniumhq.org/projects/remote-control/). Writing unit tests is good, but it might provide more to create some functional integration tests rather than unit-testing the presentation layer code.
On the project I'm working on at the moment we dabbled with using selenium. We actually spent a lot of time writing these selenium tests, but found that they added little value because the UI changes so much and you just end up doubling your effort for very little return on investment. Another problem with selenium is that it requires your code to be deployed, which means it doesn't play well with unit test frameworks eg maven. What I would say is that writing really good unit tests for your managed beans is invaluable.
JSF unit testing
[ "", "java", "unit-testing", "jsf", "junit", "jsfunit", "" ]
I'm working with a mess of HTML markup. In order to get reliable matches I have resorted to explicitly querying a chain of elements using the ['>' operator](http://docs.jquery.com/Selectors/child). For this question I am attempting to select the parent of an explicit chain of descendents. For example, I'd like to select the table element with class 'toolbar' in the following HTML: ``` <table class='toolbar'> <tbody> <tr> <td class='button'> ... </td> </tr> </tbody> </table> ``` Here is what I've tried: **1. Use 'has'** ``` $("table.toolbar:has(tbody > tr > td.button)") ``` Here elements are matched even if tbody isn't a direct descendent of table so this doesn't reliably work. **2. Use '>' and parent()** ``` $("table.toolbar > tbody > tr > td.button").parent().parent().parent() ``` This works but is messy. Also have to make sure the correct number of parent() calls are included. **3. ???** Due to the crap HTML, it is critical that elements are explicitly given in the query as **one direct descendent beneath another**. Can anyone please help with the nicest way of doing this? *Thanks!*
``` $("table.toolbar > tbody > tr > td.button").closest("table.toolbar") ``` Still a bit messy but should work. * [closest(expr) documentation](http://docs.jquery.com/Traversing/closest)
``` $("td.button").parents("table.toolbar") ``` seems the easiest way.
How can I elegantly select a parent including its set of direct descendents?
[ "", "javascript", "jquery", "" ]
I have the following code in a sample file: ``` #include "SkCanvas.h" #include "SkDevice.h" #include "SkGLCanvas.h" #include "SkGraphics.h" #include "SkImageEncoder.h" #include "SkPaint.h" #include "SkPicture.h" #include "SkStream.h" #include "SkWindow.h" ``` However, this code is located in various folders within /home/me/development/skia (which includes core/ animator/ images/ ports/ svg/ and a lot more.) How can I make GCC recognize this path?
Try `gcc -c -I/home/me/development/skia sample.c`.
The `-I` directive does the job: ``` gcc -Icore -Ianimator -Iimages -Ianother_dir -Iyet_another_dir my_file.c ```
How to include header files in GCC search path?
[ "", "c++", "gcc", "header", "" ]
I have a little problems understand what's going on behind the scenes of the "type T" to get this right, I'm hopping that some of you can show me a light at the end of the tunnel :) I have a [COM object](http://www.bcltechnologies.com) that I assign almost the some things (properties) but I need to use this for all objects, and I want to do this once and only that will work with all types. Printer type: ``` switch (type) { case convert2pdf.ConvertFileType.Word: WordPrintJob oPrintJob = null; break; case convert2pdf.ConvertFileType.Excel: ExcelPrintJob oPrintJob = null; break; case convert2pdf.ConvertFileType.PowerPoint: PowerPointPrintJob oPrintJob = null; break; case convert2pdf.ConvertFileType.IE: IEPrintJob oPrintJob = null; break; case convert2pdf.ConvertFileType.Publisher: PublisherPrintJob oPrintJob = null; break; case convert2pdf.ConvertFileType.Visio: VisioPrintJob oPrintJob = null; break; default: GenericPrintJob oPrintJob = null; break; } ``` and then, no matter what my object type that I created, I implement every time this: ``` PDFSetting oPDFSetting = null; oPrintJob = oPrinter.GenericPrintJob; oPDFSetting = oPrintJob.PDFSetting; /*put water mark on the first page, set the water mark text to "BCL EasyPDF */ oPDFSetting.set_Watermark(0, true); oPDFSetting.set_WatermarkColor(0, (uint)System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Blue)); oPDFSetting.set_WatermarkFirstPageOnly(0, true); oPDFSetting.set_WatermarkText(0, "EasyPDF"); /*set the meta data for the pdf file*/ oPDFSetting.MetaData = true; oPDFSetting.MetaDataAuthor = "Your Name"; oPDFSetting.MetaDataCreator = "BCL"; oPDFSetting.MetaDataKeywords = "PDF"; oPDFSetting.MetaDataSubject = "Converter"; oPDFSetting.MetaDataTitle = "easyPDF SDK"; ``` How do I use the "type T" thingy (men... after 3 years of C# I still can't understand that no matter what I read, and I read Wikipedia, ASP.NET 3.5 Professional book, tutorials, ...) :( In other words is, how can I reuse the properties. I thought about creating an ExtensionMethod, but I will have to write all of them and not reuse any code... I thought about Creating a Generic control and create a new controls that inherit that base one so I could use ``` GlocalObject oPrintJob = null; ``` ... ``` WordPrintJob oPrintJob = (WordPrintJob)GlocalObject; ``` am I making any sense? --- **Update from the answers** Ok, so, there is no "type T" but base class/interface... I'm then trying to create that Interface so I can inherit from it and I get this image below: [alt text http://www.balexandre.com/temp/2009-06-02\_1521\_soQuestion\_Interface.png](http://www.balexandre.com/temp/2009-06-02_1521_soQuestion_Interface.png) If in the interface I say PrintJob type, how can I return a WordPrintJob type? :-( I don't get it ...
You'll need to define a base class `PrintJob` and have `PDFSetting` as a property of that. Then define `WordPrintJob`, `ExcelPrintJob` etc. to be subclasses of `PrintJob`. It's a long time since I've done this so I can't remember off hand whether you'll be able to access `PDFSettings` from the sub class or if you'll have to cast the variable to the base class first.
Chris is essentially correct so your switch statement would look thus:: ``` PrintJob oPrintJob = null; switch (type) { case convert2pdf.ConvertFileType.Word: oPrintJob = new WordPrintJob(); break; case convert2pdf.ConvertFileType.Excel: oPrintJob = new ExcelPrintJob(); break; case convert2pdf.ConvertFileType.PowerPoint: oPrintJob = new PowerPointPrintJob(); break; case convert2pdf.ConvertFileType.IE: oPrintJob = new IEPrintJob(); break; case convert2pdf.ConvertFileType.Publisher: oPrintJob = new PublisherPrintJob(); break; case convert2pdf.ConvertFileType.Visio: oPrintJob = new VisioPrintJob(); break; default: oPrintJob = new GenericPrintJob(); break; } ``` The PDFSettings property would be defined in your base PrintJob class and each of the specific print job classes would inherit from that base class.
How to reuse the same variable, but for different types?
[ "", "c#", "inheritance", "types", "" ]
I've created a pagination script that takes a long block of text and breaks it into pages. First, the text is loaded into a div with the id `#page`. Then the script measures the height of `#page` and calculates how many pages it should be broken into to fit into the `div` with class `.detailsholder`. The div .detailsholder is cleared out, and the appropriate number of page divs are added inside. (Each one actually has the entire text of #page inside, but the top margin is set negatively, the height is fixed, and overflow is set to hidden, so only the proper amount appears.) And it works great, except for this: while Safari and Firefox on the Mac work perfectly, IE and Firefox on Windows add an extra page. Because of the way the pages are created, as described above in parentheses, the last page appears blank -- the text is shifted too far up to appear in the page `window`. Here's the code. I'm using jQuery, as you can see. ``` var descHeight = $('#page').outerHeight(); if (descHeight > 250 ) { var numberOfPages = Math.round(descHeight/210)+1; //Figure out how many pages var artistText = $('#page').html(); //Grab the text into a variable $('.detailsholder').empty(); //Empty the container so we can fill //it with pages for (i=0;i<=numberOfPages-1;i++) { //Each page has the entire text //content, but is shifted up and var shiftUp = 0-(210 * i); //cut off at the bottom. $('.detailsholder').append('<div id="page' + (i+1) + '" class="page" style="height:225px;"><div style="border:dotted 1px red;margin-top:' + shiftUp + 'px"' + artistText + '</div>'); } } ``` Thanks!
I see one problem in the algorithm. `Math.round` should be `Math.floor` in order to give the correct number of pages. In order to see why assume that `descHeight` is `400`. Then you would need only 2 pages of height `210` each, but `Math.round(400/210) + 1 == 3`. Could it be that a combination of this problem together with a different standard font size between platforms (which will probably affect `descHeight` and trigger the problem) is the reason for the behaviour you observe?
Have you tried it across similar platformed computers with different resolution/font settings? I think this problem might have more to do with display settings and the CSS part of your Javascript then platform differences. My CSS isn't great, but you may want to avoid px and try to use a % instead. **The following might help with your diagnostics:** * <http://browsersize.com/> * [Firebug](http://getfirebug.com/) (for Firefox) * [Developer Toolbar](http://www.microsoft.com/en-us/download/details.aspx?id=18359) (for IE) * [Web Inspector](http://macdevelopertips.com/safari/firebug-like-tools-in-safari.html) (for Safari, haven't personally tried this one)
JavaScript behaving differently on Mac and PC? I know it shouldn't
[ "", "javascript", "css", "windows", "macos", "browser", "" ]
This is the well know select algorithm. see <http://en.wikipedia.org/wiki/Selection_algorithm>. I need it to find the median value of a set of 3x3x3 voxel values. Since the volume is made of a billion voxels and the algorithm is recursive, it better be a little bit fast. In general it can be expected that values are relatively close. The fastest known algorithm I have tried out so far uses the quick sort partition function. I would like to know if there is a faster one. I've "invented" a 20% faster one using two heaps, but expected an even faster one using a hash. Before implementing this, I'd like to know if a blitz fast solution already exist out there. The fact that I'm using floats shouldn't matter since they can be considered as unsigned integer after inverting the sign bit. The order will be preserved. EDIT: benchmark and source code moved into a separate answer as suggested by Davy Landman. See below for the answer by chmike. **EDIT**: The most efficient algorithm so far was referenced below by Boojum as a link to the [Fast Median and Bilateral Filtering](http://www.shellandslate.com/fastmedian.html) paper which is now the answer to this question. The first smart idea of this method is to use radix sort, the second is to combine median search of adjacent pixels who share a lot of pixels.
Since it sounds like you're performing a median filter on a large array of volume data, you might want to take a look at the [Fast Median and Bilateral Filtering](http://www.shellandslate.com/fastmedian.html) paper from SIGGRAPH 2006. That paper deals with 2D image processing, but you might be able to adapt the algorithm for 3D volumes. If nothing else, it might give you some ideas on how to step back and look at the problem from a slightly different perspective.
The selection algorithm is linear time (O(n)). Complexity-wise you can't do better than linear time, because it takes linear time to read in all the data. So you couldn't have made something that is faster complexity-wise. Perhaps you have something that is a constant factor faster on certain inputs? I doubt it would make much of a difference. C++ already includes the linear-time selection algorithm. Why not just use it? ``` std::vector<YourType>::iterator first = yourContainer.begin(); std::vector<YourType>::iterator last = yourContainer.end(); std::vector<YourType>::iterator middle = first + (last - first) / 2; std::nth_element(first, middle, last); // can specify comparator as optional 4th arg YourType median = *middle; ``` Edit: Technically, that is only the median for a container of odd length. For one of even length, it will get the "upper" median. If you want the traditional definition of median for even length, you might have to run it twice, once for each of the two "middles" at `first + (last - first) / 2` and `first + (last - first) / 2 - 1` and then average them or something.
Fastest code C/C++ to select the median in a set of 27 floating point values
[ "", "c++", "c", "algorithm", "optimization", "" ]
I need help with my code. I would like to write only numbers/integers in my textbox and would like to display that in my listbox. Is my code below in order? This seems to give an error. ``` int yourInteger; string newItem; newItem = textBox1.Text.Trim(); if (newItem == Convert.ToInt32(textBox1.Text)) { listBox1.Items.Add(newItem); } ``` ==== Update: This is how my code looks like now. My question is, can listBox handle the data type "long"? Because when I entered the number 20,000,000 I just got an hour glass for 20 minutes. But when I tried this one with the console, I got the answer. So I'm not sure what kind of element can handle data type "long". ``` string newItem; newItem = textBox1.Text.Trim(); Int64 num = 0; if(Int64.TryParse(textBox1.Text, out num)) { for (long i = 2; i <= num; i++) { //Controls if i is prime or not if ((i % 2 != 0) || (i == 2)) { listBox1.Items.Add(i.ToString()); } } } private void btnClear_Click(object sender, EventArgs e) { listBox1.Items.Clear(); } ```
Use this: ``` int yourInteger; string newItem; newItem = textBox1.Text.Trim(); Int32 num = 0; if ( Int32.TryParse(textBox1.Text, out num)) { listBox1.Items.Add(newItem); } else { customValidator.IsValid = false; customValidator.Text = "You have not specified a correct number"; } ``` This assumes you have a customValidator.
``` int result = int.Parse(textBox1.Text.Trim()); ``` If you want to check for validity: ``` int result; if (int.TryParse(textBox1.Text.Trim(), out result)) // it's valid integer... // int is stored in `result` variable. else // not a valid integer ```
Convert string to integer
[ "", "c#", ".net", "string", "integer", "" ]
What is the best/most elegant way to abstract out the conversion of units of measures in the client, based on a user-preferred unit of measure setting? For example, let's say user A's preferred unit of measure is "metric", while user's B's preference is "imperial". Now lets say I've calculated the area of something in meters squared. When I go to display the value I need to use different conversion factors for each user (eg, "1 meter = 1.09361 yards"). Or say I've calculated the fluid volume in `mL`. User B's view will get calculated using the conversion "236.588237 mL = 1 US cup". Is there an existing javascript library that anyone here knows about that handles these trivial UOM conversions?
Here's a little script I threw together just for the heck of it. It handles all the SI conversions for grams, bytes, meters and liters, and also I've added ounces and pounds as an example of non-SI units. To add more, you'll need to: 1. Add the base type to the "units" list for items that follow SI or 2. Add the conversion ratios for items that don't follow SI Usage: ``` $u(1, 'g').as('kg').val(); // converts one gram to kg ``` You can get the value out with .val(), a string representation using .toString() or the full details via .debug() ``` (function () { var table = {}; window.unitConverter = function (value, unit) { this.value = value; if (unit) { this.currentUnit = unit; } }; unitConverter.prototype.as = function (targetUnit) { this.targetUnit = targetUnit; return this; }; unitConverter.prototype.is = function (currentUnit) { this.currentUnit = currentUnit; return this; }; unitConverter.prototype.val = function () { // first, convert from the current value to the base unit var target = table[this.targetUnit]; var current = table[this.currentUnit]; if (target.base != current.base) { throw new Error('Incompatible units; cannot convert from "' + this.currentUnit + '" to "' + this.targetUnit + '"'); } return this.value * (current.multiplier / target.multiplier); }; unitConverter.prototype.toString = function () { return this.val() + ' ' + this.targetUnit; }; unitConverter.prototype.debug = function () { return this.value + ' ' + this.currentUnit + ' is ' + this.val() + ' ' + this.targetUnit; }; unitConverter.addUnit = function (baseUnit, actualUnit, multiplier) { table[actualUnit] = { base: baseUnit, actual: actualUnit, multiplier: multiplier }; }; var prefixes = ['Y', 'Z', 'E', 'P', 'T', 'G', 'M', 'k', 'h', 'da', '', 'd', 'c', 'm', 'u', 'n', 'p', 'f', 'a', 'z', 'y']; var factors = [24, 21, 18, 15, 12, 9, 6, 3, 2, 1, 0, -1, -2, -3, -6, -9, -12, -15, -18, -21, -24]; // SI units only, that follow the mg/kg/dg/cg type of format var units = ['g', 'b', 'l', 'm']; for (var j = 0; j < units.length; j++) { var base = units[j]; for (var i = 0; i < prefixes.length; i++) { unitConverter.addUnit(base, prefixes[i] + base, Math.pow(10, factors[i])); } } // we use the SI gram unit as the base; this allows // us to convert between SI and English units unitConverter.addUnit('g', 'ounce', 28.3495231); unitConverter.addUnit('g', 'oz', 28.3495231); unitConverter.addUnit('g', 'pound', 453.59237); unitConverter.addUnit('g', 'lb', 453.59237); window.$u = function (value, unit) { var u = new window.unitConverter(value, unit); return u; }; })(); console.log($u(1, 'g').as('kg').debug()); console.log($u(1, 'kg').as('g').debug()); console.log($u(1, 'g').as('mg').debug()); console.log($u(1, 'mg').as('g').debug()); console.log($u(1, 'mg').as('kg').debug()); console.log($u(1, 'g').as('oz').debug()); console.log($u(1, 'g').as('lb').debug()); console.log($u(1, 'oz').as('lb').debug()); console.log($u(1, 'lb').as('g').debug()); // this last one throws an exception since you can't convert liters to mg console.log($u(1, 'l').as('mg').debug()); ``` I've moved this to a small repo on Github so if anyone wants to improve/enhance they can do so: <https://github.com/jerodvenemafm/jsunitconverter>
You might check out this port of Ruby Units to Javascript: <https://github.com/gentooboontoo/js-quantities>
Unit of Measure Conversion Library
[ "", "javascript", "" ]
I am thinking of implementing an easy Instant Messaging server in Java, but I don't want to create yet another protocol, but instead use an already simple IM-protocol. But I don't know which protocol I should use. The reason Why I want to use an already existing IM-protocol, is that I would like my 'users' to be able to use their own clients, for example pidgin - which already offers a wide spread of protocols, such as XMPP, Simple, Bonjour, etc - and I don't have to develop any clients. I have looked a bit a XMPP but it since a lot of work embed that protocol into a new server. Maybe there are other protocols that are easier to use? My questions is, do you guys have any suggestions of protocols that are real basic and easy to use in Java? Pidgin supports a whole bunch of protocols, but which protocols are relevant for me?
XMPP is widely used and has standards backing behind it. It is pretty easy to use if you use an existing library - there are many client libraries for it in many languages. The google says there are [many in java](http://www.google.com/search?&q=xmpp+java+library). An advantage of using XMPP is that your server can act as a gateway to all the other Xmpp/Jabber servers on the net, so your users can talk in & out of your network - like to people logged into GoogleTalk, using standard JID addresses, like bob@yourhost.com/desktop.
For the widest support I would go with XMPP/Jabber. There's no other choice really.
Looking for easy Instant Messaging protocol for own IM-server/service in in Java
[ "", "java", "xmpp", "instant-messaging", "" ]
(Leaving aside hair-splitting about if this is integration-testing or unit-testing.) I would rather first test at the large scale. If my app writes a VRML file that is the same as the reference one then the VRML exporter works, I don't then have to run unit tests on every single statement in the code. I would also like to use this do some level of poor-man gui testing by comparing screenshots. Is there a unit test framework (for C++ ideally) that integrates this sort of testing - or at least makes it easy to integrate with unit tests? edit. It seems a better term is approval testing. So are there any other unit test frameworks that incorporate Approval Testing ?
Have a look at [Approval Tests](http://blog.approvaltests.com/), written by a couple of friends of mine. Not C++, but it's the general idea of what you're after, also known as Golden Master tests. Good stuff, whether it's unit tests or not.
Kitware, for VTK, uses [CDash](http://cdash.org/) to do most of its testing. Many of its tests are similar in nature to this - they write out an image of the rendered model, and compare it to a reference image. In addition, they have code in there to specifically handle very subtle differences to the reference image due to different graphics card drivers/manufacturers/etc. The tests can be written in a way to compare the reference image with some tolerance.
Unit testing , approval testing and datafiles
[ "", "c++", "unit-testing", "" ]
I want to left join TableA to TableB where a certain condition in tableA is true So I do this type of SQL query ``` Select * from TableA Left Join TableB on TableA.fld1 = TableB.fld2 where TableA.fld3 = True ``` This works OK. Now however I want to do the Join only with certain records in TableB, ie those records in TableB where a certain condition is met, specifically *fld4* has **false** as its value. The reason I want to do this is I want to know which rows in tableA don't have a match in tableB among the rows in tableB where *fld4* is **false**. If I was to delete all the rows in TableB where *fld4* is **true** and run the above query I'd get the correct result. All I'd need to do is find the rows in the resultant recordset with null in some cell. But if instead of deleting rows from TableB first I alter the query to the one below I get no rows at all returned ``` Select * from TableA Left Join TableB on TableA.fld1 = TableB.fld2 where TableA.fld3 = True and TableB.fld4 = false ``` If my ramblings make sense can someone tell me what I'm doing wrong? Thanks
Put it in the join clause: ``` select * from TableA left join TableB on TableA.fld1 = TableB.fld2 and TableB.fld4 = False where TableA.fld3 = True ``` Edit: ah, I missed this: > I want to know which rows in tableA don't have a match in tableB among the rows in tableB where fld4 is false. Joel's query would work, but since you are not interested in any rows from TableB, a correlated subquery may be cleaner: ``` select * from TableA where TableA.fld3 = True and not exists ( select * from TableB where TableA.fld1 = TableB.fld2 and TableB.fld4 = False ) ```
You should put the condition in the join clause. When you have a where clause that filters rows on the "right" side of a left join query, you ultimately exclude rows. Try this: ``` Select * from TableA Left Join TableB on TableA.fld1 = TableB.fld2 and TableB.fld4 = false where TableA.fld3 = True ```
TableA Left Join (a subset of) Table B
[ "", "sql", "" ]
I am working on a Python project that includes a lot of simple example scripts to help new users get used to the system. As well as the source code for each example, I include the output I get on my test machine so users know what to expect when all goes well. It occured to me that I could use this as a crude form of unit testing. Automatically run all the example scripts and do a load of diffs against the expected output. All of my example scripts end with extension .py so I can get their filenames easily enough with something like ``` pythonfiles=[filename for filename in os.listdir(source_directory) if filename[-3:]=='.py'] ``` So, pythonfiles contains something like ['example1.py', 'cool\_example.py'] and so on. What syntax can I use to actually run the scripts referenced in this list?
You could leverage [doctest](http://docs.python.org/library/doctest.html) to help you get this done. Write a method that executes each script, and in the docstring for each method you paste the expected output: ``` def run_example1(): """ This is example number 1. Running it should give you the following output: >>> run_example1() "This is the output from example1.py" """ os.system('python example1.py') # or you could use subprocess here if __name__ == "__main__": import doctest doctest.testmod() ``` Note I haven't tested this. Alternatively, as Shane mentioned, you could use subprocess. Something like this will work: ``` import subprocess cmd = ('example1.py', 'any', 'more', 'arguments') expected_out = """Your expected output of the script""" exampleP = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) out, err = exampleP.communicate() # out and err are stdout and stderr, respectively if out != expected_out: print "Output does not match" ```
You want to use the [subprocess module](http://docs.python.org/library/subprocess.html#module-subprocess).
Running a set of Python scripts in a list
[ "", "python", "" ]
I am looking to implement "like" functionallity a bit similar as they do in [friendfeed](http://friendfeed.com). Is there a django reusable app that already does this? Thanks! Nick.
This sort of thing you should just write yourself from scratch. A 'like' in its most basic form is going to be an object with relations to a user and some other object. Look at the [contenttypes framework](http://docs.djangoproject.com/en/dev/ref/contrib/contenttypes/) docs to see how to use generic foreign keys for this. The only other thing you need to worry about is to make the create view idempotent. If you're new to django this is probably a fun little exercise to familiarise yourself with contenttypes. If you're not new, the whole app should take you less than an hour. I wouldn't go searching for a pluggable app either way.
You could put your own together using parts of [Pinax](http://pinaxproject.com/). There isn't one app that would do this for you as it's too specific and reusable Django apps are supposed to be very focussed.
Django reusable app for like functionality as in friendfeed
[ "", "python", "django", "" ]
I have written a c++ program , I want to know how to calculate the time taken for execution so I won't exceed the time limit. ``` #include<iostream> using namespace std; int main () { int st[10000],d[10000],p[10000],n,k,km,r,t,ym[10000]; k=0; km=0; r=0; scanf("%d",&t); for(int y=0;y<t;y++) { scanf("%d",&n); for(int i=0;i<n;i++) { cin>>st[i] >>d[i] >>p[i]; } for(int i=0;i<n;i++) { for(int j=i+1;j<n;j++) { if((d[i]+st[i])<=st[j]) { k=p[i]+p[j]; } if(k>km) km=k; } if(km>r) r=km; } ym[y]=r; } for( int i=0;i<t;i++) { cout<<ym[i]<<endl; } //system("pause"); return 0; } ``` this is my program and i want it to be within time limit 3 sec !! how to do it ? yeah sorry i meant execution time !!
If you have cygwin installed, from it's bash shell, run your executable, say `MyProgram`, using the `time` utility, like so: ``` /usr/bin/time ./MyProgram ``` This will report how long the execution of your program took -- the output would look something like the following: ``` real 0m0.792s user 0m0.046s sys 0m0.218s ``` You could also manually modify your C program to instrument it using the `clock()` library function, like so: ``` #include <time.h> int main(void) { clock_t tStart = clock(); /* Do your stuff here */ printf("Time taken: %.2fs\n", (double)(clock() - tStart)/CLOCKS_PER_SEC); return 0; } ```
With C++11 for measuring the execution time of a piece of code, we can use the now() function: ``` auto start = std::chrono::steady_clock::now(); // Insert the code that will be timed auto end = std::chrono::steady_clock::now(); // Store the time difference between start and end auto diff = end - start; ``` If you want to print the time difference between start and end in the above code, you could use: ``` std::cout << std::chrono::duration<double, std::milli>(diff).count() << " ms" << std::endl; ``` If you prefer to use nanoseconds, you will use: ``` std::cout << std::chrono::duration<double, std::nano>(diff).count() << " ns" << std::endl; ``` The value of the diff variable can be also truncated to an integer value, for example, if you want the result expressed as: ``` auto diff_sec = std::chrono::duration_cast<std::chrono::nanoseconds>(diff); std::cout << diff_sec.count() << std::endl; ``` For more info click [here](https://solarianprogrammer.com/2012/10/14/cpp-11-timing-code-performance/)
calculating execution time in c++
[ "", "c++", "execution-time", "" ]
If I use entity framework with linq to sql to query it and I have an object Person but I only need two properties of that object, what's in memory will be load, the entire object ? Example : I got the entity Person with properties : Name, Age, Address, Country, Language ... I only need to use the property Name and Age. So I got no need to load the address, country and other property ... what will be in memory and what type of query will be ask to SQL ? If my Linq query is : ``` public IQueryable<Person> FindAllPersons() { return from person in db.Persons select person; } ``` And later in code I only call the Name and Age property of each Person in the list.
You can query for only the fields you need. Like so, ``` public IQueryable<Person> FindAllPersons() { return from person in db.Persons select new Person(){Name = person.Name, Age = person.Age}; } ```
As an alternative, you can set Delay Loaded to true for all columns you don't want to be loaded instantly.
Entity - Linq to Sql Only load a part of the entity
[ "", "c#", "linq-to-sql", "entity-framework", ".net-3.5", "" ]
I'm interested in using Doctrine as an ORM for a new Zend Framework app I'm writing. I'm trying to figure out the best way to integrate it as straightforward as possible. Every example I find is different, and a lot of them pre-date the new autoloading features in ZF 1.8. None of them have worked for me yet. Does anyone have a good way to do this? I'm inclined to want to place it in my bootstrap file, but some people suggest making a Zend\_Application\_Resource plugin. The hard part seems to be getting the load paths working correctly for both the Doctrine namespace and the model classes which by default don't follow the Zend auto-loading convention. Any thoughts? Thanks.
I wrote a Resource Bootstrapper for Doctrine and Zend Framework a few weeks ago and turned it all into a small wrapper framework, cause I think ZF and Doctrine are a great team. You can read the article here: <http://coffeecoders.de/2009/06/using-the-zend-framework-18-bootstrapper-and-doctrine-110/> It is fully configurable via the Bootstrap resource configurations (example included, too). Unfortunately Doctrine searches for Models in the model folder with the same classname as the filename (which doesn't match the ZF naming scheme) so it was actually not possible to get rid of registering the Doctrine Autoloader. The resource Loader looks like this: ``` <?php /** * Doctrine model loading bootstrap resource. Options must provide a connection string. * directory option for model directory is optional (default is ./models). * Further options will be set for the Doctrine manager via setAttribute (e.g. model_loading). * @author daff */ class Cuckoo_Application_Resource_Model extends Zend_Application_Resource_ResourceAbstract { public function init() { $manager = Doctrine_Manager::getInstance(); $options = $this->getOptions(); foreach($options as $key => $value) { if($key != 'connection' && $key != 'directory') $manager->setAttribute($key, $value); } if(empty($options['connection'])) throw new Exception("No database connection string provided!"); Doctrine_Manager::connection($options['connection']); if(empty($options['directory'])) $dir = './models'; else $dir = $options['directory']; Doctrine::loadModels(realpath($dir)); return $manager; } } ```
<http://weierophinney.net/matthew/archives/220-Autoloading-Doctrine-and-Doctrine-entities-from-Zend-Framework.html> take a look at this post. It gives a detailed explanation, directory structure and how to use autaloading features.
Integrate Doctrine with Zend Framework 1.8 app
[ "", "php", "zend-framework", "orm", "doctrine", "" ]
I normally set my column size when creating a parameter in ADO.NET. But what size do I use if the column is of type `VARCHAR(MAX)`? ``` cmd.Parameters.Add("@blah", SqlDbType.VarChar, ?????).Value = blah; ```
In this case you use -1.
For those of us who did not see -1 by Michal Chaniewski, the complete line of code: ``` cmd.Parameters.Add("@blah",SqlDbType.VarChar,-1).Value = "some large text"; ```
What size do you use for varchar(MAX) in your parameter declaration?
[ "", "c#", "sql-server", "ado.net", "" ]
I am working inside of a quite complex eclipse based application, and having a problem with a JTable based custom component inside of a JSplitPane. The part of the application that I actually have access to is a panel, within a tab, within a panel, within the actual application, so there are a lot of things that can go wrong. The specific problem that I'm having right now is that the table component is selecting the wrong cell when I click on it. If I select a cell in row 0, column 0, the cell that actually gets selected is at row 2, column 0, which is about 20 pixels below the actual click. This only happens if the table is in a JSplitPane though: if I just add the table itself to a panel, cell selection is correct. What it seems like to me is that because the table is in a JSplitPane, the boundaries of the table (or maybe the viewport of the scroll pane containing the table?) are off by about 20 pixels somewhere. Another problem that I had which can back this theory up, is that scrolling the table caused repaints above the table: so for example, as I scrolled down, instead of the table scrolling, it actually moved upwards (painting over the components above the table) about 20 pixels before scrolling. I was able to workaround this problem by adding ``` jscrollpane.getViewport().setScrollMode(JViewport.BACKINGSTORE_SCROLL_MODE); ``` to the scrollpane that contained the table. Because of all the custom components involved, I can't actually get a small app that shows the problem, but I have the next best thing, which is an app that shows the layout that I have (of course, it doesn't actually have the same problems). Any ideas on what might be causing the problem? ``` //Test class showing layout of table/splitpane import javax.swing.*; import java.awt.*; public class SplitTest { private static JFrame frame; private static JPanel buildTable() { JPanel tblPanel = new JPanel(); tblPanel.setLayout(new BorderLayout()); String[] cols = new String[]{"one", "two", "three", "four", "five", "six", "seven"}; Object[][] data = new Object[30][7]; for(int x = 0;x < data.length;x++) for(int y = 0;y < data[x].length;y++) data[x][y] = x + ", " + y; JTable tbl = new JTable(data, cols); JScrollPane scrollPane = new JScrollPane(tbl); tblPanel.add(scrollPane, BorderLayout.CENTER); return tblPanel; } private static JPanel buildTab() { JPanel pnl = new JPanel(); pnl.setLayout(new BorderLayout()); JPanel menuPnl = new JPanel(); menuPnl.setLayout(new FlowLayout(FlowLayout.LEFT)); menuPnl.add(new JLabel("label")); menuPnl.add(new JComboBox(new String[]{"one", "two"})); menuPnl.add(new JButton("Button")); pnl.add(menuPnl, BorderLayout.NORTH); JSplitPane splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT); splitPane.setLeftComponent(buildTable()); JPanel bottomPnl = new JPanel(); bottomPnl.setPreferredSize(new Dimension(800, 200)); bottomPnl.setBackground(Color.RED); splitPane.setRightComponent(bottomPnl); splitPane.setDividerLocation(.5); pnl.add(splitPane, BorderLayout.CENTER); return pnl; } private static JTabbedPane buildGUI() { JTabbedPane topLevelTabbedFrame = new JTabbedPane(); topLevelTabbedFrame.addTab("Tab 1", buildTab()); topLevelTabbedFrame.addTab("Tab 2", new JPanel()); topLevelTabbedFrame.addTab("Tab 3", new JPanel()); return topLevelTabbedFrame; } private static void createAndShowGUI() { frame = new JFrame("Split Test"); frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); frame.getContentPane().add(buildGUI(), BorderLayout.CENTER); // frame.setSize(new Dimension(800, 600)); frame.pack(); frame.setVisible(true); } public static void main(String[] args) throws Exception { SwingUtilities.invokeLater(new Runnable() { public void run() { createAndShowGUI(); } }); } } ```
As it turns out, the problem was with the order that the components were initialized and added to the split pane. So the eventual fix was to delay adding the table to the split pane until after the split pane was actually added to the panel, rather than adding the table to the split pane before adding the split pane to the panel. Making that small change fixed the issue.
Have you tries running it on a different box to check if its hardware related. May be related to this bug <https://bugs.java.com/bugdatabase/view_bug?bug_id=4763448>
JTable selects wrong cell on click
[ "", "java", "swing", "scroll", "jtable", "" ]
I have a few values that I would like to pass into a filter and get a URL out of it. In my template I have: ``` {% if names %} {% for name in names %} <a href='{{name|slugify|add_args:"custid=name.id, sortid=2"}}'>{{name}}</a> {%if not forloop.last %} | {% endif %} {% endfor %} {% endif %} ``` In my templatetags I have: ``` @register.filter def add_args(value, args): argz = value.strip() + '-' + 'ARGS' arglist = args.split(',') for arg in arglist: keyval = arg.split('=') argz.join(keyval[0] + 'ZZ' + keyval[1]) argz.join('QQ') return argz ``` The output URL should look like: ``` http://foo.org/john-smith-ARGScustidZZ11QQsortidZZ2 ``` Where ARGS is the start of the arguments, ZZ is '=' and QQ is an '&' equivalent. First of all: This would work, but I get the custid=name.id coming in the add\_args(), where I want to have custid=11 to come in. How pass in the id as an id and not text. Also, is there a way to just send in an array of key=>value like in PHP. In PHP I would build an array, let say: ``` arglist = array('custid' => $nameid, 'sortid' => $sortid ); ``` Then I would pass the arglist as an argument to `add_args()` and in `add_args()` I would do ``` foreach( arglist as $key => $value) $argstr .= $key . 'ZZ' . $value . 'QQ'. ``` Does anyone have a better way of making this work? Note: if I have to pass all arguments as a string and split them up in the filter I don't mind. I just don't know how to pass the name.id as its value ...
This "smart" stuff logic should not be in the template. Build your end-of-urls in your view and then pass them to template: ``` def the_view(request): url_stuff = "custid=%s, sortid, ...." % (name.id, 2 ...) return render_to_response('template.html', {'url_stuff':url_stuff,}, context_instance = RequestContext(request)) ``` In template.html: ``` .... <a href='{{url_stuff}}'>{{name}}</a> .... ``` If you need a url for a whole bunch of objects consider using [get\_absolute\_url](http://docs.djangoproject.com/en/dev/ref/models/instances/#get-absolute-url) on the model.
You can't pass `name.id` to your filter. Filter arguments can be asingle value or a single literal. Python/Django doesn't attempt any "smart" variable replacement like PHP. I suggest you to create a tag for this task: ``` <a href='{% add_args "custid" name.id "sortid" "2" %}{{name|slugify}}{% end_add_args %}'>{{name}}</a> ``` This way you can know which argument is a literal value and which should be taken fron context etc... Docs are quite clear about this, take a look at the [example](http://docs.djangoproject.com/en/dev/howto/custom-template-tags/#passing-template-variables-to-the-tag). Also if this `name` is any way related to a model, say we want to get to the permalink, adding a method that returns the URL with the proper arguments might be the tidiest solution. Overall, I would refrain putting too much logic into templates. Django is not PHP.
Django -- how to use templatetags filter with multiple arguments
[ "", "python", "django", "filter", "django-templates", "tags", "" ]
**Any ideas how to configure Wordpress to get the date and page numbers in Eastern Arabic Numerals?** These are 0660 up till 0669 in UTF-8. I am talking about getting those numbers **٠١٢٣٤٥٦٧٨٩** replace those **0123456789**. I am using Wordpress 2.7.
،السلام عليكم This isn't possible using any of the default wordpress tools. The "[Styling Page Links](http://codex.wordpress.org/Styling_Page-Links "Styling Page Links")" documentation only provides limited customization of the page numbers. So you have a couple options. 1. Edit *wp\_link\_pages()* in wp-includes/post-template.php But this is pretty hackish, and will cause problems when it comes time to upgrade. 2. Write a small plugin that bypasses *wp\_link\_pages()* entirely, possibly by editing an [existing (WP Page Numbers)](http://wordpress.org/extend/plugins/wp-page-numbers/ "WP Page Numbers") plugin. This has the benefit of being maintainable and portable (you could distribute the plugin). In both cases you will have to do some mapping: { {0،٠}, {1,١}, {2, ٢} ....}, and do a string replacement after the page number calculation. *Also,* I looked into the [Arabic WP translation](http://arabic.wordpress.net/ "WP in Arabic") but it uses traditional numerals, which seems silly. حظ سعيد يابشا
I'd suggest that you don't do the replacement... Keeping the normal numbers 0x40 to 0x49 allows search engines to search in the numbers. An Arab who prefers the other number system would have set that in their operating system, and they would see 0123456789 as ٠١٢٣٤٥٦٧٨٩.
Eastern Arabic Numerals in Wordpress
[ "", "php", "wordpress", "blogs", "arabic", "" ]
I am trying to access the Model data passed to the view in the action filter OnActionExecuted. Does anyone know if this is possible? I am trying to do something like this: ``` public override void OnActionExecuted(ActionExecutedContext filterContext) { //get model data //... sitemap.SetCurrentNode(model.Name); } ``` Any advice?
The model is at: ``` filterContext.Controller.ViewData.Model ```
I don't know why but `filterContext.Controller.ViewData.Model` is always null even when the model bind is executed before `OnActionExecuted`. I found a solution using the `OnModelUpdated` event to set that property before. I have the model binder: ``` public class CustomModelBinder: DefaultModelBinder { protected override void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext) { controllerContext.Controller.ViewData.Model = bindingContext.Model; base.OnModelUpdated(controllerContext, bindingContext); } } ``` After that you need to set the default binder to your new model binder in `Application_Start()` section in Global.asax: ``` ModelBinders.Binders.DefaultBinder = new CustomModelBinder(); ``` Finally you can access your `Model` in an `ActionFilterAttribute`: ``` public class TraceLog : ActionFilterAttribute { public override void OnActionExecuted(ActionExecutedContext filterContext) { //filterContext.Controller.ViewData.Model now isn't null base.OnActionExecuted(filterContext); } } ```
Asp.net mvc - Accessing view Model from a custom Action filter
[ "", "c#", "asp.net-mvc", "custom-action-filter", "" ]
``` if (listBox1.InvokeRequired) { listBox = new StringBuilder(this.listBox1.Text); } ``` This is the code in c# which when executed produces an invalid cross thread operation error for listBox1 which is a listbox in my form. Could u guys please tell me why?? I am using the invokeRequired method too and am not changing the contents of the listbox either.
InvokeRequired only tells you that an Invoke is necessary in order to validly access the element. It doesn't make the access legal. You must use the invoke method to push the update to the appropriate thread ``` Action update = () => listbox = new StringBuilder(this.listBox1.Text); if (listBox1.InvokeRequired) { listBox1.Invoke(update); } else { update(); } ```
InvokeRequired simply checks to see if Invoke is required. You found it's required, yet didn't call Invoke!
crossthread operations error
[ "", "c#", "multithreading", "" ]
I know this is a rather broad question, but have a class that has a method to display an image and would like to use that method in a different piece of code to open up the image, but not have that method call be blocking. So if I had the following snippet somewhere in a piece of code: ``` ImageClass MyImage = new ImageClass(); MyImage.DisplayImage(@"C:\SomeImage.jpg"); Console.Writeline("This is the line after displaying the image"); ``` I would basically want the image to display and then proceed on to the Console Writeline. Do I have to create a new thread or process to do this? Thanks in advance.
Yes, you will need to use additional threads. I'm not as familiar with GDI, but you may need to run the non-UI code in a separate thread so that the UI code can run in the main UI thread. Something like the following: ``` ImageClass MyImage = new ImageClass(); MyImage.DisplayImage(@"C:\SomeImage.jpg"); ThreadPool.QueueUserWorkItem(new WaitCallback(new delegate(object o) { Console.Writeline("This is the line after displaying the image"); })); ```
Yes, creating a new thread and calling MyImage.DisplayImage(@"C:\SomeImage.jpg"); in that thread is the best way to do it.
C# Displaying a image in a form that is non-blocking to the rest of my code
[ "", "c#", "system.drawing", "" ]
Does anyone know how can I replace this 2 symbol below from the string into code? * ' left single quotation mark into ‘ * ' right single quotation mark into ’ * " left double quotation mark into “ * " right double quotation mark into ”
Knowing which way to make the quotes go (left or right) won't be easy if you want it to be foolproof. If it's not that important to make it exactly right all the time, you could use a couple of regexes: ``` function curlyQuotes(inp) { return inp.replace(/(\b)'/, "$1’") .replace(/'(\b)/, "‘$1") .replace(/(\b)"/, "$1”") .replace(/"(\b)/, "“$1") } curlyQuotes("'He said that he was \"busy\"', said O'reilly") // ‘He said that he was “busy”', said O’reilly ``` You'll see that the second ' doesn't change properly.
The hard part is identifying apostrophes, which will mess up the count of single-quotes. For the double-quotes, I think it's safe to find them all and replace the odd ones with the left curly and the even ones with the right curly. Unless you have a case with nested quotations. What is the source? English text? Code?
replace symbol in javascript
[ "", "javascript", "quotes", "quotation-marks", "" ]
I'm trying to serialize a NameValueCollection over WCF. I keep getting exceptions telling me to add one type after another. After adding them, I finally get > Type 'System.Object[]' cannot be added to list of known types since another type 'System.Collections.ArrayList' with the same data contract name '<http://schemas.microsoft.com/2003/10/Serialization/Arrays:ArrayOfanyType>' is already present. The contract now looks like this: ``` [KnownType(typeof(NameValueCollection))] [KnownType(typeof(CaseInsensitiveHashCodeProvider))] [KnownType(typeof(CaseInsensitiveComparer))] [KnownType(typeof(string[]))] [KnownType(typeof(Object[]))] [KnownType(typeof(ArrayList))] [DataContract] public class MyClassDataBase { [DataMember] public NameValueCollection DataCollection = new NameValueCollection(); } ``` I really dont know what to do to be able to serialize my NameValueColletion. Another strange thing is that the compiler warns that the CaseInsensitiveHashCodeProvider is deprecated.
The best idea would be to stop using weak types like `NameValueCollection` and `ArrayList`. Use `Dictionary<string,string>` and `List<T>` instead.
The `NameValueCollection` doesn't seem exactly to be designed for this use case. There is [a series](http://weblogs.asp.net/avnerk/archive/2006/08/02/WCF-Serialization-Part-2_3A00_-NameValueCollection-Denied_2100_.aspx) [of blog](http://weblogs.asp.net/avnerk/archive/2006/08/02/WCF-Serialization-Part-2b_3A00_-WCF-Collection-Serialization.aspx) [posts](http://weblogs.asp.net/avnerk/archive/2006/08/02/WCF-Serialization-Part-2c_3A00_-Hacking-the-NameValueCollection-_2800_unsuccesfully_2900_.aspx) on [this blog](http://weblogs.asp.net/avnerk/) that deals with this problem and presents [a possible solution](http://weblogs.asp.net/avnerk/archive/2006/08/03/WCF-Serialization-Part-2d_3A00_-A-Solution_2C00_-a-Conclusion-and-a-Contribution.aspx) (to wit: *use an IDictionary*). I haven't tested it though.
WCF serialization problem using NameValueCollection
[ "", "c#", "wcf", "serialization", "" ]
I have seen references to some browsers natively supporting JSON parsing/serialization of objects safely and efficiently via the `window.JSON` Object, but details are hard to come by. Can anyone point in the right direction? What are the methods this Object exposes? What browsers is it supported under?
All modern browsers support native JSON encoding/decoding (Internet Explorer 8+, Firefox 3.1+, Safari 4+, and Chrome 3+). Basically, `JSON.parse(str)` will parse the JSON string in `str` and return an object, and `JSON.stringify(obj)` will return the JSON representation of the object `obj`. More details on the [MDN article](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_native_JSON).
jQuery-1.7.1.js - 555 line... ``` parseJSON: function( data ) { if ( typeof data !== "string" || !data ) { return null; } // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } jQuery.error( "Invalid JSON: " + data ); } rvalidchars = /^[\],:{}\s]*$/, rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, ```
Browser-native JSON support (window.JSON)
[ "", "javascript", "json", "browser", "" ]
I am using 'explain' to view why my query is hitting every single row in my database, and I do not understand why it is doing so. Could someone take a look and give me a hint what I am missing? My database is MyISAM, and I am using Mysql 5.1, PHP5 Here is my table: ``` -- -- Table structure for table `users` -- CREATE TABLE IF NOT EXISTS `users` ( `user_id` bigint(20) NOT NULL auto_increment, `name` varchar(40) default NULL, `city` varchar(90) default NULL, `latitude` float NOT NULL default '0', `longitude` float NOT NULL default '0', PRIMARY KEY (`user_id`), UNIQUE KEY `name` (`name`), KEY `Radius Search` (`latitude`,`longitude`), KEY `Radius 2` (`longitude`,`latitude`) ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=38666 ; ``` Here is my query: ``` $query = "SELECT name, city FROM users WHERE ( (69.1 * (latitude - " . $user->latitude . ")) * (69.1 * (latitude - " . $user->latitude . ")) ) + ( (69.1 * (longitude - " . $user->longitude . ") * COS(" . $user->latitude . " / 57.3)) * (69.1 * (longitude - " . $user->longitude . ") * COS(" . $user->latitude . " / 57.3)) ) < " . pow($radius, 2) . " ORDER BY ( (69.1 * (latitude - " . $user->latitude . ")) * (69.1 * (latitude - " . $user->latitude . ")) ) + ( (69.1 * (longitude - " . $user->longitude . ") * COS(" . $user->latitude . " / 57.3)) * (69.1 * (longitude - " . $user->longitude . ") * COS(" . $user->latitude . " / 57.3)) ) ASC"; ``` And finally, my explain... ``` id select_type table type possible_keys key key_len ref rows Extra 1 SIMPLE users ALL NULL NULL NULL NULL 38665 Using where; Using filesort ```
**Most likely** it is because you are filtering on an EXPRESSION rather than an indexed column. MySQL indexes on columns, not expressions. You have a couple of options here: 1. Can you boil down the expression to a fixed value and store it in one or two columns? If that is not possible, then consider creating a very fast lookup table, and join against it. For example: ``` CREATE TABLE user_loc ( longitude float(n,m) not null, latitude float(n,m) not null, user_id int unsigned not null ); ``` Because it will be a tiny fixed width table, you should be able to query it very fast even with a full table scan. Just join against it to get the users you want. (note: check performance requirements before going to these lengths, as you may not need it at all)
How exactly is it supposed to use a sorted index on 'latitude' to more efficiently evaluate your where clause? ... When a field is used in an expression in the where clause, indexes typically do not apply. Moreover, in this case I'm not sure you can even rewrite the clause to make the index apply, which is a little rarer. **Addendum**: Looking at what you are actually trying to do, maybe you can use a fixed-size lat/long box around the users' coordinate, so that you can use `BETWEEN` clauses on lat and long. Then you can keep the `ORDER BY` complex as it is now, and cut-off after the '`x`' closest other users. Then you may never notice that the matches are actually in a box rather than a circular radius from the one you are considering.
Mysql not using my indexes
[ "", "php", "mysql", "query-optimization", "" ]
How do I in .NET format a number as percentage without showing the percentage sign? If I have the number `0.13` and use the format string `{0:P0}` the output is `13 %`. However I would like to get `13` instead, *without* having to multiply the number by 100 and using the format string `{0:N0}`. (Background: In ASP.NET I have a GridView with a BoundField where I would like to display a number as percentage but without the percentage sign (%). How do I do that?) --- Thanks for the answers. At the time of editing 4 out of 6 suggest what I would like to avoid, as explained above. I was looking for a way to use a format string only, and avoid multiplying by 100 and using `{0:N0}`, but the answers indicate that's impossible... --- Solved by using the accepted solution by [Richard](https://stackoverflow.com/users/67392/richard): ``` public class MyCulture : CultureInfo { public MyCulture() : base(Thread.CurrentThread.CurrentCulture.Name) { this.NumberFormat.PercentSymbol = ""; } } Thread.CurrentThread.CurrentCulture = new MyCulture(); ```
Define a custom culture with its own [`NumberFormatInfo`](http://msdn.microsoft.com/library/system.globalization.numberformatinfo) which returns `String.Empty` for its [`PercentSymbol`](http://msdn.microsoft.com/library/system.globalization.numberformatinfo.percentsymbol) property. Then use that custom culture for impacted pages (or for the whole application). This could be done by cloning from the default so other regional settings are preserved.
Why don't you just multiply the number by 100 and use your `"{0:N0}"` format string? That seems to me to be the easiest solution. Unless you can come up with a viable reason why that's out of the question, that's my advice. It's not rocket science :-)
How to format a number as percentage without the percentage sign?
[ "", "c#", "string-formatting", "" ]
I've a JME application running in a samsung i617 cell phone, and the applications is throwing OutOfMemoryError when its heap goes over 7.1 MB (and the cell phone has 64 mb)... Is it possible to use the -Xmx and -Xms parameters in JME
No, this isn't possible. Max heap size is device dependent. See also this [question](https://stackoverflow.com/questions/348018/increase-heap-size-in-j2me). The total memory of the handset is irrelevant. The JVM (or better the KVM) has only access to a part of it. The total amount varies from handset to handset. It could also be a restriction for the total memory a single MIDlet can access.
Just for the record WeakReferenecs are supported on CLDC 1.1 [javadoc](http://java.sun.com/javame/reference/apis/jsr139/java/lang/ref/WeakReference.html) (can't make comments yet, sorry...)
Using -Xmx and -Xms in a JME application in a cell phone
[ "", "java", "memory-management", "java-me", "jvm", "" ]
Am wondering how to post an array using $.ajax. My array is something like this: ``` var a = new Array(); a['test'] = 1; a['test2'] = 2; and so on... ``` I tried: ``` $.ajax({ url: baseUrl+"chat.php", data: { vars: a}, type: 'post', success: function(data) { alert(data); }}); ``` Any suggestions?
Try this one: ``` var a = {}; a['test'] = 1; a['test2'] = 2; // or var a = {}; a.test = 1; a.test2 = 2; // or var a = { test : 1, test2 : 2 }; $.ajax({ url: baseUrl+"chat.php", data: a, type: 'post', success: function(data) { alert(data); } }); ``` You may then access the data in your PHP script like this: ``` $_POST['test']; $_POST['test2']; ```
I used this: ``` var newArray = new Array(); newArray.push("item1"); newArray.push("item2"); newArray.push("item3"); $.ajax({ type: "POST", url: urlToPost, data: JSON.stringify(newArray), contentType: "application/json" }); ```
jQuery post array
[ "", "javascript", "jquery", "" ]
I'm currently researching the 2nd edition of C# in Depth, and trying to implement "dynamic protocol buffers" - i.e. a level of dynamic support on top of my existing protocol buffer library. As such, I have a `DlrMessage` type derived from `DynamicObject`. After a little bit of playing around I've managed to get it to respond to simple properties with remarkably little code, but I want to go a lot further - and to really understand what's going on. So far I haven't found any good explanations of the DLR - and a lot of the blog posts are effectively out of date now, as things have changed (I believe) between the previous CTP and .NET 4.0 beta 1. The [MSDN documentation for DynamicObject](http://msdn.microsoft.com/en-us/library/system.dynamic.dynamicobject(VS.100).aspx) is pretty minimal at the moment. My most immediate query is whether there's a simple way of saying, "Use reflection to bind any calls I can't handle, using this particular object." (In other words, I want to augment the existing reflection binding rather than doing everything myself, if possible.) Unfortunately I'm not getting very far by guesswork. Are there any definitive and recent sources of documentation I should know about? I'm aware that part of writing about a new technology *is* exploration, but a helping hand would be appreciated :)
Best source I've found and read frequently is the last years worth of Chris Burrow's posts on [his blog](http://blogs.msdn.com/cburrows/). There's also the [official DLR documentation page](http://www.codeplex.com/dlr/Wiki/View.aspx?title=Docs%20and%20specs) which is off the [main DLR site](http://dlr.codeplex.com/Wiki/View.aspx?title=Home).
I too am researching this at the moment and there is not too much info yet. I cant help with your query but below is some information I have found: There is a fair amount within the PDC videos. <http://channel9.msdn.com/pdc2008/TL44/> <http://channel9.msdn.com/pdc2008/TL10/> This article talks about how the DLR works with IronPython: <http://msdn.microsoft.com/en-us/magazine/cc163344.aspx> There is a very small amount in the training kit preview at: <http://www.microsoft.com/downloads/details.aspx?FamilyID=752cb725-969b-4732-a383-ed5740f02e93&displayLang=en> Hope this helps Alex
What's the best source of information on the DLR (.NET 4.0 beta 1)?
[ "", "c#", "dynamic", "c#-4.0", "dynamic-language-runtime", "" ]
I am contemplating taking the next step with my PHP applications and making the option fields dynamic. That would open the doors for more automation. I have drop downs throughout my project, they are used to select a specific user and I update them manually when a new user is added (which is also a manual process). But if i take the first step and make these drop downs become populated by a MySQL Database, then i can move on to dynamic user creation. I know how I can achieve this, but I am curious about some other alternatives (If there is any). Here is what I would do.. ``` $query = ** MySQL Select * From Database Query ** echo '<select name="usernames">'; while($row == mysql_fetch_array($query)) { echo '<option>' . $row['username'] . '</option>'; } echo '</select>'; ``` So my questions is, would you do this differently? And why? Thanks!
What you are doing will work fine. I like to make it into a function so that if I ever need that dropdown on another page I dont have to write a lot of code over again. ``` function userDD() { $query = ** MySQL Select * From Database Query ** $html = '<select name="usernames">'; while($row == mysql_fetch_array($query)) { $html .= '<option>' . $row['username'] . '</option>'; } $html .= '</select>'; return $html; } ``` This code does exactly what your code does except it doenst use echo. Instead you use a variable ($html) to store all of the data then when you are done you return it.
Your way is fine, but two things need to be changed: - **Run [htmlentities](http://php.net/htmlentities)() or [htmlspecialchars](http://php.net/htmlspecialchars)() on all echoed HTML to avoid XSS.** Unless you already sanitized it at database entry time but I find this practice silly. - Add a `value` attribute to each `<option>` tag, otherwise you won't be able to retrieve the username selected. I suggest using the username's corresponding ID or something else that's unique to that user. If it's a string, use htmlentities/htmlspecialchars on it too.
Using MySQL Databases and PHP to Populate forms
[ "", "php", "mysql", "" ]
I want to include the current time and date in a .net application so I can include it in the start up log to show the user what version they have. Is it possible to retrieve the current time during compilation, or would I have to get the creation/modification time of the executable? E.g. > Welcome to ApplicationX. This was built *day-month-year* at *time*.
If you're using reflection for your build number you can use that to figure out when a build was compiled. Version information for an assembly consists of the following four values: 1. Major Version 2. Minor Version 3. Build Number 4. Revision You can specify all the values or you can accept the default build number, revision number, or both by using an asterisk (\*). Build number and revision are based off Jan 1, 2000 by default. The following attribute will set Major and minor, but then increment build number and revision. ``` [assembly: AssemblyVersion("5.129.*")] ``` Then you can use something like this: ``` public static DateTime CompileTime { get { System.Version MyVersion = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; // MyVersion.Build = days after 2000-01-01 // MyVersion.Revision*2 = seconds after 0-hour (NEVER daylight saving time) DateTime compileTime = new DateTime(2000, 1, 1).AddDays(MyVersion.Build).AddSeconds(MyVersion.Revision * 2); return compileTime; } } ```
The only way I know of doing this is somewhat convoluted - You can have a pre-build event that runs a small application which generates the source code on the fly. An easy way to do this is to just overwrite a very small file that includes a class (or partial class) with the day/month/year hardcoded as a string constant. If you set this to run as a pre-build event, it will rewrite that file before every build.
How do I find the current time and date at compilation time in .net/C# application?
[ "", "c#", "build", "clr", "" ]
I want to test my Dao Class using the SpringContextTests. In my method class I extended the `AbstractTransactionalJUnit4SpringContextTests` in order for my test class to integrate with JUnit4. I have also set up the configurations and made the initialization and database clean up in the `@Before` and tearDown in the `@After`. My test class works perfectly. My problem was, when I run my test class and the database is filled with data, the original data was not rolled back and my database is cleared. In the `@Before` method, I clear the database and populate data, thinking that I will be able to rollback it but its not. Can anyone site an example that works and rollbacks information in the database. ADDONS: Every database manipulation in my test methods are rolled back. But the execution of `super.deleteFromTables("person")` in the `@Before` method did not rollback all the previous data from the database. Spring rollbacks all the CRUD operations but the database clean up before the transaction do not rollback.
Thank you to all those who answered my question. I learned a lot from those answers but it didn't solve my problem. I knew my test data does a transaction management and it does its job properly. The mistake is on my part. I forgot the lesson about database commands that when you execute a DDL statement after a DML statement, it will automatically commit the transaction. I executed a DDL after a DML by deleting all record and then `ALTER` the `AUTO_INCREMENT` of the table where in it will cause an auto-commit and delete all records of the table permanently. FIXING THAT SCENARIO SOLVED MY PROBLEM.
Possible causes: * you're using a database/database engine which does not have proper transactions; * you're using multiple transaction managers and/or data sources and the proper one is not picked up; * you're doing your own, separate, transactions in the test class --- As for an example, here's one ( top of my head, not compiled ) ``` public class DBTest extends AbstractTransactionalJUnit4SpringContextTests { @Autowired private SomeDAO _aBeanDefinedInMyContextFile; @Test public void insert_works() { assert _aBeanDefinedInMyContextFile.findAll() == 0; _aBeanDefinedInMyContextFile.save(new Bean()); assert _aBeanDefinedInMyContextFile.findAll() == 1; } } ``` Key points: * the `SomeDAO` is an interface which corresponds to a bean declared in my context; * the bean does not have any transactional settings ( advice/programmatic), it relies on the caller being transactional - either the service in production, or the test in our situation; * the test does not include any transactional management code, as it's all done in the framework.
Spring Transaction Management Test
[ "", "java", "unit-testing", "spring", "testing", "" ]
how can I get a object from an array when this array is returned by a function? ``` class Item { private $contents = array('id' => 1); public function getContents() { return $contents; } } $i = new Item(); $id = $i->getContents()['id']; // This is not valid? //I know this is possible, but I was looking for a 1 line method.. $contents = $i->getContents(); $id = $contents['id']; ```
You should use the 2-line version. Unless you have a compelling reason to squash your code down, there's no reason *not* to have this intermediate value. However, you could try something like ``` $id = array_pop($i->getContents()) ```
Keep it at two lines - if you have to access the array again, you'll have it there. Otherwise you'll be calling your function again, which will end up being uglier anyway.
PHP - How to get object from array when array is returned by a function?
[ "", "php", "arrays", "syntax", "function", "" ]
I have a Python script that I want to use as a controller to another Python script. I have a server with 64 processors, so want to spawn up to 64 child processes of this second Python script. The child script is called: ``` $ python create_graphs.py --name=NAME ``` where NAME is something like XYZ, ABC, NYU etc. In my parent controller script I retrieve the name variable from a list: ``` my_list = [ 'XYZ', 'ABC', 'NYU' ] ``` So my question is, what is the best way to spawn off these processes as children? I want to limit the number of children to 64 at a time, so need to track the status (if the child process has finished or not) so I can efficiently keep the whole generation running. I looked into using the subprocess package, but rejected it because it only spawns one child at a time. I finally found the multiprocessor package, but I admit to being overwhelmed by the whole threads vs. subprocesses documentation. Right now, my script uses `subprocess.call` to only spawn one child at a time and looks like this: ``` #!/path/to/python import subprocess, multiprocessing, Queue from multiprocessing import Process my_list = [ 'XYZ', 'ABC', 'NYU' ] if __name__ == '__main__': processors = multiprocessing.cpu_count() for i in range(len(my_list)): if( i < processors ): cmd = ["python", "/path/to/create_graphs.py", "--name="+ my_list[i]] child = subprocess.call( cmd, shell=False ) ``` I really want it to spawn up 64 children at a time. In other stackoverflow questions I saw people using Queue, but it seems like that creates a performance hit?
What you are looking for is the [process pool](http://docs.python.org/library/multiprocessing.html#module-multiprocessing.pool) class in multiprocessing. ``` import multiprocessing import subprocess def work(cmd): return subprocess.call(cmd, shell=False) if __name__ == '__main__': count = multiprocessing.cpu_count() pool = multiprocessing.Pool(processes=count) print pool.map(work, ['ls'] * count) ``` And here is a calculation example to make it easier to understand. The following will divide 10000 tasks on N processes where N is the cpu count. Note that I'm passing None as the number of processes. This will cause the Pool class to use cpu\_count for the number of processes ([reference](http://docs.python.org/library/multiprocessing.html#multiprocessing.pool.multiprocessing.Pool)) ``` import multiprocessing import subprocess def calculate(value): return value * 10 if __name__ == '__main__': pool = multiprocessing.Pool(None) tasks = range(10000) results = [] r = pool.map_async(calculate, tasks, callback=results.append) r.wait() # Wait on the results print results ```
Here is the solution I came up, based on Nadia and Jim's comments. I am not sure if it is the best way, but it works. The original child script being called needs to be a shell script because I need to use some 3rd party apps including Matlab. So I had to take it out of Python and code it in bash. ``` import sys import os import multiprocessing import subprocess def work(staname): print 'Processing station:',staname print 'Parent process:', os.getppid() print 'Process id:', os.getpid() cmd = [ "/bin/bash" "/path/to/executable/create_graphs.sh","--name=%s" % (staname) ] return subprocess.call(cmd, shell=False) if __name__ == '__main__': my_list = [ 'XYZ', 'ABC', 'NYU' ] my_list.sort() print my_list # Get the number of processors available num_processes = multiprocessing.cpu_count() threads = [] len_stas = len(my_list) print "+++ Number of stations to process: %s" % (len_stas) # run until all the threads are done, and there is no data left for list_item in my_list: # if we aren't using all the processors AND there is still data left to # compute, then spawn another thread if( len(threads) < num_processes ): p = multiprocessing.Process(target=work,args=[list_item]) p.start() print p, p.is_alive() threads.append(p) else: for thread in threads: if not thread.is_alive(): threads.remove(thread) ``` Does this seem like a reasonable solution? I tried to use Jim's while loop format, but my script just returned nothing. I am not sure why that would be. Here is the output when I run the script with Jim's 'while' loop replacing the 'for' loop: ``` hostname{me}2% controller.py ['ABC', 'NYU', 'XYZ'] Number of processes: 64 +++ Number of stations to process: 3 hostname{me}3% ``` When I run it with the 'for' loop, I get something more meaningful: ``` hostname{me}6% controller.py ['ABC', 'NYU', 'XYZ'] Number of processes: 64 +++ Number of stations to process: 3 Processing station: ABC Parent process: 1056 Process id: 1068 Processing station: NYU Parent process: 1056 Process id: 1069 Processing station: XYZ Parent process: 1056 Process id: 1071 hostname{me}7% ``` So this works, and I am happy. However, I still don't get why I can't use Jim's 'while' style loop instead of the 'for' loop I am using. Thanks for all the help - I am impressed with the breadth of knowledge @ stackoverflow.
How to spawn parallel child processes on a multi-processor system?
[ "", "python", "exec", "subprocess", "multiprocessing", "" ]
I am trying to set the DF (don't fragment flag) for sending packets using UDP. Looking at the Richard Steven's book Volume 1 Unix Network Programming; The Sockets Networking API, I am unable to find how to set this. I suspect that I would do it with setsockopt() but can't find it in the table on page 193. Please suggest how this is done.
You do it with the `setsockopt()` call, by using the `IP_DONTFRAG` option: ``` int val = 1; setsockopt(sd, IPPROTO_IP, IP_DONTFRAG, &val, sizeof(val)); ``` [Here's](http://publib.boulder.ibm.com/infocenter/iseries/v5r4/topic/apis/ssocko.htm) a page explaining this in further detail. For Linux, it appears you have to use the `IP_MTU_DISCOVER` option with the value `IP_PMTUDISC_DO` (or `IP_PMTUDISC_DONT` to turn it off): ``` int val = IP_PMTUDISC_DO; setsockopt(sd, IPPROTO_IP, IP_MTU_DISCOVER, &val, sizeof(val)); ``` I haven't tested this, just looked in the header files and a bit of a web search so you'll need to test it. As to whether there's another way the DF flag could be set: > I find nowhere in my program where the "force DF flag" is set, yet `tcpdump` suggests it is. Is there any other way this could get set? From this excellent page [here](http://linux.die.net/man/7/ip): > `IP_MTU_DISCOVER:` Sets or receives the Path MTU Discovery setting for a socket. When enabled, Linux will perform Path MTU Discovery as defined in RFC 1191 on this socket. The don't fragment flag is set on all outgoing datagrams. The system-wide default is controlled by the `ip_no_pmtu_disc` `sysctl` for `SOCK_STREAM` sockets, and disabled on all others. For non `SOCK_STREAM` sockets it is the user's responsibility to packetize the data in MTU sized chunks and to do the retransmits if necessary. The kernel will reject packets that are bigger than the known path MTU if this flag is set (with `EMSGSIZE`). This looks to me like you can set the system-wide default using `sysctl`: ``` sysctl ip_no_pmtu_disc ``` returns `"error: "ip_no_pmtu_disc" is an unknown key"` on my system but it may be set on yours. Other than that, I'm not aware of anything else (other than `setsockopt()` as previously mentioned) that can affect the setting.
If you are working in Userland with the intention to bypass the Kernel network stack and thus building your own packets and headers and hand them to a custom Kernel module, there is a better option than `setsockopt()`. You can actually set the DF flag just like any other field of `struct iphdr` defined in `linux/ip.h`. The 3-bit IP flags are in fact part of the `frag_off` (Fragment Offset) member of the structure. When you think about it, it makes sense to group those two things as the flags are fragmentation related. According to the [RFC-791](http://www.ietf.org/rfc/rfc791.txt), the section describing the IP header structure states that Fragment Offset is 13-bit long and there are three 1-bit flags. The `frag_off` member is of type `__be16`, which can hold 13 + 3 bits. Long story short, here's a solution: ``` struct iphdr ip; ip.frag_off |= ntohs(IP_DF); ``` We are here exactly setting the DF bit using the designed-for-that-particular-purpose `IP_DF` mask. `IP_DF` is defined in `net/ip.h` (kernel headers, of course), whereas `struct iphdr` is defined in `linux/ip.h`.
How to set the don't fragment (DF) flag on a socket?
[ "", "c++", "sockets", "udp", "packet", "" ]
I have created test application to test, Is StringBuilder copy data to another instance and grow it buffer when its length is more than current capacity and verify in ildasm.exe but it seem identical. How to verify StringBuilder will copy its data into new instance and grow the buffer by the specified limit?
If you want to inspect how StringBuilder is implemented, just fire up Reflector and look at it. The implementation for `StringBuilder.Append(string)` is as follows ``` public StringBuilder Append(string value) { if (value != null) { string stringValue = this.m_StringValue; IntPtr currentThread = Thread.InternalGetCurrentThread(); if (this.m_currentThread != currentThread) { stringValue = string.GetStringForStringBuilder(stringValue, stringValue.Capacity); } int length = stringValue.Length; int requiredLength = length + value.Length; if (this.NeedsAllocation(stringValue, requiredLength)) { string newString = this.GetNewString(stringValue, requiredLength); newString.AppendInPlace(value, length); this.ReplaceString(currentThread, newString); } else { stringValue.AppendInPlace(value, length); this.ReplaceString(currentThread, stringValue); } } return this; } ``` Look at the section with `NeedsAllocation`, `GetNewString` and so forth to find what you're looking for.
Capacity represents the contiguous memory allocated to the StringBuilder. Capacity can be >= length of the string. When more data is appended to the StringBuilder than the capacity, StringBuilder automatically increases the capacity. Since the capacity has exceeded (that is contiguous memory is filled up and no more buffer room is available), a larger buffer area is allocated and data is copied from the original memory to this new area. It does not copy data to new 'instance' but to new 'memory location'. The instance remains the same but points to the new memory location. Edit FYI: Default capacity of StringBuilder if not specified during creation is 16 If you wanna see the memory locations for StringBuilder then you can debug your applications and check the memory using Debug > Windows > Memory. You can actually see the address of each and every byte stored in your StringBuilder when Append stmt runs. If you need to get the locations programatically [this link](http://www.codeproject.com/KB/cs/sojaner_memory_scanner.aspx) might help.
StringBuilder and capacity?
[ "", "c#", "stringbuilder", "" ]
I keep on getting confused about this design decision a lot of the time when I'm writing programs, but I'm not 100% sure when I should make a function to be a member function of a class, when to leave it as a normal function in which other source files can call the function when the function declaration is exposed in a header file. Does the desired access to member variables of a class have to do with the decision most of the time?
**The Interface Principle** by Herb Sutter *For a class X, all functions, including free functions, that both (a) "mention" X, and (b) are "supplied with" X are logically part of X, because they form part of the interface of X.* For in depth discussion read [Namespaces and the Interface Principle](http://www.gotw.ca/publications/mill08.htm) by Herb Sutter. EDIT Actually, if you want to understand C++ go and read **everything** what Herb Sutter has written :)
I use classes when I need to maintain state. If a function doesn't need access to maintained state information, then I prefer a free function because it makes testing and code reuse easier. If I have a bunch of related functionality but don't need to maintain state, then I prefer putting free functions in a namespace.
C++ Member Functions vs Free Functions
[ "", "c++", "function", "methods", "" ]
Is there a way to return a list of all the subdirectories in the current directory in Python? I know you can do this with files, but I need to get the list of directories instead.
Do you mean immediate subdirectories, or every directory right down the tree? Either way, you could use [`os.walk`](http://docs.python.org/library/os.html#os.walk) to do this: ``` os.walk(directory) ``` will yield a tuple for each subdirectory. Ths first entry in the 3-tuple is a directory name, so ``` [x[0] for x in os.walk(directory)] ``` should give you all of the subdirectories, recursively. Note that the second entry in the tuple is the list of child directories of the entry in the first position, so you could use this instead, but it's not likely to save you much. However, you could use it just to give you the immediate child directories: ``` next(os.walk('.'))[1] ``` Or see the other solutions already posted, using [`os.listdir`](http://docs.python.org/library/os.html#os.listdir) and [`os.path.isdir`](http://docs.python.org/library/os.path.html#os.path.isdir), including those at "[How to get all of the immediate subdirectories in Python](https://stackoverflow.com/questions/800197/get-all-of-the-immediate-subdirectories-in-python)".
You could just use `glob.glob` ``` from glob import glob glob("/path/to/directory/*/", recursive = True) ``` Don't forget the trailing `/` after the `*`.
Getting a list of all subdirectories in the current directory
[ "", "python", "directory", "subdirectory", "" ]
I'm fairly new to using relational databases, so I prefer using a good ORM to simplify things. I spent time evaluating different Python ORMs and I think SQLAlchemy is what I need. However, I've come to a mental dead end. I need to create a new table to go along with each instance of a player I create in my app's player table. I think I know how to create the table by changing the name of the table through the metadata then calling the create function, but I have no clue on how to map it to a new dynamic class. Can someone give me some tips to help me get past my brain freeze? Is this even possible? Note: I'm open to other ORMs in Python if what I'm asking is easier to implement.Just show me how :-)
We are spoiled by SQLAlchemy. What follows below is taken directly from the [tutorial](https://docs.sqlalchemy.org/en/latest/orm/tutorial.html), and is really easy to setup and get working. And because it is done so often, the documentation [moved to full declarative](https://github.com/sqlalchemy/sqlalchemy/commit/4abcc0da839a57513f18a7a9ea7ee6918d48e4b1#diff-968e8ba485a103281d4e8854c32110c8) in Aug 2011. Setup your environment (I'm using the SQLite in-memory db to test): ``` >>> from sqlalchemy import create_engine >>> engine = create_engine('sqlite:///:memory:', echo=True) >>> from sqlalchemy import Table, Column, Integer, String, MetaData >>> metadata = MetaData() ``` Define your table: ``` >>> players_table = Table('players', metadata, ... Column('id', Integer, primary_key=True), ... Column('name', String), ... Column('score', Integer) ... ) >>> metadata.create_all(engine) # create the table ``` If you have logging turned on, you'll see the SQL that SQLAlchemy creates for you. Define your class: ``` >>> class Player(object): ... def __init__(self, name, score): ... self.name = name ... self.score = score ... ... def __repr__(self): ... return "<Player('%s','%s')>" % (self.name, self.score) ``` Map the class to your table: ``` >>> from sqlalchemy.orm import mapper >>> mapper(Player, players_table) <Mapper at 0x...; Player> ``` Create a player: ``` >>> a_player = Player('monty', 0) >>> a_player.name 'monty' >>> a_player.score 0 ``` That's it, you now have a your player table.
It's a very old question. Anyway if you prefer ORM, it's quite easy to generate table class with type: ``` from sqlalchemy.ext.declarative import declarative_base from sqlalchemy import Column, Integer, String Base = declarative_base() Test = type('Test', (Base,), { '__tablename__': 'test', 'test_id': Column(Integer, primary_key=True, autoincrement=True), 'fldA': Column(String), ... other columns } ) Base.metadata.create_all(engine) # passed session create with sqlalchemy session.query(Test).all() ``` Making a class factory, it's easy to assign names to a class and database table.
Dynamic Table Creation and ORM mapping in SqlAlchemy
[ "", "python", "database", "sqlalchemy", "" ]
I'd like to be able to do the following: ``` num_intervals = (cur_date - previous_date) / interval_length ``` or ``` print (datetime.now() - (datetime.now() - timedelta(days=5))) / timedelta(hours=12) # won't run, would like it to print '10' ``` but the division operation is unsupported on timedeltas. Is there a way that I can implement divison for timedeltas? **Edit:** Looks like this was added to Python 3.2 (thanks rincewind!): <http://bugs.python.org/issue2706>
Sure, just convert to a number of seconds (minutes, milliseconds, hours, take your pick of units) and do the division. *EDIT* (again): so you can't assign to `timedelta.__div__`. Try this, then: ``` divtdi = datetime.timedelta.__div__ def divtd(td1, td2): if isinstance(td2, (int, long)): return divtdi(td1, td2) us1 = td1.microseconds + 1000000 * (td1.seconds + 86400 * td1.days) us2 = td2.microseconds + 1000000 * (td2.seconds + 86400 * td2.days) return us1 / us2 # this does integer division, use float(us1) / us2 for fp division ``` And to incorporate this into nadia's suggestion: ``` class MyTimeDelta: __div__ = divtd ``` Example usage: ``` >>> divtd(datetime.timedelta(hours = 12), datetime.timedelta(hours = 2)) 6 >>> divtd(datetime.timedelta(hours = 12), 2) datetime.timedelta(0, 21600) >>> MyTimeDelta(hours = 12) / MyTimeDelta(hours = 2) 6 ``` etc. Of course you could even name (or alias) your custom class `timedelta` so it gets used in place of the real `timedelta`, at least in your code.
Division and multiplication by integers seems to work [out of the box](http://docs.python.org/library/datetime.html#timedelta-objects): ``` >>> from datetime import timedelta >>> timedelta(hours=6) datetime.timedelta(0, 21600) >>> timedelta(hours=6) / 2 datetime.timedelta(0, 10800) ```
How can I perform divison on a datetime.timedelta in python?
[ "", "python", "date", "datetime", "division", "timedelta", "" ]
I am looking at java APIs to convert JPEG file streams to TIFF files. I looked at the JAI but did not find something similar to what i am looking at. Can someone point me to a good API which does this ?
There's an example here <http://log.robmeek.com/2005/08/write-tiff-in-java.html> and another here [Tiff compression using Java ImageIO](https://stackoverflow.com/questions/281512/tiff-compression-using-java-imageio)
JIMI is quite easy to use. <http://java.sun.com/products/jimi/> Unfortunately Sun transmogriffed it into Java2D (afair) and THAT is not quite that easy to use. For a quick solution, use JIMI.
Java API to convert JPEG to TIFF
[ "", "java", "api", "jpeg", "tiff", "" ]
I use PHP\_OS constant and I want to know what it can return on differents OS. I found this : * On Linux -> Linux * On FreeDSB -> FreeBSD * On Windows NT -> WINNT * On Mac Os X -> Darwin Can anyone tell me what they get with them configurations ? On Solaris, Windows XP...
Try [php\_uname](http://php.net/manual/en/function.php-uname.php) for retrieving operating system information
Just for the record... I'm running on Windows XP and this is what's returned: `PHP_OS` : `WINNT` `php_uname('s')` : `Windows NT` **UPDATE:** The same on Windows 7.
What is the name of your system with PHP_OS constant
[ "", "configuration", "php", "" ]
If I have a reference to a class and invoke a method on it, and the class or the method is final, my understanding is that the compiler or the JVM would replace the dynamic dispatch with a cheaper static dispatch since it can determine exactly which version would be invoked. However, what if I have a reference to an interface, and the interface currently has only a single implementor, and that implementor is final or the method is final in that implementor, can the JVM figure that out at runtime and optimize these calls?
(Insert Knuth quote here about optimization.) See [Wikis Home > HotSpot Internals for OpenJDK > PerformanceTechniques](https://wiki.openjdk.java.net/display/HotSpot/PerformanceTechniques). > * Methods are often inlined. This increases the compiler's "horizon" of > optimization. > * Static, private, final, and/or "special" invocations are easy to > inline. > * Virtual (and interface) invocations are often demoted to "special" > invocations, if the class hierarchy > permits it. A dependency is registered > in case further class loading spoils > things. > * Virtual (and interface) invocations with a lopsided type profile are > compiled with an optimistic check in > favor of the historically common type > (or two types). There are some interesting links from [Inlining](https://wiki.openjdk.java.net/display/HotSpot/Inlining).
AFAIK, the JVM can in-line up to two methods, the methods doesn't have to be final. It can do this if the methods are small and called often. If your code calls three or more methods, only the most commonly called methods will be invoked. Note 1: The JVM does care how many implementations there are, only how many are actually called. Note 2: The JVM can inline methods which didn't exist at compile time, its only the code available at runtime which matters.
Does Java optimize method calls via an interface which has a single implementor marked as final?
[ "", "java", "performance", "" ]
I am dynamically adding a bunch of controls to a form. Each control calls the same method, and in that method I need to know the array index of the the control that performed the action. ``` CheckBox[] myCB = new CheckBox[100]; int i; for (i = 0; i < 100; i++) { myCB[i] = new CheckBox(); myCB[i].Text = "Clicky!"; myCB[i].Click += new System.EventHandler(dynamicbutton_Click); tableLayoutPanel1.Controls.Add(myCB[i]); } private void dynamicbutton_Click(Object sender, System.EventArgs e) { label1.Text = sender.???array index property???.ToString(); } ``` So if I click `myCB[42]` `label1` will read "42" Of course, if there is an easier way to handle dynamic controls I'd appreciate pointers.
One obvious solution would be to set the tag: ``` CheckBox[] myCB = new CheckBox[100]; for (int i = 0; i < myCB.Length; i++) { myCB[i] = new CheckBox(); myCB[i].Text = "Clicky!"; myCB[i].Click += new System.EventHandler(dynamicbutton_Click); myCB[i].Tag = i; tableLayoutPanel1.Controls.Add(myCB[i]); } ``` Then: ``` private void dynamicbutton_Click(Object sender, System.EventArgs e) { Control control = (Control) sender; label1.Text = sender.Tag.ToString(); } ``` Another alternative is to capture the information in the event handler, most simply using a lambda expression or anonymous method: ``` CheckBox[] myCB = new CheckBox[100]; for (int i = 0; i < myCB.Length; i++) { int index = i; // This is very important, as otherwise i will // be captured for all of them myCB[i] = new CheckBox(); myCB[i].Text = "Clicky!"; myCB[i].Click += (s, e) => label1.Text = index.ToString(); tableLayoutPanel1.Controls.Add(myCB[i]); } ``` or for more complicated behaviour: ``` CheckBox[] myCB = new CheckBox[100]; for (int i = 0; i < myCB.Length; i++) { int index= i; // This is very important, as otherwise i will // be captured for all of them myCB[i] = new CheckBox(); myCB[i].Text = "Clicky!"; myCB[i].Click += (s, e) => DoSomethingComplicated(index, s, e); tableLayoutPanel1.Controls.Add(myCB[i]); } ``` (where you declare `DoSomethingComplicated` appropriately).
``` private void dynamicbutton_Click(Object sender, System.EventArgs e) { label1.Text = Array.IndexOf(myCB, (CheckBox)sender).ToString(); } ```
How can I get the array index of a given object in C# with control arrays?
[ "", "c#", ".net", "controls", "event-handling", "control-array", "" ]
I am creating a web app that will be used to create invoices and quotes. Currently, I am tediously creating all the controls at design time resulting in controls like the following: txtQty1, txtDescription1, txtUnitPrice1, txtItemCode1. Then for the next line, I just repeat the controls, but add a 2 to the end of the Id. This goes on with 3, 4, 5, etc up until however many line items I need. I know this is a stupid way of doing it and I should probably do it at runtime, but I am not sure what is the best way to do it at runtime and could I possibly use JQuery to add the ASP.NET controls at runtime?
It sounds like you are wanting to dynamically create some number of controls at run time and add them to the page. This is fairly common, but unfortunately is much more complicated. Everything from referencing the controls to adding events becomes just a little bit harder. Additionally, dynamically added controls must be re-added during each postback. The controls themselves do not automatically persist between postbacks. This article gives a great introduction to the topic: <http://www.singingeels.com/Articles/Dynamically_Created_Controls_in_ASPNET.aspx> Ultimately, it depends how easily you would like to be able to access the value of those TextBoxes. In JQuery you can create textboxes on the client side, but it will be even harder to use those values from the ASP.NET code-behind page, because they won't be server-side controls. If it is just going to be a few controls, I would recommend sticking a few controls on during design time and showing and hiding them, as you are already doing. When you are dealing with more than a few, potentially many, repeated controls (which it sounds like you might be), you may have to go with dynamically added controls. Again, I tend to avoid this route unless I have to, because it adds a great deal of complexity.
The simplest way is to override the pages OnInit function, and add the controls there. eg ``` protected override void OnInit(EventArgs e) { for (int i = 0; i != 10; ++i) { TextBox tb = new TextBox(); // Init textBox here Label lb = new Label(); // Init Label here Literal lt = new Literal(); lt.Text = "<br />"; this.Form.Controls.Add(tb); this.Form.Controls.Add(lb); this.Form.Controls.Add(lt); } } ``` You can also investigate databound controls (eg GridView, ListView and Repeater)
Creating ASP.NET controls at runtime for an ASP.NET Invoice App?
[ "", "c#", "asp.net", "jquery", "" ]
I've been debating this to myself for the last few minutes, and I'm seeing reasons for both yes and no. This stemmed from looking at the answers to [Java HashMap vs. Hashtable](https://stackoverflow.com/questions/40471/java-hashmap-vs-hashtable) and seeing several people say Hashtable is in fact slower. It seems to me that a synchronized method *should* act absolutely no different than its unsynchronized counterpart if running in a single thread, since the action of synchronizing shouldn't block anything. That said, I would imagine the compiler handles the two cases differently and that's why people are saying synchronized is slower. Not that it's by any means conclusive, but I ran some simple tests on HashMap vs Hashtable, and saw little difference in speed.
Yes, single-theaded Java programs that use synchronization *may* be slightly slower than they would be without synchronization. For early Java releases, synchronization was expensive. For any modern release, however, *uncontended* synchronization is pretty cheap. I wouldn't worry about this. Note that Java 6 has and Java 7 is to have good optimizations around locking: * Lock coarsening * Lock elision * Adaptive Spin locking * Biased locking For more information, see the [Java SE 6 Performance White Paper](http://java.sun.com/performance/reference/whitepapers/6_performance.html). Also note that uncontended synchronization appears to be more expensive on multi-core CPUs than on single-core CPUs, perhaps due to the Java Memory Model requirements of synchronization forcing local CPU caches to be shared with other CPUs, or some other memory barrier. For example, read [Do Java 6 threading optimizations actually work? - Part II](http://www.infoq.com/articles/java-threading-optimizations-p2). (The Part I was not as insightful as the Part II.)
Yes. They are going to be slightly slower due to the extra overhead of maintaining locks.
Are Synchronized Methods Slower In Single Threaded Applications?
[ "", "java", "multithreading", "synchronization", "" ]
I use the following code to convert a gif file to a jpg file, it works but the result jpg file isn't the same quality as the original gif file, why ? Any way to improve the quality ? ``` try { ImageIO.write(ImageIO.read(new File("C:/abc.gif")),"jpg",new File("C:/abc.jpg")); } catch (Exception e) { e.printStackTrace(); } ``` So, to ask this question from another angle, with the above approach, how to increase the output quality ?
[JPEG](http://en.wikipedia.org/wiki/JPEG) is a [lossy image compression](http://en.wikipedia.org/wiki/Lossy_compression) format which discards information that the human eyes can't notice very well. However, depending on the image quality settings when compressing the image, [compression artifacts](http://en.wikipedia.org/wiki/Compression_artifact), such as blockiness and smudging can become visible -- this is the reason behind the image not appearing to be clear. It may be possible that the [`ImageIO.write`](http://java.sun.com/javase/6/docs/api/javax/imageio/ImageIO.html#write(java.awt.image.RenderedImage,%20java.lang.String,%20java.io.File)) method is saving the JPEG with a lower quality setting than necessary to keep the image looking good enough. In order to set the quality setting higher, it will be necessary to use the [`ImageWriteParam`](http://java.sun.com/javase/6/docs/api/javax/imageio/ImageWriteParam.html) to specify the image quality settings, then use the [`ImageWriter`](http://java.sun.com/javase/6/docs/api/javax/imageio/ImageWriter.html) to output the JPEG. For example: ``` // Get a writer for JPEG. ImageWriter iw = ImageIO.getImageWritersByFormatName("jpeg").next(); iw.setOutput(new FileImageOutputStream(outputFile)); // Set the compression quality to 0.9f. ImageWriteParam iwParam = iw.getDefaultWriteParam(); iwParam.setCompressionQuality(0.9f); // Write image iw.write(null, new IIOImage(imageToWrite, null, null), iwParam); ``` Methods of interest: * [`ImageWriteParam.setCompressionQuality`](http://java.sun.com/javase/6/docs/api/javax/imageio/ImageWriteParam.html#setCompressionQuality(float)) * [`ImageWriter.write`](http://java.sun.com/javase/6/docs/api/javax/imageio/ImageWriter.html#write(javax.imageio.metadata.IIOMetadata,%20javax.imageio.IIOImage,%20javax.imageio.ImageWriteParam)) That said, as the other answers mention, JPEG is unsuitable for compression of text and illustrations. If the goal is to preserve the image quality, but the file size can be bigger than with compression with JPEG, then using an [lossless image compression](http://en.wikipedia.org/wiki/Lossless_data_compression) format such as [PNG](http://en.wikipedia.org/wiki/Portable_Network_Graphics) would preserve the image quality as it is, without any loss. However, in many cases, the file size of a PNG file will be larger than a JPEG. (But this is not always the case.) The general rule of thumb is, for photographs and other realistic images, lossy compression formats such as JPEG will work well for the file size vs. quality trade off, while lossless compression formats such as PNG will work better for illustrations and line art, where there are large areas of similar color with little gradient effects.
JPEG is specially bad for images with text inside. A good alternative is .PNG.
Why the jpg file I converted from a gif file isn't crisp and clear?
[ "", "java", "compression", "jpeg", "gif", "javax.imageio", "" ]
I am using rxtx api to read data from a GPS device over a com port. Right now I'm finding the correct com port by reading a config file and looking for the port listed. The problem that I'm having is that if the device is unplugged the com port could change then the user has to know to change the config file. I wrote an app similar to this in c# and was able to list the windows device name instead of the com port and I cycled through the com ports until the device name matched the name in the config file. Using that method nothing in the config file has to change even if the com port being used changes. Is there a way to do that with the rxtx api? Thanks in advance!
If anyone is interested... I created a windows service in C# that monitors a socket. If a client connects to that socket the service gathers port name, and device id that is on that port and sends the data in a string over the com port the client can then parse apart the string to get the data it needs. In my case the string being passed is: "ACPI\PNP0501 \*PNP0501 ,COM1 ,PCI\VEN\_8086&DEV\_29B7&SUBSYS\_02111028&REV\_02 PCI\VEN\_8086&DEV\_29B7&SUBSYS\_02111028 PCI\VEN\_8086&DEV\_29B7&CC\_070002 PCI\VEN\_8086&DEV\_29B7&CC\_0700 ,COM3 ,USB\Vid\_067b&Pid\_2303&Rev\_0400 USB\Vid\_067b&Pid\_2303 ,COM5" When I parse it I can see that ACPI\PNP0501 \*PNP0501 is the device id for COM 1, there are three device id's for COM3, and two device ids on COM5. This may not be the best way to handle this but it is good enough for my needs and it saved me from JNI. :)
If you want to get the name associated with the device on the COM port (particularly if a driver is installed to provide it), you'll have to do so with a smidge of the dreaded Java->Native Interface to talk to the Windows APIs that gather this information. C# is nice, in that this information is gathered and provided to you, but in Java you have to go this extra step. [Windows Function Discovery](http://msdn.microsoft.com/en-us/library/aa363892(VS.85).aspx) may prove useful. I'm not certain exactly what API provides this functionality.
rxtx com port
[ "", "java", "serial-port", "rxtx", "" ]
Scenario. Language C#, Unit testing using VS2008 Unit testing framework I have a static class with a static constructor and 2 methods. I have 4 test methods written to test the entire class. My Static Constructor has some important initializations. Now if I run all the 4 unit test cases in tandem, the static constructor will be called only at the beginning. At the end of each test case, there is no such thing called static destructor, So the state info in the constructor gets carried to the next unit test case also. What is the workaround for this.
The simplest solution is to add a "Reset" method to your static class, which would have the equivalent behaviour of destructing it and reconstructing it. There may be a valid reason why you are using a static class here. However, because statics don't play nicely with unit tests, I usually search for an alternative design.
``` Type staticType = typeof(StaticClassName); ConstructorInfo ci = staticType.TypeInitializer; object[] parameters = new object[0]; ci.Invoke(null, parameters); ``` from <http://colinmackay.scot/2007/06/16/unit-testing-a-static-class/>
UnitTesting Static Classes
[ "", "c#", ".net", "unit-testing", "" ]
I am looking for a way to create a class with a set of static properties. At run time, I want to be able to add other dynamic properties to this object from the database. I'd also like to add sorting and filtering capabilities to these objects. How do I do this in C#?
You might use a dictionary, say ``` Dictionary<string,object> properties; ``` I think in most cases where something similar is done, it's done like this. In any case, you would not gain anything from creating a "real" property with set and get accessors, since it would be created only at run-time and you would not be using it in your code... Here is an example, showing a possible implementation of filtering and sorting (no error checking): ``` using System; using System.Collections.Generic; using System.Linq; namespace ConsoleApplication1 { class ObjectWithProperties { Dictionary<string, object> properties = new Dictionary<string,object>(); public object this[string name] { get { if (properties.ContainsKey(name)){ return properties[name]; } return null; } set { properties[name] = value; } } } class Comparer<T> : IComparer<ObjectWithProperties> where T : IComparable { string m_attributeName; public Comparer(string attributeName){ m_attributeName = attributeName; } public int Compare(ObjectWithProperties x, ObjectWithProperties y) { return ((T)x[m_attributeName]).CompareTo((T)y[m_attributeName]); } } class Program { static void Main(string[] args) { // create some objects and fill a list var obj1 = new ObjectWithProperties(); obj1["test"] = 100; var obj2 = new ObjectWithProperties(); obj2["test"] = 200; var obj3 = new ObjectWithProperties(); obj3["test"] = 150; var objects = new List<ObjectWithProperties>(new ObjectWithProperties[]{ obj1, obj2, obj3 }); // filtering: Console.WriteLine("Filtering:"); var filtered = from obj in objects where (int)obj["test"] >= 150 select obj; foreach (var obj in filtered){ Console.WriteLine(obj["test"]); } // sorting: Console.WriteLine("Sorting:"); Comparer<int> c = new Comparer<int>("test"); objects.Sort(c); foreach (var obj in objects) { Console.WriteLine(obj["test"]); } } } } ```
If you need this for data-binding purposes, you can do this with a custom descriptor model... by implementing `ICustomTypeDescriptor`, `TypeDescriptionProvider` and/or `TypeCoverter`, you can create your own `PropertyDescriptor` instances at runtime. This is what controls like `DataGridView`, `PropertyGrid` etc use to display properties. To bind to lists, you'd need `ITypedList` and `IList`; for basic sorting: `IBindingList`; for filtering and advanced sorting: `IBindingListView`; for full "new row" support (`DataGridView`): `ICancelAddNew` (phew!). It is a ***lot*** of work though. `DataTable` (although I hate it) is cheap way of doing the same thing. If you don't need data-binding, just use a hashtable ;-p Here's a [simple example](https://stackoverflow.com/questions/882214/data-binding-dynamic-data) - but you can do a lot more...
How do I create dynamic properties in C#?
[ "", "c#", "" ]
How can I convert the following `list` to a `string`? ``` list1= [[1, '1', 1], [2,'2',2], [3,'3',3]] Result: '1 1 1' '2 2 2' '3 3 3' ``` Thanks
ended up with this: ``` for a, b, c in data: print(repr(a)+' '+repr(b)+' '+repr(c)) ``` i had to write the output to a `textfile`, in which the write() method could only take type `str`, this is where the `repr()` function came in handy ``` repr()- Input: object; Output: str ``` ...shoulda stated I was working in Python tho...thanks for the input
Looks like Python. List comprehensions make this easy: ``` list1= [[1, '1', 1], [2,'2',2], [3,'3',3]] outlst = [' '.join([str(c) for c in lst]) for lst in list1] ``` Output: ``` ['1 1 1', '2 2 2', '3 3 3'] ```
convert nested lists to string
[ "", "python", "string", "list", "nested", "" ]
What is the best and quickest way to resize images on the client side using JavaScript? **EDIT: Sorry, I meant the best way to *display* an image resized on the client side..**
Easy. ``` <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>Client-Side Image Resize (Why?!)</title> <script type="text/javascript"> window.onload = function() { var url = "http://www.google.com/intl/en_ALL/images/logo.gif"; var img = new Image(); img.onload = function() { var w = parseInt((this.width + "").replace(/px/i, ""), 10); var h = parseInt((this.height + "").replace(/px/i, ""), 10); // 50% scale w = (w / 2) + "px"; h = (h / 2) + "px"; var htmlImg = document.createElement("img"); htmlImg.setAttribute("src", url); htmlImg.setAttribute("width", w); htmlImg.style.width = w; htmlImg.setAttribute("height", h); htmlImg.style.height = h; document.body.appendChild(htmlImg); } img.src = url; } </script> </head> <body> <h1>Look, I'm Resized!</h1> </body> </html> ```
If you are not too put off by flash, with flash10 now you have the choice of processing uploaded files on the client side before sending them to the server. So you could use a hidden/transparent/small flash object to allow the client to upload their image, have flash resize the image(it has some good image manipulation apis), then send the byte data to the server. the as3 core lib has a jpeg and png encoders if you want to encode the image to either format before uploading. If you don't have flash you can always download the flex 3(or 4) sdk and use flashdevelop to do it all gratis =)
How to display resized images on a web page while maintaining aspect ratio?
[ "", "javascript", "jquery", "image", "image-manipulation", "" ]
I am trying to upload a file to a sever using PHP. I cannot get it to work. Here is the code: ``` if( isset($_POST['Upload']) ) { //size condition if ( $_FILES['uploaded']['size'] > 350000) { $mesg = "Your file is too large.<br>"; exit; } if( move_uploaded_file($_FILES['uploaded']['tmp_name'], "upload/" . $_FILES['uploaded']['name'] ) ) { $mesg = "The file ". basename( $_FILES['uploaded']['name']). " has been uploaded"; } else { $mesg = "Sorry, there was a problem uploading your file."; } } else { $mesg = "Select a File to upload."; } ``` Here is the code for the form I am using to submit the file: ``` <? echo $mesg; ?> <br /><br /> <form enctype="multipart/form-data" action="" method="POST"> Please choose a file: <input name="uploaded" type="file" /><br /> <input type="submit" value="Upload" /> </form> ```
Your submit button does not have a name: ``` <input type="submit" value="Upload" /> ``` You are checking for `$_POST['Upload']`, so you probably want: ``` <input type="submit" value="Upload" name="Upload" /> ```
You need `enctype="multipart/form-data"` inside your `<form>` tag or nothing will be uploaded. For more, check out the [PHP manual](http://www.php.net/manual/en/features.file-upload.post-method.php). Also, I am not sure if you're just doing this to test the functionality, but you should be wary of putting uploaded files in a web accessible folder, especially with their original names. This leaves an open door for someone to upload a malicious script and potentially take over your server.
Problems uploading a file in php
[ "", "php", "html", "file", "upload", "file-upload", "" ]
Is there a plugin-less way of retrieving [query string](http://en.wikipedia.org/wiki/Query_string) values via jQuery (or without)? If so, how? If not, is there a plugin which can do so?
Use [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams#Browser_compatibility) to get parameters from the query string. For example: ``` const urlParams = new URLSearchParams(window.location.search); const myParam = urlParams.get('myParam'); ``` **Update: Jan-2022** Using [`Proxy()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) is [faster](https://jsben.ch/MeP5G) than using [`Object.fromEntries()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/fromEntries) and better supported. This approach comes with the caveat that you can no longer iterate over query parameters. ``` const params = new Proxy(new URLSearchParams(window.location.search), { get: (searchParams, prop) => searchParams.get(prop), }); // Get the value of "some_key" in eg "https://example.com/?some_key=some_value" let value = params.some_key; // "some_value" ``` **Update: June-2021** For a specific case when you need all query params: ``` const urlSearchParams = new URLSearchParams(window.location.search); const params = Object.fromEntries(urlSearchParams.entries()); ``` **Update: Sep-2018** You can use [URLSearchParams](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams#Browser_compatibility) which is simple and has [decent (but not complete) browser support](https://caniuse.com/urlsearchparams). ``` const urlParams = new URLSearchParams(window.location.search); const myParam = urlParams.get('myParam'); ``` **Original** You don't need jQuery for that purpose. You can use just some pure JavaScript: ``` function getParameterByName(name, url = window.location.href) { name = name.replace(/[\[\]]/g, '\\$&'); var regex = new RegExp('[?&]' + name + '(=([^&#]*)|&|#|$)'), results = regex.exec(url); if (!results) return null; if (!results[2]) return ''; return decodeURIComponent(results[2].replace(/\+/g, ' ')); } ``` **Usage:** ``` // query string: ?foo=lorem&bar=&baz var foo = getParameterByName('foo'); // "lorem" var bar = getParameterByName('bar'); // "" (present with empty value) var baz = getParameterByName('baz'); // "" (present with no value) var qux = getParameterByName('qux'); // null (absent) ``` NOTE: If a parameter is present several times (`?foo=lorem&foo=ipsum`), you will get the first value (`lorem`). There is no standard about this and usages vary, see for example this question: [Authoritative position of duplicate HTTP GET query keys](https://stackoverflow.com/questions/1746507/authoritative-position-of-duplicate-http-get-query-keys). NOTE: The function is case-sensitive. If you prefer case-insensitive parameter name, [add 'i' modifier to RegExp](https://stackoverflow.com/questions/3939715/case-insensitive-regex-in-javascript) NOTE: If you're getting a no-useless-escape eslint error, you can replace `name = name.replace(/[\[\]]/g, '\\$&');` with `name = name.replace(/[[\]]/g, '\\$&')`. --- This is an update based on the new [URLSearchParams specs](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams) to achieve the same result more succinctly. See answer titled "[URLSearchParams](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/901144#12151322)" below.
Some of the solutions posted here are inefficient. Repeating the regular expression search every time the script needs to access a parameter is completely unnecessary, one single function to split up the parameters into an associative-array style object is enough. If you're not working with the HTML 5 History API, this is only necessary once per page load. The other suggestions here also fail to decode the URL correctly. ``` var urlParams; (window.onpopstate = function () { var match, pl = /\+/g, // Regex for replacing addition symbol with a space search = /([^&=]+)=?([^&]*)/g, decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); }, query = window.location.search.substring(1); urlParams = {}; while (match = search.exec(query)) urlParams[decode(match[1])] = decode(match[2]); })(); ``` Example querystring: > `?i=main&mode=front&sid=de8d49b78a85a322c4155015fdce22c4&enc=+Hello%20&empty` Result: ``` urlParams = { enc: " Hello ", i: "main", mode: "front", sid: "de8d49b78a85a322c4155015fdce22c4", empty: "" } alert(urlParams["mode"]); // -> "front" alert("empty" in urlParams); // -> true ``` This could easily be improved upon to handle array-style query strings too. An example of this is [here](http://jsbin.com/adali3/2), but since array-style parameters aren't defined in [RFC 3986](https://www.rfc-editor.org/rfc/rfc3986) I won't pollute this answer with the source code. [For those interested in a "polluted" version, look at campbeln's answer below](https://stackoverflow.com/questions/901115/how-can-i-get-query-string-values-in-javascript/23401756#23401756). Also, as pointed out in the comments, `;` is a legal delimiter for `key=value` pairs. It would require a more complicated regex to handle `;` or `&`, which I think is unnecessary because it's rare that `;` is used and I would say even more unlikely that both would be used. If you need to support `;` instead of `&`, just swap them in the regex. --- If you're using a server-side preprocessing language, you might want to use its native JSON functions to do the heavy lifting for you. For example, in PHP you can write: ``` <script>var urlParams = <?php echo json_encode($_GET, JSON_HEX_TAG);?>;</script> ``` Much simpler! #UPDATED > A new capability would be to retrieve repeated params as following `myparam=1&myparam=2`. There is not a *specification*, however, most of the current approaches follow the generation of an array. ``` myparam = ["1", "2"] ``` So, this is the approach to manage it: ``` let urlParams = {}; (window.onpopstate = function () { let match, pl = /\+/g, // Regex for replacing addition symbol with a space search = /([^&=]+)=?([^&]*)/g, decode = function (s) { return decodeURIComponent(s.replace(pl, " ")); }, query = window.location.search.substring(1); while (match = search.exec(query)) { if (decode(match[1]) in urlParams) { if (!Array.isArray(urlParams[decode(match[1])])) { urlParams[decode(match[1])] = [urlParams[decode(match[1])]]; } urlParams[decode(match[1])].push(decode(match[2])); } else { urlParams[decode(match[1])] = decode(match[2]); } } })(); ```
How can I get query string values in JavaScript?
[ "", "javascript", "url", "plugins", "query-string", "" ]
I know i can use AJAX and SILVERLIGHT with my ASP.NET web page. But what do you think about using flash with asp.net? Can this be done? How can this be done? Would you recommend me using flash at all with ASP.NET? I will NOT be using WEB SERVICES, just a plain ASP.NET website. Thanks in advance! **EDIT:** What about performance issues???
I have used Flash in ASP.NET websites plenty. Software should always boil down to the best tool for the job, if Flash is the way you need to go for your RIA, then so be it. Remember, ASP.NET is nothing "new/different" ultimately, it is just a fancy HTML generator. Therefore, to use flash, you simply use the plain old HTML [OBJECT and EMBED tags](http://kb2.adobe.com/cps/415/tn_4150.html) to place the Flash on the page. The benefit of using things like ASP.NET (or any other framework) is that you can encapsulate the EMBED logic to use things like [swfObject](http://code.google.com/p/swfobject/).
flash is client side, what you use server side has very little impact on it.
Using FLASH with ASP.NET - YAY or NAY?
[ "", "c#", "asp.net", "vb.net", "flash", "flashdevelop", "" ]
How do I set the windows default printer in C#.NET?
Using the SetDefaultPrinter Windows API. [Here's how to pInvoke that.](http://www.pinvoke.net/default.aspx/winspool/SetDefaultPrinter.html?diff=y)
``` using System; using System.Drawing.Printing; using System.Windows.Forms; using System.Runtime.InteropServices; namespace WindowsFormsApplication1 { public partial class Form1 : Form { private void listAllPrinters() { foreach (var item in PrinterSettings.InstalledPrinters) { this.listBox1.Items.Add(item.ToString()); } } private void listBox1_SelectedValueChanged(object sender, EventArgs e) { string pname = this.listBox1.SelectedItem.ToString(); myPrinters.SetDefaultPrinter(pname); } public Form1() { InitializeComponent(); listAllPrinters(); } } public static class myPrinters { [DllImport("winspool.drv", CharSet = CharSet.Auto, SetLastError = true)] public static extern bool SetDefaultPrinter(string Name); } } ```
How do I set the windows default printer in C#?
[ "", "c#", "windows", "printing", "" ]
I need to add a script before the `</body>` tag, so instead of [modifying all the pages](https://stackoverflow.com/questions/962219/toughie-automatic-insertion-of-some-javascript-into-my-entire-website), I was wondering if I could configure the server to add some HTML before that tag for every HTML document being served?
**If** you have PHP installed on your server, you can set up the `auto_append` and/or `auto_prepend` directives in the php.ini file or .htaccess. You can also set up .html extensions to be parsed as PHP files by Apache, so every HTTP request for an .html document is sent back with a header and a footer automagically included. If PHP is set up, try adding these lines into your .htaccess: ``` AddType application/x-httpd-php .html php_value auto_prepend_file /var/www/public/foo.html ```
Apache can *handle* that using [mod\_layout](http://tangent.org/362/mod_layout.html) Here's a relevant article: [Advanced Apache Headers/Footers](http://wannabe.guru.org/scott/hobbies/apache/)
How to add some HTML to every HTML document served?
[ "", "javascript", "html", "server-configuration", "" ]
``` byte[] header = new byte[]{255, 216}; string ascii = Encoding.ASCII.GetString(header); ``` I expect ASCII to be equal to be FFD8 (JPEG SOI marker) Instead I get "????"
In this case you'd be better to compare the byte arrays rather than converting to string. If you must convert to string, I suggest using the encoding Latin-1 aka ISO-8859-1 aka Code Page 28591 encoding, as this encoding will map all bytes with hex values are in the range 0-255 to the Unicode character with the same hex value - convenient for this scenario. Any of the following will get this encoding: ``` Encoding.GetEncoding(28591) Encoding.GetEncoding("Latin1") Encoding.GetEncoding("ISO-8859-1") ```
Yes, that's because [ASCII](http://en.wikipedia.org/wiki/ASCII) is only 7-bit - it doesn't define any values above 127. Encodings typically decode unknown binary values to '?' (although this can be changed using [DecoderFallback](http://msdn.microsoft.com/en-us/library/system.text.decoderfallback.aspx)). If you're about to mention "extended ASCII" I suspect you actually want `Encoding.Default` which is "the default code page for the operating system"... [code page 1252](http://en.wikipedia.org/wiki/Windows-1252) on most Western systems, I believe. What characters were you expecting? EDIT: As per the accepted answer (I suspect the question was edited after I added my answer; I don't recall seeing anything about JPEG originally) you shouldn't convert binary data to text unless it's genuinely encoded text data. JPEG data is *binary* data - so you should be checking the actual bytes against the expected bytes. Any time you convert arbitrary binary data (such as images, music or video) into text using a "plain" text encoding (such as ASCII, UTF-8 etc) you risk data loss. If you *have* to convert it to text, use Base64 which is nice and safe. If you just want to compare it with expected binary data, however, it's best not to convert it to text at all. EDIT: Okay, here's a class to help image detection method for a given byte array. I haven't made it HTTP-specific; I'm not entirely sure whether you should really fetch the `InputStream`, read just a bit of it, and then fetch the stream again. I've ducked the issue by sticking to byte arrays :) ``` using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; public sealed class SignatureDetector { public static readonly SignatureDetector Png = new SignatureDetector(0x89, 0x50, 0x4e, 0x47); public static readonly SignatureDetector Bmp = new SignatureDetector(0x42, 0x4d); public static readonly SignatureDetector Gif = new SignatureDetector(0x47, 0x49, 0x46); public static readonly SignatureDetector Jpeg = new SignatureDetector(0xff, 0xd8); public static readonly IEnumerable<SignatureDetector> Images = new ReadOnlyCollection<SignatureDetector>(new[]{Png, Bmp, Gif, Jpeg}); private readonly byte[] bytes; public SignatureDetector(params byte[] bytes) { if (bytes == null) { throw new ArgumentNullException("bytes"); } this.bytes = (byte[]) bytes.Clone(); } public bool Matches(byte[] data) { if (data == null) { throw new ArgumentNullException("data"); } if (data.Length < bytes.Length) { return false; } for (int i=0; i < bytes.Length; i++) { if (data[i] != bytes[i]) { return false; } } return true; } // Convenience method public static bool IsImage(byte[] data) { return Images.Any(detector => detector.Matches(data)); } } ```
c# and Encoding.ASCII.GetString
[ "", "c#", "encoding", "ascii", "" ]
I have a Form that gets the name of one of its Labels from a text file. This works fine when starting the app. But from another Form that text file changes and I would like that Label to change accordingly. This refresh takes place when the Form that made those text files changes took place closes. I thought Refreshing it would do the same thing as what happens when I use the MainForm\_Load. But I guess not. Could I be doing something wrong or just misunderstand what Refresh does? Thanks
The `Refresh` method only calls the `Invalidate` method, so it just causes a repaint of the controls with their current data. Put the code that gets the data from the text file in a separate method, so that you can call it both from the `Load` event handler, and from any code that needs to cause the reload.
All the Refresh method on a form does is Invalidate the form then calls Update (which boils down to a [UpdateWindow](http://msdn.microsoft.com/en-us/library/dd145167(VS.85).aspx) call) One way to solve your problem is to use the FileSystemWatcher object to monitor your text file for changes. When a change is detected, it can then call your code that opens the file and outputs the data to your label. ``` FileSystemWatcher fsw = new FileSystemWatcher(); fsw.Path = @"c:\temp"; // path to file fsw.Filter = "yourfile.txt"; fsw.Changed += fsw_Changed; fsw.EnableRaisingEvents = true; ``` Then in your changed event you just defined ``` void fsw_Changed(object sender, FileSystemEventArgs e) { updateLabelFromTextFile(); } private void updateLabelFromTextFile() { var fs = File.OpenText(@"c:\temp\yourfile.txt"); string sContent = fs.ReadToEnd(); fs.Close(); fs.Dispose(); if (label1.InvokeRequired) { MethodInvoker mi = delegate { label1.Text = sContent; }; this.BeginInvoke(mi); } else label1.Text = sContent; } ``` Note that FileSystemWatcher events are fired in a separate thread, thus the need for the BeginInvoke. Here is a link to an [example](http://www.c-sharpcorner.com/UploadFile/thiagu304/FileSystemWatcher03192007133144PM/FileSystemWatcher.aspx) (just do a search on FileSystemWatcher and you'll find tons more examples).
MainForm.Refresh(); doesn't do what I thought it would do
[ "", "c#", "winforms", "" ]
I have a table of dates call [BadDates], it has just one column where every record is a date to exclude. I have a UDF as follows: ``` CREATE FUNCTION [dbo].[udf_GetDateInBusinessDays] ( @StartDate datetime, --Start Date @NumberDays int --Good days ahead ) RETURNS datetime AS BEGIN -- Declare the return variable here DECLARE @ReturnDate datetime SET @ReturnDate = @StartDate DECLARE @Counter int SET @Counter = 0 WHILE @Counter < @NumberDays BEGIN SET @ReturnDate = DateAdd(d,1,@ReturnDate) IF ((SELECT COUNT(ID) FROM dbo.[BadDates] WHERE StartDate = @ReturnDate) = 0) BEGIN SET @Counter = @Counter + 1 END END RETURN @ReturnDate END ``` This UDF works great, but it is slow in processing. The stored procedure that uses this runs the UDF in every record. Is there other ways to provide this same functionality in a faster method. Any help is greatly appreciated!
I haven't tested this but in theory it should work. I add up the number of days. Then I check if there were any baddates in that range. If there were I add the number of bad days and check if there were anymore baddates in the range I just added. Repeat until no bad dates. ``` CREATE FUNCTION [dbo].[udf_GetDateInBusinessDays] ( @StartDate datetime, --Start Date @NumberDays int --Good days ahead ) RETURNS datetime AS BEGIN -- Declare the return variable here DECLARE @ReturnDate datetime SET @ReturnDate = dateadd(d, @NumberDays, @StartDate); DECLARE @d int; SET @d = (select count(1) from baddates where startdate >= @StartDate and startdate <= @ReturnDate); declare @t datetime; WHILE @d > 0 BEGIN set @t = @ReturnDate; set @ReturnDate = dateadd(d, @d, @ReturnDate); SET @d = (select count(1) from baddates where startdate > @t and startdate <= @ReturnDate); END RETURN @ReturnDate END ```
I'm assuming that what you are trying to do is calculate the date that is x working days past a given date.e.g. what date is 10 working days from today. I am also assuming that your baddates table contains non-working days e.g. Weekends and bank holidays. I have encountered similar requirements in the past and usually ended up with days table that contains all possible dates along with a flag that indicates whether a particular date is a working day or not. I then use that table to calculate what date is x working days from the provided date by selecting the record that is x days after the starting date. So something like this ``` CREATE TABLE all_days ( dated DATETIME, day_state CHAR(1) ) ``` Where day\_state is value of D - Working Day W - Weekend B - Bank Holiday The SQL to find the date after x working days then becomes ``` SELECT MAX(dated) FROM ( SELECT TOP(@number_days) dated FROM all_days WHERE day_state = 'D' AND dated >= @start_date ORDER by dated ASC ) ``` This code is untested but should give you the general idea. You may not want to differentiate between weekends and public holidays in which case you could rename the day\_state to working\_day and make it a BIT field. You should create a composite unique index on dated and day\_state.
Help with slow UDF in SQL Server 2005
[ "", "sql", "recursion", "performance", "user-defined-functions", "" ]
We all know that throwing pointers to exception is bad: ``` try { ... throw new MyExceptionClass(); } catch (MyExceptionClass* e) { ... } ``` What's your approach to cleaning the catch targets up in legacy code? I figure that I can fix the first part by making `operator new` private: ``` class MyExceptionClass { public: ... private: void* operator new(size_t); } ``` How can I make the catch side of things equally ugly at compile-time? I don't want to just cause this to fall into the `catch (...)` territory.
If I understand you correctly, you want to turn a bad practice into a compilation error. By making the exception type non-heap-allocatable, you've managed to make this illegal: ``` throw new MyExceptionClass(); ``` Alas, the next part can't be done like you want it. There's no way to make the catch block illegal. Although, if you've made it illegal to heap-allocate MyExceptionClass, there's no need to worry about the catch blocks. It'll just be wasted space. If you want to enforce not catching by a pointer, you want a lint-like tool. I'd recommend looking at [EDoC++](http://edoc.sourceforge.net/index.html). It's a modified gcc compiler to check for proper exception usage.
There is nothing you can do to prevent catching by pointer, aside from static analysis tools or code review. However, if you make it nearly impossible to throw a `MyExceptionClass` pointer, a `catch(MyExceptionClass*)` block will be dead code. To more completely prevent throwing by pointer, you'll actually need to do some more work. **Hide all forms of operator new --** See [here](https://stackoverflow.com/questions/10985/how-to-prevent-an-object-being-created-on-the-heap/11299#11299). **Hide the address-of operator --** Throwing the address of a previously allocated object carries some of the same issues of throwing a heap-allocated object. ``` class MyExceptionClass { private: MyExceptionClass* operator&(); } ```
Pointer-to-Exception Clean-Up
[ "", "c++", "exception", "legacy", "" ]
I've been playing around with what I thought was a simple idea. I want to be able to read in a file from somewhere (website, filesystem, ftp), perform some operations on it (compress, encrypt, etc.) and then save it somewhere (somewhere may be a filesystem, ftp, or whatever). It's a basic pipeline design. What I would like to do is to read in the file and put it onto a MemoryStream, then perform the operations on the data in the MemoryStream, and then save that data in the MemoryStream somewhere. I was thinking I could use the same Stream to do this but run into a couple of problems: 1. Everytime I use a StreamWriter or StreamReader I need to close it and that closes the stream so that I cannot use it anymore. That seems like there must be some way to get around that. 2. Some of these files may be big and so I may run out of memory if I try to read the whole thing in at once. I was hoping to be able to spin up each of the steps as separate threads and have the compression step begin as soon as there is data on the stream, and then as soon as the compression has some compressed data available on the stream I could start saving it (for example). Is anything like this easily possible with the C# Streams? ANyone have thoughts as to how to accomplish this best? Thanks, Mike
Using a helper method to drive the streaming: ``` static public void StreamCopy(Stream source, Stream target) { byte[] buffer = new byte[8 * 1024]; int size; do { size = source.Read(buffer, 0, 8 * 1024); target.Write(buffer, 0, size); } while (size > 0); } ``` You can easily combine whatever you need: ``` using (FileStream iFile = new FileStream(...)) using (FileStream oFile = new FileStream(...)) using (DeflateStream oZip = new DeflateStream(outFile, CompressionMode.Compress)) StreamCopy(iFile, oZip); ``` Depending on what you are actually trying to do, you'd chain the streams differently. This also uses relatively little memory, because only the data being operated upon is in memory.
StreamReader/StreamWriter *shouldn't* have been designed to close their underlying stream -- that's a horrible misfeature in the BCL. But they do, they won't be changed (because of backward compatibility), so we're stuck with this disaster of an API. But there are some well-established workarounds, if you want to use StreamReader/Writer but keep the Stream open afterward. * For a StreamReader: don't Dispose the StreamReader. It's that simple. It's harmless to just let a StreamReader go without ever calling Dispose. The only effect is that your Stream won't get prematurely closed, which is actually a plus. * For a StreamWriter: there may be buffered data, so you can't get away with just letting it go. You have to call Flush, to make sure that buffered data gets written out to the Stream. *Then* you can just let the StreamWriter go. (Basically, you put a Flush where you normally would have put a Dispose.)
Stream Reuse in C#
[ "", "c#", "" ]
I'm using pycurl to access a JSON web API, but when I try to use the following: ``` ocurl.setopt(pycurl.URL, gaurl) # host + endpoint ocurl.setopt(pycurl.RETURNTRANSFER, 1) ocurl.setopt(pycurl.HTTPHEADER, gaheader) # Send extra headers ocurl.setopt(pycurl.CUSTOMREQUEST, "POST") # HTTP POST req ocurl.setopt(pycurl.CONNECTTIMEOUT, 2) ``` and execute the script, it fails. ``` File "getdata.py", line 46, in apicall ocurl.setopt(pycurl.RETURNTRANSFER, 1) AttributeError: 'module' object has no attribute 'RETURNTRANSFER' ``` I haven't a clue what's going on, and why RETURNTRANSFER doesn't appear to exist while all the other options do.
The manual shows the usage being [something like this](http://pycurl.sourceforge.net/doc/curlobject.html): ``` >>> import pycurl >>> import StringIO >>> b = StringIO.StringIO() >>> conn = pycurl.Curl() >>> conn.setopt(pycurl.URL, 'http://www.example.org') >>> conn.setopt(pycurl.WRITEFUNCTION, b.write) >>> conn.perform() >>> print b.getvalue() <HTML> <HEAD> <TITLE>Example Web Page</TITLE> </HEAD> <body> <p>You have reached this web page by typing &quot;example.com&quot;, &quot;example.net&quot;, or &quot;example.org&quot; into your web browser.</p> <p>These domain names are reserved for use in documentation and are not availabl e for registration. See <a href="http://www.rfc-editor.org/rfc/rfc2606.txt">RFC 2606</a>, Section 3.</p> </BODY> </HTML> ``` Seems a little roundabout, but I'm not a big fan of PycURL...
CURLOPT\_RETURNTRANSFER is not a libcurl option, it is but provided within the PHP/CURL binding
pycurl: RETURNTRANSFER option doesn't exist
[ "", "python", "curl", "libcurl", "pycurl", "attributeerror", "" ]
I've been having big problems in reproducing and finding the cause of a bug. The occurence seems entirely random, so I suspected an uninitialized variable somewhere. But then I found this piece of code: ``` CMyClass obj; // A obj.DoStuff(); if ( somebool ) { CMyClass obj; // B obj.DoStuff(); } obj.DoOtherStuff(); ``` It seems as though DoOtherStuff() is either done on "B", or that B.DoStuff() sometimes actually works on A - i.e. i DoStuff() is actually called on the first obj. Could this happen? I don't think I got a compiler warning (I've fixed the code now in hoping that it might help). It seems *very* likely that this piece of the actual code is where the bug I'm trying to find is, but there could of course be other reasons I haven't discovered yet.
The code, as written, should work. The first call to `DoStuff()` and the last call to `DoOtherStuff()` can only be sent to `A`. The call to `DoStuff()` inside the `if(somebool) { }` block can only be sent to `B`. From the [standard](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2005/n1905.pdf): > **3.3.2 Local scope** > > 1. A name declared in a block (6.3) is local to that block. Its potential scope begins at its point of declaration (3.3.1) and > ends at the end of its declarative region. And: > **3.3.7 Name hiding** > > 1. A name can be hidden by an explicit declaration of that same name in a nested declarative region or derived class (10.2). That being said, perhaps this is not what was *intended* by the author of that code. If the variables have the same name, perhaps the intent is to have only one instance of that variable, and the `B` instance created inside the loop is a mistake. Have you gone through the logic to see if a second instance makes sense?
Unless `obj.DoStuff()` makes a change to a some global object then as Valentin points out it should all be self contained within the scope of the if statement
Can this cause undefined behaviour?
[ "", "c++", "undefined", "" ]
I have created a multidimensional array in Python like this: ``` self.cells = np.empty((r,c),dtype=np.object) ``` Now I want to iterate through all elements of my twodimensional array, and I do not care about the order. How do I achieve this?
It's clear you're using numpy. With numpy you can just do: ``` for cell in self.cells.flat: do_somethin(cell) ```
If you need to change the values of the individual cells then ndenumerate (in numpy) is your friend. Even if you don't it probably still is! ``` for index,value in ndenumerate( self.cells ): do_something( value ) self.cells[index] = new_value ```
Iterating through a multidimensional array in Python
[ "", "python", "arrays", "multidimensional-array", "numpy", "iteration", "" ]
What is the best way to reference or include a file using Javascript, looking for the closest functionality of PHP's include() ability.
I would check out [Javascript equivalent for PHP's include](http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_include/): > This article is part of the 'Porting > PHP to Javascript' Project, which aims > to decrease the gap between developing > for PHP & Javascript. There is no direct equivalent - you can either go with the function I linked above or use `document.write` to write out a new `script` tag with a `src` pointing to the file you wish to include. **Edit:** Here is a rudimentary example of what I mean: ``` function include(path) { document.write( "<script type=\"text/javascript\" src=\"" + path + "\"></script>" ); } ``` **Edit 2:** Ugh, what an ugly example - here is a better one: ``` function include(path) { script = document.createElement("script"); script.setAttribute("type", "text/javascript"); script.setAttribute("src", path); if (head = document.getElementsByTagName("head")[0]) { head.appendChild(script); } } ``` `document.write` is a hackish way of doing things and I shouldn't have recommended it. If you go with one of my examples please use the second one.
I have a script that I wrote a while back (using [Mootools](http://mootools.net)) that allows for one to include javascript files on the fly (with a callback function after its loaded). You can modify it to work the library of your choice if you choose. Note the `gvi` prefix is just my namespace and that gvi.scripts is an array containing all the javascript files currently included on the page, those can be removed if you want. Also, the `filename` function can be removed, that was just added to make my life easier [`require('some-script')` vs `require('js/some-script.js')`]. ``` //if dom isn't loaded, add the function to the domready queue, otherwise call it immediately gvi.smartcall = function(fn) { return (Browser.loaded) ? fn() : window.addEvent('domready', fn); } //For dynamic javascript loading gvi.require = function(files, callback, fullpath) { callback = callback || $empty; fullpath = fullpath || false; var filename = function(file) { if (fullpath == true) return file; file = ( file.match( /^js\/./ ) ) ? file : "js/"+file; return ( file.match( /\.js$/ ) ? file : file+".js" ); } var exists = function(src) { return gvi.scripts.contains(src); } if ($type(files) == "string") { var src = filename(files); if (exists(src)) { gvi.smartcall(callback); } else { new Asset.javascript( src, { 'onload' : function() { gvi.scripts.push(src); gvi.smartcall(callback); } }); } } else { var total = files.length, loaded = 0; files.each(function(file) { var src = filename(file); if (exists(src) && loaded == total) { gvi.smartcall(callback); } else if (exists(src)) { loaded++; } else { new Asset.javascript( src, { 'onload' : function() { gvi.scripts.push(src); loaded++; if (loaded == total) gvi.smartcall(callback); } }); } }); } } ``` And you call it like ``` gvi.require('my-file', function() { doStuff(); }); //or gvi.require(['file1', 'file2'], function() { doStuff(); }); ```
What comparable Javascript function can reference a file like PHP's include()?
[ "", "php", "ajax", "include", "" ]
I have some SerialPort code that constantly needs to read data from a serial interface (for example COM1). But this seems to be very CPU intensive and if the user moves the window or a lot of data is being displayed to the window (such as the bytes that are received over the serial line) then communication gets messed up. Considering the following code: ``` void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { byte[] buffer = new byte[port.ReadBufferSize]; var count = 0; try { count = port.Read(buffer, 0, buffer.Length); } catch (Exception ex) { Console.Write(ex.ToString()); } if (count == 0) return; //Pass the data to the IDataCollector, if response != null an entire frame has been received var response = collector.Collect(buffer.GetSubByteArray(0, count)); if (response != null) { this.OnDataReceived(response); } ``` The code needs to be collected as the stream of data is constant and the data has to be analyzed for (frames/packets). ``` port = new SerialPort(); //Port configuration code here... this.collector = dataCollector; //Event handlers port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived); port.Open(); ``` If there is no user interaction and nothing being added to the window, this works fine but as soon as there is interaction communication really gets messed up. Timeouts occur etc.... For example, this messes everything up: ``` Dispatcher.BeginInvoke(new Action(() => { var builder = new StringBuilder(); foreach (var r in data) { builder.AppendFormat("0x{0:X} ", r); } builder.Append("\n\n"); txtHexDump.AppendText(builder.ToString()); txtHexDump.ScrollToEnd(); }),System.Windows.Threading.DispatcherPriority.ContextIdle); }); ``` But even simple calls to log4net cause problems. Are there any best practices to optimize SerialPort communication or can someone tell me what I'm doing wrong... **Update:** In case the above didn't make much sence. I made a very simple (and stupid) little example: ``` class Program { static void Main(string[] args) { var server = new BackgroundWorker(); server.DoWork += new DoWorkEventHandler(server_DoWork); server.RunWorkerAsync(); var port = new SerialPort(); port.PortName = "COM2"; port.Open(); string input = ""; Console.WriteLine("Client on COM2: {0}", Thread.CurrentThread.ManagedThreadId); while (input != "/quit") { input = Console.ReadLine(); if (input != "/quit") { var data = ASCIIEncoding.ASCII.GetBytes(input); port.Write(data, 0, data.Length); } } port.Close(); port.Dispose(); } static void server_DoWork(object sender, DoWorkEventArgs e) { Console.WriteLine("Listening on COM1: {0}", Thread.CurrentThread.ManagedThreadId); var port = new SerialPort(); port.PortName = "COM1"; port.Open(); port.ReceivedBytesThreshold = 15; port.DataReceived += new SerialDataReceivedEventHandler(port_DataReceived); } static void port_DataReceived(object sender, SerialDataReceivedEventArgs e) { var port = (SerialPort)sender; int count = 0; byte[] buffer = new byte[port.ReadBufferSize]; count = ((SerialPort)sender).Read(buffer, 0, buffer.Length); string echo = ASCIIEncoding.ASCII.GetString(buffer,0,count); Console.WriteLine("-->{1} {0}", echo, Thread.CurrentThread.ManagedThreadId); } } ``` The result might look like this: Listening on COM1: 6 Client on COM2: 10 This is some sample data that I send ---> 6 This is some sample data that I send So reading the data from the port happens on the main thread.... Might this be part of what's causing my problems?
Your last conclusion, that the event runs on the Main thread, may not be true for Windows App. Don't test this in a Console. The proper way to tune this is: * set a large enough buffer, although the minimum 4096 is usually Ok * set the ReceivedBytesThreshold as high as tolerable (and do it **before** the Open()) * do as little as possible in the Received event, pass the data to a Queue or MemoryStream if you need more time
I am surprised no one caught this. The SerialPort class utilizes its own thread when using the DataReceived event. This means that if the subscriber, for example, is accessing any Form elements, then it must be done so with either an Invoke, or BeginInvoke method(s). Otherwise, you end up with a cross thread operation. In older versions of .net, this would go along unnoticed with unpredictable behaviour (depending on the CPU cores in the PC) and in later versions, should raise an exception.
System.IO.Ports.SerialPort and Multithreading
[ "", "c#", ".net", "performance", "serial-port", "" ]
I need a few global variables that I need in all `.js` files. For example, consider the following 4 files: 1. `global.js` 2. `js1.js` 3. `js2.js` 4. `js3.js` Is there a way that I can declare 3 global variables in `global.js` and access them in any of the other 3 `.js` files considering I load all the above 4 files into a HTML document? Can someone please tell me if this is possible or is there a work around to achieve this?
Just define your variables in global.js outside a function scope: ``` // global.js var global1 = "I'm a global!"; var global2 = "So am I!"; // other js-file function testGlobal () { alert(global1); } ``` To make sure that this works you have to include/link to global.js before you try to access any variables defined in that file: ``` <html> <head> <!-- Include global.js first --> <script src="/YOUR_PATH/global.js" type="text/javascript"></script> <!-- Now we can reference variables, objects, functions etc. defined in global.js --> <script src="/YOUR_PATH/otherJsFile.js" type="text/javascript"></script> </head> [...] </html> ``` You could, of course, link in the script tags just before the closing <body>-tag if you do not want the load of js-files to interrupt the initial page load.
The recommended approach is: ``` window.greeting = "Hello World!" ``` You can then access it within any function: ``` function foo() { alert(greeting); // Hello World! alert(window["greeting"]); // Hello World! alert(window.greeting); // Hello World! (recommended) } ``` This approach is preferred for two reasons. 1. The intent is explicit. The use of the `var` keyword can easily lead to declaring global `vars` that were intended to be local or vice versa. This sort of variable scoping is a point of confusion for a lot of Javascript developers. So as a general rule, I make sure all variable declarations are preceded with the keyword `var` or the prefix `window`. 2. You standardize this syntax for reading the variables this way as well which means that a locally scoped `var` doesn't clobber the global `var` or vice versa. For example what happens here is ambiguous: ``` greeting = "Aloha"; function foo() { greeting = "Hello"; // overrides global! } function bar(greeting) { alert(greeting); } foo(); bar("Howdy"); // does it alert "Hello" or "Howdy" ? ``` However, this is much cleaner and less error prone (you don't really need to remember all the variable scoping rules): ``` function foo() { window.greeting = "Hello"; } function bar(greeting) { alert(greeting); } foo(); bar("Howdy"); // alerts "Howdy" ```
How to declare a global variable in a .js file
[ "", "javascript", "global-variables", "" ]
While I know that by definition a boolean consists of only two states, true or false. I was wondering what value does a boolean have before it is initialized with one of these states.
[It defaults to false.](http://java.sun.com/docs/books/tutorial/java/nutsandbolts/datatypes.html) **Edit:** By popular demand: > unless you're using the wrapped [Boolean](http://java.sun.com/javase/6/docs/api/java/lang/Boolean.html), which defaults to null. – sudhir.j
If it is a local variable, it is a compiler error to reference it before it was initialized. If it is a field, it is initialized to false.
What is the third boolean state in java?
[ "", "java", "boolean", "primitive", "" ]
I am trying to build a query such that some column are built up from a previous matching row. For example with the following data: ``` CREATE TABLE TEST (SEQ NUMBER, LVL NUMBER, DESCR VARCHAR2(10)); INSERT INTO TEST VALUES (1, 1, 'ONE'); INSERT INTO TEST VALUES (2, 2, 'TWO1'); INSERT INTO TEST VALUES (3, 2, 'TWO2'); INSERT INTO TEST VALUES (4, 3, 'THREE1'); INSERT INTO TEST VALUES (5, 2, 'TWO3'); INSERT INTO TEST VALUES (6, 3, 'THREE2'); COMMIT ``` I want the following data retrieved. ``` SEQ L1 L2 L3 1 ONE NULL NULL 2 ONE TWO1 NULL 3 ONE TWO2 NULL 4 ONE TWO2 THREE1 5 ONE TWO3 THREE1 5 ONE TWO3 THREE2 ``` ie for row 3, it itself has the value for L2, for L1 it has to go to the most recent row that contains L1 data, in this case the first row. I have tried looking at analytics and the connect clause but can't get my head around a solution. Any ideas?
**Update**: there is a much simpler solution than my first answer. It is more readable AND more elegant, I will therefore put it here first (As often, thanks to [Tom Kyte](http://asktom.oracle.com/pls/asktom/f?p=100:11:0::::P11_QUESTION_ID:1769805100346245044 "Ask Tom")): ``` SQL> SELECT seq, 2 last_value(CASE 3 WHEN lvl = 1 THEN 4 descr 5 END IGNORE NULLS) over(ORDER BY seq) L1, 6 last_value(CASE 7 WHEN lvl = 2 THEN 8 descr 9 END IGNORE NULLS) over(ORDER BY seq) L2, 10 last_value(CASE 11 WHEN lvl = 3 THEN 12 descr 13 END IGNORE NULLS) over(ORDER BY seq) L3 14 FROM TEST; SEQ L1 L2 L3 ---------- ---------- ---------- ---------- 1 ONE 2 ONE TWO1 3 ONE TWO2 4 ONE TWO2 THREE1 5 ONE TWO3 THREE1 6 ONE TWO3 THREE2 ``` Following is my initial solution: ``` SQL> SELECT seq, 2 MAX(L1) over(PARTITION BY grp1) L1, 3 MAX(L2) over(PARTITION BY grp2) L2, 4 MAX(L3) over(PARTITION BY grp3) L3 5 FROM (SELECT seq, 6 L1, MAX(grp1) over(ORDER BY seq) grp1, 7 L2, MAX(grp2) over(ORDER BY seq) grp2, 8 L3, MAX(grp3) over(ORDER BY seq) grp3 9 FROM (SELECT seq, 10 CASE WHEN lvl = 1 THEN descr END L1, 11 CASE WHEN lvl = 1 AND descr IS NOT NULL THEN ROWNUM END grp1, 12 CASE WHEN lvl = 2 THEN descr END L2, 13 CASE WHEN lvl = 2 AND descr IS NOT NULL THEN ROWNUM END grp2, 14 CASE WHEN lvl = 3 THEN descr END L3, 15 CASE WHEN lvl = 3 AND descr IS NOT NULL THEN ROWNUM END grp3 16 FROM test)) 17 ORDER BY seq; SEQ L1 L2 L3 ---------- ---------- ---------- ---------- 1 ONE 2 ONE TWO1 3 ONE TWO2 4 ONE TWO2 THREE1 5 ONE TWO3 THREE1 6 ONE TWO3 THREE2 ```
Do you have only 3 levels (or a fixed number of levels)? If so, you could use something like that, which is very inefficient but I believe works (I can't run it from this computer so it's a "blind" code that may require slight alterations): ``` SELECT COUNTER.SEQ AS SEQ, A.DESCR AS L1, B.DESCR AS L2, C.DESCR AS L3 FROM TABLE AS COUNTER, TABLE AS A, TABLE AS B, TABLE AS C WHERE A.SEQ = (SELECT MAX(D.SEQ) FROM TABLE AS D WHERE D.LVL = 1 AND D.SEQ <= COUNTER.SEQ) AND B.SEQ = (SELECT MAX(D.SEQ) FROM TABLE AS D WHERE D.LVL = 2 AND D.SEQ <= COUNTER.SEQ) AND C.SEQ = (SELECT MAX(D.SEQ) FROM TABLE AS D WHERE D.LVL = 3 AND D.SEQ <= COUNTER.SEQ) ```
Oracle SQL Query (Analytics?)
[ "", "sql", "oracle", "analytics", "" ]
**Application**: HTA (therefore IE) This is an application that uses SendKeys to populate a FILE input field. **Issue**: File is never uploaded. **Description**: An offscreen form (invisible to user) uploads a file to the server. The file input is entered via SendKeys (javascript). Appears to be isolated to when IE8 is installed. --- Does anyone know of what may be causing this and any workarounds? *Sorry for lack of information. I will edit the question with additional information if no answers are submitted.*
IE8 has set the <input type="file"> element to read-only in order to prevent security attacks. (see [article](http://blogs.msdn.com/ie/archive/2008/07/02/ie8-security-part-v-comprehensive-protection.aspx)). Therefore a programmatic way isn't possible.
I actually solved this problem with an interesting trick. Here's how... Create an external vbscript 'include file' called 'vbshelper.inc' which contains the following code: ``` function stuffKeys(x) Set wshShell = CreateObject("WScript.Shell") wshShell.Sendkeys(x) end function ``` --- Inside your HTML code header, place the following lines as your first < Script> element... ``` <Script language="VBScript" src="vbshelper.inc"> function defaultFldr() stuffKeys(" C:\Temp\*.txt~") end function function do_something() . . . etc end function </Script> ``` [Note-1 There is a space before the C in ' C:\Temp\\*.txt~' and a tilde ( ~ ) after the .txt.] [Note-2 I had to specify Script type=VBScript and not type="text/vbscript". I'm not sure why this is required.] --- later, in your HTML code, create the button like this... ``` <input type="File" id="srcFile" onchange="do_something()" onclick="defaultFldr()"> ``` [Note-3: I tried to call the stuffKeys function right from the onclick command, but it didn't work. Probably because you have to use single quotes around the folder string.] So... You can't create the WScript object from within an HTML or HTA page, but it works when referenced from an external include file. Keep the 'vbshelper.inc' file in the same folder as your HTML or HTA file.
IE8 causing FILE input entry to be blank via SendKeys
[ "", "javascript", "html", "internet-explorer-8", "wsh", "hta", "" ]
Is the following supported across \*nix platforms? ``` #include <cstdio> #include <sys/types.h> #include <signal.h> #include <unistd.h> class SignalProcessor { public: static void OnMySignal(int sig_num) { printf("Caught %d signal\n", sig_num); fflush(stdout); return; } }; using namespace std; int main() { signal(SIGINT,SingalProcessor::OnMySignal); printf("Ouch\n"); pause(); return 0; } ```
Technically no you can't. You just happen to be getting lucky that your compiler is using the same calling convention that it uses for 'C' functions. As the C++ ABI is not defined the next version of the compiler is free to use a completely different calling convention and this will mess with your code with no warning from the compiler. See: <http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.2> See the note at the end of this section > Note: static member functions do not require an actual object to be invoked, > so pointers-to-static-member-functions are usually type-compatible with regular > pointers-to-functions. However, although it probably works on most compilers, > it actually would have to be an extern "C" non-member function to be correct, > since "C linkage" doesn't only cover things like name mangling, but also > calling conventions, which might be different between C and C++. Edit: To answer the comment by Sasha: Using threading as an example: ``` #include <iostream> class Thread { public: virtual void run() = 0; }; extern "C" void* startThrerad(void* data) { Thread* thread = reinterpret_cast<Thread*>(data); try { thread->run(); } catch(...) { /* Log if required. Don't let thread exit with exception. */ } return NULL; } class MyJob: public Thread { public: virtual void run() {std::cout << "HI\n";} }; int main() { MyJob job; // MyJob inherits from Thread pthread_t th; // In most situation you do not need to dynamic cast. // But if you use multiple inheritance then things may get // interesting, as such best to always use it. pthread_create(&th,NULL,startThrerad,dynamic_cast<Thread*>(&job)); void* result; pthread_join(th,&result); } ```
I do the equivalent with Windows thead procedures and other assorted callbacks, and RTX interrupts all the time. The only real gotchas are that the members have to be static (which you already figured out), and that you have to make sure your routine is set to use the standard C/system call calling convention. Sadly, how you do that is platform dependent. In Win32 it is with the "\_\_stdcall" modifier. Note that you can use the passback-in pointer paramteter to "convert" such calls into normal class method calls. Like so ("self\_calling\_callback" is the static method): ``` unsigned long __stdcall basic_thread::self_calling_callback (void *parameter) { if (parameter) { basic_thread * thread = reinterpret_cast<basic_thread *>(parameter); thread->action_callback(); } return 0; // The value returned only matters if someone starts calling GetExitCodeThread // to retrieve it. } basic_thread::basic_thread () { // Start thread. m_Handle = CreateThread(NULL, 0, self_calling_callback, (PVOID)this, 0, &m_ThreadId ); if( !IsHandleValid() ) throw StartException("CreateThread() failed", GetLastError()); } ```
Can the signal system call be used with C++ static members of the class?
[ "", "c++", "c", "linux", "signals", "unix", "" ]
i want to parse VB6 code via Regex. However being new to Regex I have encountered a few problems concerning the regexes to use. Currently, I have problems recognizing these constructs: ``` ' Subs ' Sub Test Private Sub Test(ByVal x as Integer) 'Private Sub Test(ByVal y as Integer) Dim dummy as String dummy = "Private Sub Test(ByVal y as Integer)" End Sub ``` I have basically these 2 problems: How do I write a Regex that matches the Sub definition, and includes the all commment (and empty) lines above its definition? And how can I prevent that the Sub definitions which are either disabled by comment or included in strings aren't matched? Plus I need to support definitions which are spanned over multiple lines, like this one: ``` ' Subs ' Sub Test Private Function Test2( _ ByVal x as Integer _ ) As Long 'Private Sub Test(ByVal y as Integer) Dim dummy as String dummy = "Private Sub Test(ByVal y as Integer)" End Function ``` Any hint would be greatly appreaciated. The solutions I've come up with don't work with multiple lines or capture more than just one Sub definition. It then just matches to the end of the last End Sub occurrence due to greedy matching. My try in C# currently looks like this: ``` (('(?<comment>[\S \t]+[\n\r]+))*((?<accessmodifier>(Private|Public))\s+_?)(?<functiontype>(Sub|Function))\s+_?(?<name>[\S]+)\((?<parameters>[\S \t]*)\)([ \t]+As[ \t]+(?<returntype>\w+))?)|(?<endfunction>End (Sub|Function)) ``` I'm using `Multiline`, `Singleline`, `IgnoreCase`, `ExplicitCapture`. Thanks for your help!
Why are you parsing this code? If you're trying to create your own compiler, you'll need a lot more than regexes. If you're writing an editor with syntax highlighting and type-ahead completion, regexes can do a pretty good job on the first, but not the second. That said, the biggest problem I see with your regex is that you're not handling line continuations properly. This: `\s+_?` matches one or more whitespace characters, optionally followed by an underscore. But if there is an underscore it should be followed by a newline, which you aren't matching. That's easy enough to remedy - `\s+(_\s+)?` - but I'm not sure you need to be that specific. I suspect this: `[\s_]+` will do just as well. As for avoiding apparent sub/function declarations inside comments and strings, the simplest way would be to match them only at the left margin, with maybe some tabs or spaces for indentation. It's cheating, I know, but it may be good enough for whatever you're doing. I relied heavily on that trick when I was writing a Java [file navigation scheme](http://www.editpadpro.com/fns.html) for EditPad Pro. You can't do this kind of thing with regexes without employing lots of gimmicks and simplifying assumptions. Try this regex: ``` ^(?>('(?<comment>.*[\n\r]+))*) [ \t]*(?<accessmodifier>(Private|Public)) [\s_]+(?<functiontype>(Sub|Function)) [\s_]+(?<name>\S+) [\s_]*\((?<parameters>[^()]*)\) ([\s_]+As[\s_]+(?<returntype>\w+))? | ^[ \t]*(?<endfunction>End (Sub|Function)) ``` Of course you'll need to reassemble it first. It should be compiled with the `Multiline`, `IgnoreCase` and `ExplicitCapture` options, but not `Singleline`.
I suspect that this won't be possible for all but the simplest cases. With regexps you can't parse recursive structures, and languages (such as VB) will have recursive features. See [this CodingHorror blog entry](http://www.codinghorror.com/blog/archives/000253.html) for more info. Unless you have very simple cases, I think some form of parser is going to be the way forward.
Regex spanning over multiple lines / recognzing commented lines
[ "", "c#", "regex", "" ]
I have a bit of a weird problem. I have a form with a Label in it for outputting text at certain points in the program instead of console output. Given the following code: ``` result = SetupDiGetDeviceRegistryProperty(deviceInfoSet, ref tBuff, (uint)SPDRP.DEVICEDESC, out RegType, ptrBuf, buffersize, out RequiredSize); if (!result) { errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message; statusLabel.Text += "\nSetupDiGetDeviceRegistryProperty failed because " + errorMessage.ToString(); } else { statusLabel.Text += "\nPtr buffer length is: " + ptrBuf.Length.ToString(); sw.WriteLine(tCode.GetString(ptrBuf) ); sw.WriteLine("\n"); // This is the only encoding that will give any legible output. // Others only show the first character "U" string tmp = tCode.GetString(ptrBuf) + "\n"; statusLabel.Text += "\nDevice is: " + tmp + ".\n"; } ``` I get just the one hardware ID output on the label. This piece of code is at the end of my loop. at 1st this made me think that my loop was some how hanging, but when I decided to direct output to a file I get almost what I want and the output outside the loop. Can anyone tell me what's going on here? All I want is to get the string representing the hardware ID from the []byte (**ptrBuf**). Can some explain what's going on here, please? My working environment is MSVstudio 2008 express. In windows 7. Thanks
You haven't shown what `tCode` is, unfortunately. Looking at the [docs for the API call](http://msdn.microsoft.com/en-us/library/ms792967.aspx) it looks like it should be populated with a REG\_SZ. I *suspect* that's Unicode, i.e. ``` string property = Encoding.Unicode.GetString(ptrBuf, 0, RequiredSize); ``` should convert it. However, if you're expecting multiple values, I wonder if it's a `'\0'`-separated string: trying to output that in a Win32 control will indeed stop at the first `'\0'`. Try this: ``` string property = Encoding.Unicode.GetString(ptrBuf, 0, RequiredSize); .Replace('\0', ' '); ``` That should (if I'm guessing correctly) space-separate the values.
You need to specify an encoding: ``` // C# to convert a byte array to a string. byte [] dBytes = ... string str; System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding(); str = enc.GetString(dBytes); ```
getting a string from a []byte in C#
[ "", "c#", ".net", "usb", "" ]
I'm not sure what I'm doing wrong here. I have a generic class, which is basically a glorified integer, with a few methods for certain string formatting, as well as into/from string and int conversions: ``` public class Base { protected int m_value; ... // From int public static implicit operator Base(int Value) { return new Base(Value); } ... // To string public static explicit operator string(Base Value) { return String.Format("${0:X6}", (int)Value); } } ``` And it functions fine. I can successfully use implicit and explicit conversions: ``` Base b = 1; Console.WriteLine((string)b); // Outputs "$000001", as expected. ``` Then I derive from this class, different child classes, which turn on/off different named bits in m\_value. For example: ``` public class Derived : Base { } ``` And then I cannot use my implicit to/from int conversions: ``` Derived d = 3; // Cannot implicitly convert type 'int' to 'Derived'. An explicit conversion exists (are you missing a cast?) ``` Even this gives the same error: ``` Derived d = (int)3; ``` Are the implicit/explicit conversions not inherited in the derived class? This will require a lot of code copying if not. **RESPONSE** Thank you so much for the quick responses! You all deserve the 'answer' checkmark, they're all very good answers. The key is to think about the types on both sides of the equal sign. Now that I think about it like that, it makes perfect sense. I obviously only have to re-write my "to Derived" conversions. The "to Int32, String, etc" conversions still apply.
The reason ``` Derived d = (int)3; ``` does not work is because the type `Derived` does not exactly match the return value of the operator `Base` as is required to invoke this operator. Notice that you haven't provided any conversion operators that contain the code `new Derived(...)`, so it is not surprising that you can't make new `Derived` instances this way. Note, however, that the opposite conversion ``` Derived v = ...; string s = (string)v; ``` will work fine (as if it were "inherited", although this is not really inheritance due to the `static` keyword).
Overloaded operators (including conversions) are inherited, but not in a way you seemingly expect them to. In particular, they aren't magically extended to operate on derived types. Let's look at your code again: ``` Derived d = 3; ``` At this point the compiler has two classes to work with, System.Int32, and Derived. So it looks for conversion operators in those classes. It will consider those inherited by Derived from Base, namely: ``` public static implicit operator Base(int Value); public static explicit operator string(Base Value); ``` The second one doesn't match because the argument should be an Int32. The first one does match the argument, but then it's return type is Base, and that one doesn't match. On the other hand, you can write this: ``` string s = (string) new Derived(); ``` And it will work, because the explicit operator in Base exists and is applicable (argument is expected to be Base, Derived inherits from Base and therefore matches the argument type). The reason why the compiler won't automagically redefine conversion operators in derived types "properly" is because there's no generic way to do so.
Are implicity/explicit conversion methods inherited in C#?
[ "", "c#", "inheritance", "" ]
Is there a way to get a standard Windows Forms application to detect if the `Shift` key is being held down on application startup - without using Windows hooks? I ideally would like the workflow to change from normal if the shift key is held down when the EXE file is run.
[Here is an article](http://www.switchonthecode.com/tutorials/winforms-accessing-mouse-and-keyboard-state) about reading the key states (and mouse) directly.
The ModifierKeys property looks ideal: ``` private void Form1_Load(object sender, EventArgs e) { if ( (ModifierKeys & Keys.Shift) != 0) { MessageBox.Show("Shift is pressed"); } } ```
Detect shift key on application startup in C#/Windows Forms
[ "", "c#", "winforms", "detect", "hotkeys", "shift", "" ]
Simple question, hopefully a simple answer: I'd like to do the following: ``` private DateTime m_internalDateTime; public var DateTimeProperty { get { return m_internalDateTime.ToString(); } // Return a string set { m_internalDateTime = value; } // here value is of type DateTime } ``` The above is just an example of what I'm trying to do. I'd like to have a public accessor to an internal variable of type x. I want the get that variable as a string, but set it using something of type x. Is this possible? --edit-- I just realized I could do something like: ``` private DateTime m_internalDateTime; public object DateTimeProperty { get { return m_internalDateTime.ToString(); } // Return a string set { m_internalDateTime = (DateTime)value; } // here value is of type DateTime } ``` But then, let say I use type y instead of a "string" as my 'get' type. If I want to use "DateTimeProperty" else where in my code, I'd have to cast it.
No. You can obviously add the .ToString() in the calling code, but you can't do what you propose without different names like this: ``` private DateTime m_internalDateTime; public DateTime SetDateTime { set { m_internalDateTime = value; } } public string GetDateTime { get { return m_internalDateTime.ToString(); } } ``` Or, even better to use methods instead of properties (as noted in the comments): ``` private DateTime m_internalDateTime; public void SetDateTime(DateTime dateTime) { m_internalDateTime = dateTime; } public string GetDateTime() { return m_internalDateTime.ToString(); } ``` Keep in mind that `var` is for *implicitly*, compile-time typed *var*iables, not *dynamic* variables. Definitely *do not* do what you noted in your edit. It introduced a break in convention, possible performance implications (albeit slight), and significant localization problems.
As a property, no this is not possible. You could make Get and Set methods that are of different types, but for a property the types must be the same. EDIT: While: ``` private DateTime m_internalDateTime; public object DateTimeProperty { get { return m_internalDateTime.ToString(); } // Return a string set { m_internalDateTime = (DateTime)value; } // here value is of type DateTime } ``` is syntactically correct, will compile and allows you to accept DateTime as input and return a string, this would not be a good plan. It works, but it makes you and anyone accessing this code, perform unneeded validation. Additionally, it is vulnerable to another developer in the future, not knowing, or realizing the implicit rules, for which you have lost compile time safety. Additionally, its hardly any more code to create either two properties, or two methods that accomplish the same goal, in a strongly typed manner. Personally, I would recommend using two methods (see Jeff Yates comment for a good explanation as to why). ``` private DateTime m_internalDateTime; public string GetDateTime() { return m_internalDateTime.ToString(); } public void SetDateTime(DateTime dateTime) { m_internalDateTime = dateTime; } ```
Accessor with different set and get types?
[ "", "c#", "variables", "types", "accessor", "" ]
Currently, I'm receiving the error "an object reference is required for the nonstatic field method or property". My code is as follows: ``` using MyApp.Global; namespace MyApp.MyNamespace { public class MyClass:System.Web.UI.Page { //Toolbox is inside Global, GetCurrentCookieData is a static method private CookieData cd = Toolbox.GetCurrentCookieData(HttpContext.Current); //the above was changed and resolved the first error, but another error //just popped up. Below, I get the error: cd denotes field //where class was expected private int CompanyID = Util.GetCompanyIDByUser(cd.Users); protected override void OnLoad(EventArgs e) { //snip } protected void MyEventHandler(object sender, EventArgs e) { //snip } } } ``` Currently, each of my methods needs to use cd, so instead of creating a variable inside each method, I was looking for a way to declare it in the class and have it available to all methods. When I try to set cd inside of the methods, it works fine. I've googled around, and it seems that I would have to have an instance of Page in order to use there, but that doesn't work. So I'm really misunderstanding how this works. Can anyone point me in the right direction? Edit: I added static keyword to cd, in order to resolve the 'cd denotes field where class was expected' error. Is this good implementation? Edit: I'm going to just mark the correct answer below and ask a new question, as I think it's deserving.
Try using `System.Web.HttpContext.Current`.
Use HttpContext.Current as already suggested. For the rest of your question: Try if you can create the cd field in OnInit, and use it afterwards in your OnLoad and other methods. Your problem is propably that the HttpContext is not yet available when the Page object is being constructed. (See [the ASP .NET Page Life Cycle](http://msdn.microsoft.com/en-us/library/ms178472.aspx))
How do I create instance of HttpContext?
[ "", "c#", "asp.net", "" ]
I wanted to know, will I run into any concurrency problem with this? This is NOT in a transaction. This code is for `Sqlite(prototype)`, but I plan to use it with either MySql or a SQL from MS ``` command.CommandText = "UPDATE tag_name SET count = count+1 "+ "WHERE tagid=@tagid"; command.Parameters.Add("@tagid", DbType.Int64).Value = tagId; command.ExecuteNonQuery(); ```
No this shouldn't be a problem. By default the locking mechanism should take care of any concurrency issues in single statements.
I may be wrong, but I don't think you would have a problem; the tag\_name table I would think would be locked while the UPDATE occurs, so that any other updates waiting to be executed would essentially be queued up rather than occurring concurrently.
Is there a concurrency with UPDATE count=count+1?
[ "", "sql", "database", "concurrency", "" ]
I have some services that an application needs running in order for some of the app's features to work. I would like to enable the option to only start the external Windows services to initialize after the application is launched. (as opposed to having them start automatically with the machine and take up memory when the application is not needed) I do not have access to the exe's code to implement this, so ideally I would like to write a C# .Net Windows service that would monitor when an exe is launched. What I've found so far is the System.IO.FileSystemEventHandler. This component only handles changed, created, deleted, and renamed event types. I don't expect that a file system component would be the ideal place to find what I'm looking for, but don't know where else to go. Maybe I'm not searching with the right keywords, but I have not yet found anything extremely helpful on Google or here on stackoverflow.com. The solution would be required to run on XP, Vista, and Win 7 when it comes... Thanks in advance for any pointers.
From [this article](http://social.msdn.microsoft.com/Forums/en-US/netfxbcl/thread/46f52ad5-2f97-4ad8-b95c-9e06705428bd?wa=wsignin1.0), you can use WMI (the `System.Management` namespace) in your service to watch for process start events. ``` void WaitForProcess() { ManagementEventWatcher startWatch = new ManagementEventWatcher( new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace")); startWatch.EventArrived += new EventArrivedEventHandler(startWatch_EventArrived); startWatch.Start(); ManagementEventWatcher stopWatch = new ManagementEventWatcher( new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace")); stopWatch.EventArrived += new EventArrivedEventHandler(stopWatch_EventArrived); stopWatch.Start(); } static void stopWatch_EventArrived(object sender, EventArrivedEventArgs e) { stopWatch.Stop(); Console.WriteLine("Process stopped: {0}" , e.NewEvent.Properties["ProcessName"].Value); } static void startWatch_EventArrived(object sender, EventArrivedEventArgs e) { startWatch.Stop(); Console.WriteLine("Process started: {0}" , e.NewEvent.Properties["ProcessName"].Value); } } ``` WMI allows for fairly sophisticated queries; you can modify the queries here to trigger your event handler only when your watched app launches, or on other criteria. [Here's a quick introduction](http://www.dreamincode.net/forums/showtopic42934.htm), from a C# perspective.
you have 3 options here: The reliable/intrusive one, set up a hook in unmanaged code that communicates back to your C# app whenever an app is launched. This is hard to get right and involves loading an extra DLL with each process. (Alternatively you could set up a driver, which is even harder to write) The less reliable way, list all the processes (using the [System.Diagnostics.Process](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.aspx) class) on a regular basis (say every 10-30 secs) to see if the app is launched. It also may be possible to watch the Win32\_Process, InstanceCreationEvent WMI event from managed code. Not sure how reliable this is, but I suspect it would be better than polling processes.
Monitor when an exe is launched
[ "", "c#", ".net", "windows-services", "monitoring", "" ]
In my C# application I want to display a context menu, but I want to add special options to the menu if the SHIFT key is being held down when the context menu is opened. I'm currently using the `GetKeyState` API to check for the SHIFT key. It works fine on my computer but users with non-English Windows say it doesn't work at all for them. I also read that in the Win32 API when a context menu is opened there's a flag that indicates in the menu should show `EXTENDEDVERBS`. In C# the `EventArgs` for the `Opening` event doesn't contain (from what I can tell) a property indicating `EXTENDEDVERBS` or if any modifier keys are pressed. Here's the code I'm using now inside the "`Opening`" event: ``` // SHIFT KEY is being held down if (Convert.ToBoolean(GetKeyState(0x10) & 0x1000)) { _menuStrip.Items.Add(new ToolStripSeparator()); ToolStripMenuItem log = new ToolStripMenuItem("Enable Debug Logging"); log.Click += new EventHandler(log_Click); log.Checked = Settings.Setting.EnableDebugLogging; _menuStrip.Items.Add(log); } ``` If GetKeyState is the right way of doing it, is my code properly detecting the SHIFT key being pressed?
You can use the [ModifierKeys static property](https://msdn.microsoft.com/en-us/library/9byw5s2d(v=vs.110).aspx) on control to determine if the shift key is being held. ``` if (Control.ModifierKeys == Keys.Shift ) { ... } ``` This is a flag style enum though so depending on your situation you may want to do more rigorous testing. Also note that this will check to see if the Shift key is held at the moment you check the value. Not the moment when the menu open was initiated. That may not be a significant difference for your application but it's worth noting.
Use this to detect if the shift key is pressed: ``` if ((Control.ModifierKeys & Keys.Shift) == Keys.Shift) ```
C# - Detecting if the SHIFT key is held when opening a context menu
[ "", "c#", "keyboard", "contextmenu", "" ]
I just wonder how to do it. I write : ``` CEdit m_wndEdit; ``` and in the button event handler (dialog app), I write : ``` m_wndEdit.Create(//with params); ``` but I still don't see the control appear in the UI. I actually wrote this in the button handler : ``` CWnd* pWnd = GetDlgItem(IDC_LIST1); CRect rect; pWnd->GetClientRect(&rect); //pWnd->CalcWindowRect(rect,CWnd::adjustBorder); wnd_Edit.Create(ES_MULTILINE | ES_NOHIDESEL | ES_READONLY,rect,this,105); wnd_Edit.ShowWindow(SW_SHOW); this->Invalidate(); ``` `id 105` doesn't exist. (I used it in the `Create` member function of `CEdit`). I just put it in there. isn't it supposed to be the id you want to give to the new control ? Should it already exist ?
Check with the following set of flags as the example mentioned in [MSDN](http://msdn.microsoft.com/en-us/library/ywby5fkc(VS.80).aspx): ``` pEdit->Create(ES_MULTILINE | WS_CHILD | WS_VISIBLE | WS_TABSTOP | WS_BORDER | ES_NOHIDESEL | ES_READONLY, rect, this, 105); ```
* The Invalidate() is not necessary * Add the WS\_VISIBLE flag to your create flags, you don't need the ShowWindow * You are creating the button on the location where IDC\_LIST1 is - you probably want to do pWdn->Destroy() after the GetClientRect() * The id you pass to Create() can be anything, of course if you want to handle messages from this button later you'll need to use the correct id. In that case it's easiest to manually add an entry to resource.h. * What do you mean with 'I put this code in the button event handler' - which button? A different one from the one you're trying to create, I may hope? Does your code get called at all, does it stop when you put a breakpoint in? What's the value of wnd\_Edit->m\_hWnd after the call to Create()? * wnd\_Edit is a member of your dialog, right, and not a a function local variable?
create a control programmatically using MFC
[ "", "c++", "mfc", "" ]
How can I make the code below to read correct text. In my text file has Hello welcome to C++, however at the end of the text, it has a new line. With the code below, my readBuffer always contains extra characters. ``` DWORD byteWritten; int fileSize = 0; //Use CreateFile to check if the file exists or not. HANDLE hFile = CreateFile(myFile, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if(hFile != INVALID_HANDLE_VALUE) { BOOL readSuccess; DWORD byteReading; char readBuffer[256]; readSuccess = ReadFile(hFile, readBuffer, byteReading, &byteReading, NULL); if(readSuccess == TRUE) { TCHAR myBuffer[256]; mbstowcs(myBuffer, readBuffer, 256); if(_tcscmp(myBuffer, TEXT("Hello welcome to C++")) == 0) { FindClose(hFile); CloseHandle(hFile); WriteResultFile(TRUE, TEXT("success!")); } } } ``` Thanks,
Either remove the new line character from the file or use \_tcsstr for checking the existence of the string "Hello Welcome to C++".
There are a few problems: * You're passing uninitialized data (byteReading) as the "# of bytes to read" parameter to ReadFile(). * Depending on how you created the file, the file's contents may not have a terminating 0 byte. The code assumes that the terminator is present. * FindClose(hFile) doesn't make sense. CloseHandle(hFile) is all you need. * You need to call CloseHandle if CreateFile() succeeds. Currently, you call it only if you find the string you're looking for. This isn't a bug, but it's helpful to zero-initialize your buffers. That makes it easier to see in the debugger exactly how much data is being read.
Trouble using ReadFile() to read a string from a text file
[ "", "c++", "winapi", "file-io", "windows-ce", "" ]
I was reading over [Injection by Hand](https://github.com/ninject/ninject/wiki/Dependency-Injection-By-Hand) and [Ninjection](https://github.com/ninject/ninject/wiki/Dependency-Injection-With-Ninject) (as well as [Why use Ninject](https://github.com/ninject/ninject/wiki/Why-Use-Ninject%3F) ). I encountered two pieces of confusion: 1. The inject by hand technique I am already familiar with, but I am not familiar with Ninjection, and thus am not sure how the complete program would work. Perhaps it would help to provide a complete program rather than, as is done on that page, showing a program broken up into pieces 2. I still don't really get how this makes things easier. I think I'm missing something important. I can kind of see how an injection framework would be helpful if you were creating a group of injections and then switching between two large groups all at once (this is useful for mocking, among other things), but I think there is more to it than that. But I'm not sure what. Or maybe I just need more examples of why this is exciting to drive home the point.
When injecting your dependencies without a DI framework you end up with arrow code all over your application telling classes how to build their dependencies. ``` public Contact() : this(new DataGateWay()) { } ``` But if you use something like Ninject, all the arrow code is in one spot making it easier to change a dependency for all the classes using it. ``` internal class ProductionModule : StandardModule { public override void Load() { Bind<IDataGateway>().To<DataGateWay>(); } } ```
> > I still don't really get how this makes things easier. I think I'm missing something important. Wouldn't it would be great if we only had to develop discrete components where each provided distinct functionality we could easily understand, re-use and maintain. Where we *only* worked on components. What prevents us from doing so, is we need some infrastructure that can somehow combine and manage these components into a working application *automatically*. Infrastructure that does this is available to us - an IOC framework. So an IOC framework isn't *about* managing dependencies or testing or configuration. Instead it is *about* managing complexity, by enabling you to only work and think about components.
Dependency Injection Frameworks: Why do I care?
[ "", "dependency-injection", "ninject", "c#", "" ]
We have a web service coded in C# that makes many calls to MS SQL Server 2005 database. The code uses Using blocks combined with C#'s connection pooling. During a SQL trace, we saw many, many calls to "sp\_resetconnection". Most of these are short < 0.5 sec, however sometimes we get calls lasting as much as 9 seconds. From what I've read sp\_resetconnection is related to connection pooling and basically resets the state of an open connection. My questions: * Why does an open connection need its state reset? * Why so many of these calls! * What could cause a call to sp\_reset connection to take a non-trivial amount of time. This is quite the mystery to me, and I appreciate any and all help!
The reset simply resets things so that you don't have to *reconnect* to reset them. It wipes the connection clean of things like SET or USE operations so each query has a clean slate. The connection is still being reused. Here's an [extensive list](http://www.sqlnotes.info/2012/02/01/few-things-about-pooled-connections/): **sp\_reset\_connection resets the following aspects of a connection:** * It resets all error states and numbers (like @@error) * It stops all EC's (execution contexts) that are child threads of a parent EC executing a parallel query * It will wait for any outstanding I/O operations that is outstanding * It will free any held buffers on the server by the connection * It will unlock any buffer resources that are used by the connection * It will release all memory allocated owned by the connection * It will clear any work or temporary tables that are created by the connection * It will kill all global cursors owned by the connection * It will close any open SQL-XML handles that are open * It will delete any open SQL-XML related work tables * It will close all system tables * It will close all user tables * It will drop all temporary objects * It will abort open transactions * It will defect from a distributed transaction when enlisted * It will decrement the reference count for users in current database; which release shared database lock * It will free acquired locks * It will releases any handles that may have been acquired * It will reset all SET options to the default values * It will reset the @@rowcount value * It will reset the @@identity value * It will reset any session level trace options using dbcc traceon() **sp\_reset\_connection will NOT reset:** * Security context, which is why connection pooling matches connections based on the exact connection string * If you entered an application role using sp\_setapprole, since application roles can not be reverted * The transaction isolation level(!)
Basically the calls are the clear out state information. If you have ANY open DataReaders it will take a LOT longer to occur. This is because your DataReaders are only holding a single row, but could pull more rows. They each have to be cleared as well before the reset can proceed. So make sure you have everything in using() statements and are not leaving things open in some of your statements. How many total connections do you have running when this happens? If you have a max of 5 and you hit all 5 then calling a reset will block - and it will appear to take a long time. It really is not, it is just blocked waiting on a pooled connection to become available. Also if you are running on SQL Express you can get blocked due to threading requirements very easily (could also happen in full SQL Server, but much less likely). What happens if you turn off connection pooling?
Why so many sp_resetconnections for C# connection pooling?
[ "", "c#", "sql-server-2005", "connection-pooling", "sp-reset-connection", "" ]
This may sound like a bit of a dumb question but how do I make a `Func<>` variable that doesn't return anything?
You can use `Action<T>` for a delegate that takes a variable and returns `void`. But note that you can also just declare your own delegate types if you want to. `Action<T>`, for example, is just ``` public delegate void Action<T>(T obj) ```
Will the Action<T> delegate work for you? [Action<T>](http://msdn.microsoft.com/en-us/library/018hxwa8.aspx)
Func not returning anything?
[ "", "c#", "lambda", "" ]
I currently have the regex: ``` (?:(?:CD)|(?:DISC)|(?:DISK)|(?:PART))([0-9]+) ``` currently this will match CD1, DISK2 etc I need it too be able to pick up CD02 (with two digits) as well as CD2 but I only seem to be able to do one or the other, and my regex skills are pretty useless. I'm using this code in C# thanks for your help Russell
Could it be that you're looking for the entire string "CD2" or "CD02" in a capture group? As in: ``` string input = "CD02"; var labelMatch = Regex.Match(input, "(?:(?:CD|... // edit for brevity if(labelMatch.Success) { string labelText = mediaLabel.Groups[1].Value; } ``` You may have made a mistake by using the `?:` expression because this tells the regex engine to match the group and then discard it from the capture groups. Some other expressions you might want to consider: ``` (?:CD|DISC|DISK|PART)(\d\d?) // throws away the label, captures 1 or 2 digits (?:CD|DISC|DISK|PART)(\d{1,2}) // ~same thing, matches exactly 1 or 2 digits ((CD|DISC|DISK|PART)\d\d?) // captures the whole thing in group 1 ```
It works here. Can you post your code that is failing? Note that your Regex can be simplified: ``` bool isMatch = Regex.IsMatch("CD02", "(?:(?:CD)|(?:DISC)|(?:DISK)|(?:PART))([0-9]+)"); bool isSimplifiedMatch = Regex.IsMatch("CD02", "(?:(CD|DIS[CK]|PART))([0-9]+)"); ```
Double digits and single digits using Regex
[ "", "c#", "regex", "" ]
Is there a way to get the entire URL used to request the current page, including the anchor (the text after the `#` - I may be using the wrong word), in included pages? i.e. page foo.php is included in bar.php. If I use your solution in foo.php, I need it to say `bar.php?blarg=a#example`.
No, I am afraid not, since the hash (the string *including* the #) never gets passed to the server, it is solely a behavioural property of the browser. The `$_SERVER['REQUEST_URI']` variable will contain the rest however. If you really need to know what the hash is, you will have to use the `document.location.hash` JavaScript property, which contains the contents of the hash (you could then insert it in a form, or send it to the server with an ajax request).
``` // find out the domain: $domain = $_SERVER['HTTP_HOST']; // find out the path to the current file: $path = $_SERVER['SCRIPT_NAME']; // find out the QueryString: $queryString = $_SERVER['QUERY_STRING']; // put it all together: $url = "http://" . $domain . $path . "?" . $queryString; echo $url; // An alternative way is to use REQUEST_URI instead of both // SCRIPT_NAME and QUERY_STRING, if you don't need them seperate: $url = "http://" . $domain . $_SERVER['REQUEST_URI']; echo $url; ```
Get entire URL, including query string and anchor
[ "", "php", "" ]