Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I have a multithreaded application that runs using a custom thread pool class. The threads all execute the same function, with different parameters. These parameters are given to the threadpool class the following way: ``` // jobParams is a struct of int, double, etc... jobParams* params = new jobParams; params.value1 = 2; params.value2 = 3; int jobId = 0; threadPool.addJob(jobId, params); ``` As soon as a thread has nothing to do, it gets the next parameters and runs the job function. I decided to take care of the deletion of the parameters in the threadpool class: ``` ThreadPool::~ThreadPool() { for (int i = 0; i < this->jobs.size(); ++i) { delete this->jobs[i].params; } } ``` However, when doing so, I sometimes get a heap corruption error: > Invalid Address specified to RtlFreeHeap The strange thing is that in one case it works perfectly, but in another program it crashes with this error. I tried deleting the pointer at other places: in the thread after the execution of the job function (I get the same heap corruption error) or at the end of the job function itself (no error in this case). I don't understand how deleting the same pointers (I checked, the addresses are the same) from different places changes anything. Does this have anything to do with the fact that it's multithreaded? I do have a critical section that handles the access to the parameters. I don't think the problem is about synchronized access. Anyway, the destructor is called only once all threads are done, and I don't delete any pointer anywhere else. Can pointer be deleted automatically? As for my code. The list of jobs is a queue of a structure, composed of the id of a job (used to be able to get the output of a specific job later) and the parameters. `getNextJob()` is called by the threads (they have a pointer to the ThreadPool) each time they finished to execute their last job. ``` void ThreadPool::addJob(int jobId, void* params) { jobData job; // jobData is a simple struct { int, void* } job.ID = jobId; job.params = params; // insert parameters in the list this->jobs.push(job); } jobData* ThreadPool::getNextJob() { // get the data of the next job jobData* job = NULL; // we don't want to start a same job twice, // so we make sure that we are only one at a time in this part WaitForSingleObject(this->mutex, INFINITE); if (!this->jobs.empty()) { job = &(this->jobs.front()); this->jobs.pop(); } // we're done with the exclusive part ! ReleaseMutex(this->mutex); return job; } ```
Let's turn this on its head: *Why are you using pointers at all?* ``` class Params { int value1, value2; // etc... } class ThreadJob { int jobID; // or whatever... Params params; } class ThreadPool { std::list<ThreadJob> jobs; void addJob(int job, const Params & p) { ThreadJob j(job, p); jobs.push_back(j); } } ``` No new, delete or pointers... Obviously some of the implementation details may be cocked, but you get the overall picture.
Thanks for extra code. Now we can see a problem - in getNextJob ``` if (!this->jobs.empty()) { job = &(this->jobs.front()); this->jobs.pop(); ``` After the "pop", the memory pointed to by 'job' is **undefined**. Don't use a reference, copy the actual data! Try something like this (it's still generic, because JobData is generic): ``` jobData ThreadPool::getNextJob() // get the data of the next job { jobData job; WaitForSingleObject(this->mutex, INFINITE); if (!this->jobs.empty()) { job = (this->jobs.front()); this->jobs.pop(); } // we're done with the exclusive part ! ReleaseMutex(this->mutex); return job; ``` } Also, while you're adding jobs to the queue you must ALSO lock the mutex, to prevent list corruption. AFAIK std::lists are NOT inherently thread-safe...?
Deleting pointer sometimes results in heap corruption
[ "", "c++", "multithreading", "pointers", "memory-management", "heap-corruption", "" ]
I need to update this table in **SQL Server** with data from its 'parent' table, see below: **Table: sale** ``` id (int) udid (int) assid (int) ``` **Table: ud** ``` id (int) assid (int) ``` `sale.assid` contains the correct value to update `ud.assid`. What query will do this? I'm thinking of a `join` but I'm not sure if it's possible.
Syntax strictly depends on which SQL DBMS you're using. Here are some ways to do it in ANSI/ISO (aka should work on any SQL DBMS), MySQL, SQL Server, and Oracle. Be advised that my suggested ANSI/ISO method will typically be much slower than the other two methods, but if you're using a SQL DBMS other than MySQL, SQL Server, or Oracle, then it may be the only way to go (e.g. if your SQL DBMS doesn't support `MERGE`): ANSI/ISO: ``` update ud set assid = ( select sale.assid from sale where sale.udid = ud.id ) where exists ( select * from sale where sale.udid = ud.id ); ``` MySQL: ``` update ud u inner join sale s on u.id = s.udid set u.assid = s.assid ``` SQL Server: ``` update u set u.assid = s.assid from ud u inner join sale s on u.id = s.udid ``` PostgreSQL: ``` update ud set assid = s.assid from sale s where ud.id = s.udid; ``` Note that the target table must not be repeated in the `FROM` clause for Postgres. Main question: [How to do an update + join in PostgreSQL?](https://stackoverflow.com/questions/7869592/how-to-do-an-update-join-in-postgresql) Oracle: ``` update (select u.assid as new_assid, s.assid as old_assid from ud u inner join sale s on u.id = s.udid) up set up.new_assid = up.old_assid ``` SQLite: ``` update ud set assid = ( select sale.assid from sale where sale.udid = ud.id ) where RowID in ( select RowID from ud where sale.udid = ud.id ); ``` SQLite 3.33 added support for an `UPDATE` + `FROM` syntax analogous to the PostgreSQL one: ``` update ud set assid = s.assid from sale s where ud.id = s.udid; ``` Main question: [Update with Join in SQLite](https://stackoverflow.com/questions/19270259/update-with-join-in-sqlite)
This should work in SQL Server: ``` update ud set assid = sale.assid from sale where sale.udid = id ```
How can I do an UPDATE statement with JOIN in SQL Server?
[ "", "sql", "sql-server", "t-sql", "sql-server-2005", "sql-update", "" ]
I Have an edit control (a text field) which I want to animate. The animation I want is that it slides out, creating an extra line for this text field. I am able to animate my text field and able to make it larger, however to show the sliding animation I first have to hide it. This means the entire text fields slides out as if being created for the first time from nothing, instead of just adding a new line. This is the code I have now: ``` SetWindowPos(hwnd, HWND_TOP, x, y, newWidth, newHeight, SWP_DRAWFRAME); ShowWindow(hwnd, SW_HIDE); AnimateWindow(hwnd, 300, AW_SLIDE | AW_VER_NEGATIVE); ``` Is it possible to show this animation without hiding it?
To expand on Nick D's answer, here's the code to achieve what you're looking for... .h ``` #define ANIMATION_TIMER 1234 #define ANIMATION_LIMIT 8 #define ANIMATION_OFFSET 4 int m_nAnimationCount; ``` --- .cpp ``` void CExampleDlg::OnTimer(UINT_PTR nIDEvent) { if (nIDEvent == ANIMATION_TIMER) { if (++m_nAnimationCount > ANIMATION_LIMIT) KillTimer(EXPAND_TIMER); else { CRect rcExpand; m_edtExpand.GetWindowRect(rcExpand); ScreenToClient(rcExpand); rcExpand.bottom += ANIMATION_OFFSET; m_edtExpand.MoveWindow(rcExpand); } } CDialog::OnTimer(nIDEvent); } void CExampleDlg::OnStartAnimation() { m_nAnimationCount = 0; SetTimer(ANIMATION_TIMER, 20, NULL); } ``` Don't forget to set the *Multiline* property on the edit control (m\_edtExpand)
An alternative way is to simulate animation with [SetTimer function](http://msdn.microsoft.com/en-us/library/ms644906(VS.85).aspx) which will call a routine to resize the window, incrementally.
WIN32, C++: Is it possible to animate a window without hiding it?
[ "", "c++", "winapi", "animation", "" ]
I serve a web page which makes the client do quite a lot of Javascript work as soon as it hits. The amount of work is proportional to the amount of content, which varies a lot. In cases where there is a huge amount of content, the work can take so long that clients will issue their users with one of those "unresponsive script - do you want to cancel it?" messages. In cases with hardly any content, the work is over in the blink of an eye. I have included a feature where, in cases where the content is larger than some value X, I include a "this may take a while" message to the user which is displayed before the hard work starts. The trouble is choosing a good value for X since, for this particular page, Chrome is so very much faster than Firefox which is faster than IE. I'd like to warn all users when appropriate, but avoid putting the message up when it's only going to be there for 100ms since this is distracting. In other words, I'd like the value for X to also depend on the browser's Javascript capabilities. So does anyone have a good way of figuring out a browser's capabilities? I'm currently considering just explicitly going off what the browser is, but that seems hacky, and there are other factors involved I guess.
If the data is relatively homogeneous, one method might be to have a helper function that checks how long a particular subset of the data has taken to go through, and make a conservative estimate of how long the entire set will take. From there, decide whether to display the message or not.
This may not be where you want to go, but do you have a good idea *why* the javascript can take so long? Is it downloading a bunch of content over the wire or is the actual formatting/churning on the browser the slow part? You might even be able to do something incrementally so that while the whole shebang takes a long time but users see content 'build' and thus don't have to be warned.
How can I estimate browser's Javascript capabilities?
[ "", "javascript", "browser", "" ]
How can i do this? (c#) Basically, i want to be able to sort of, comment out a bracket. but not really. I guess I want to close brackets out of order. That's probably not possible. I can obviously implement this in full separate if clauses, but this would considerably lighten my code. **P.S.:** I am trying to place the "//do something" code, either in a foreach loop, or for a single instance with an unrelated (to that of the foreach loop) argument, depending on a condition. I hope this helps clear it up. **pseudocode** (*what i'm trying to do, if you could close brackets out of order*): **im aware this is no where near valid code, it is pseudocode as i stated.** i havent looked at the second post yet, but the first post (Sean Bright), thank you, but the condition is unrelated to the number of entries (there will always be files in the directory, regardless of if i want the loop to execute) **extracting the //dosomething code into a function will work. I'm not sure how i overlooked that. I suppose I was wondering if there was a simpler way, but you are correct. thank you.** ``` if (isTrue) { //START LOOP string [] fileEntries = Directory.GetFiles(LogsDirectory, SystemLogFormat); foreach(string fileName in fileEntries) { using (StreamReader r = new StreamReader(fileName)) { /* The previous two blocks are not closed */ } else { using (StreamReader r = new StreamReader(SingleFileName)) { /* The previous block is not closed */ } // do all sorts of things if (isTrue) { /* Close the two unclosed blocks above */ } } } else { /* Close the unclosed block above */ } } ``` *thanks!* (indents are weird, sorry, its the forums doing)
Refactor the file processing part into a separate function: ``` public void OriginalFunction() { if ( isTrue ) { string [] fileEntries = Directory.GetFiles(LogsDirectory, SystemLogFormat); foreach(string fileName in fileEntries) { ProcessFile(fileName); } } else { ProcessFile(SingleFileName); } } public void ProcessFile( string name ) { using (StreamReader r = new StreamReader(name)) { // Do a bunch of stuff } } ```
Why not just do this: ``` string [] fileEntries = null; if (isTrue) { fileEntries = Directory.GetFiles(LogsDirectory, SystemLogFormat); } else { fileEntries = new string [] { SingleFileName }; } foreach(string fileName in fileEntries) { using (StreamReader r = new StreamReader(fileName)) { /* Do whatever */ } } ```
conditional foreach loop c#
[ "", "c#", "loops", "conditional-statements", "" ]
I'm relatively new to Web development and wouldn't even know where to start in coding a JavaScript that fades a grayscale thumbnail image into a `color` thumbnail image on `mouseover`, and vice versa on `mouseoff` (<--or whatever this is called). I've looked all over and can't find a script that does this. Is this possible? Could I use jQuery to do this? Other thoughts?
I think all you could do is load two thumbnails into a container at once, with the black and white laying over top of the colour. Then, you could use jquery to fade the opacity of the to thumbnail to 0.0. Here is a working example (it just uses a click to change it once, but I'll leave the mouseover / mouseout to you - you may want to speed up the animation): some html: ``` <div class="container"> <img src="blackandwhite.jpg" class="bw" /> <img src="colour.jpg" class="colour" /> </div> ``` some css: ``` .container { position: relative; } .container img { position: absolute; } .bw { z-index: 101; } .colour { z-index: 100; } ``` some jquery: ``` $(function() { $(".bw").click(function() { $(this).animate({ opacity: 0.0 }, 800); }); }); ```
The best way to do this would be to actually have two versions of the image. One that's grayscale and one that's color. To keep it strictly within javascript and html, I don't believe there's any other way than with the two image method. Flash, Silverlight, and maybe even HTML 5, can do it easily.
Using JavaScript to fade a thumbnail image from grayscale to to color
[ "", "javascript", "jquery", "" ]
A site I built with Kohana was slammed with an enormous amount of traffic yesterday, causing me to take a step back and evaluate some of the design. I'm curious what are some standard techniques for optimizing Kohana-based applications? I'm interested in benchmarking as well. Do I need to setup `Benchmark::start()` and `Benchmark::stop()` for each controller-method in order to see execution times for all pages, or am I able to apply benchmarking globally and quickly? I will be using the Cache-library more in time to come, but I am open to more suggestions as I'm sure there's a lot I can do that I'm simply not aware of at the moment.
**What I will say in this answer is not specific to Kohana, and can probably apply to lots of PHP projects.** Here are some points that come to my mind when talking about performance, scalability, PHP, ... *I've used many of those ideas while working on several projects -- and they helped; so they could probably help here too.* First of all, when it comes to performances, there are **many aspects/questions that are to consider**: * configuration of the server *(both Apache, PHP, MySQL, other possible daemons, and system)*; you might get more help about that on **[ServerFault](https://serverfault.com/)**, I suppose, * PHP code, * Database queries, * Using or not your webserver? * Can you use any kind of caching mechanism? Or do you need always more that up to date data on the website? # Using a reverse proxy The first thing that could be really useful is using a **reverse proxy**, like **[varnish](http://varnish.projects.linpro.no/)**, in front of your webserver: let it **cache as many things as possible**, so only requests that really need PHP/MySQL calculations *(and, of course, some other requests, when they are not in the cache of the proxy)* make it to Apache/PHP/MySQL. * First of all, your CSS/Javascript/Images *-- well, everything that is static --* probably don't need to be always served by Apache + So, you can have the reverse proxy cache all those. + Serving those static files is no big deal for Apache, but the less it has to work for those, the more it will be able to do with PHP. + Remember: Apache can only server a finite, limited, number of requests at a time. * Then, have the reverse proxy serve as many PHP-pages as possible from cache: there are probably **some pages that don't change that often**, and could be served from cache. Instead of using some PHP-based cache, why not let another, lighter, server serve those *(and fetch them from the PHP server from time to time, so they are always almost up to date)*? + For instance, if you have some RSS feeds *(We generally tend to forget those, when trying to optimize for performances)* that are requested **very often**, having them in cache for a couple of minutes could save hundreds/thousands of request to Apache+PHP+MySQL! + Same for the most visited pages of your site, if they don't change for at least a couple of minutes *(example: homepage?)*, then, no need to waste CPU re-generating them each time a user requests them. * Maybe there is a difference between pages served for anonymous users *(the same page for all anonymous users)* and pages served for identified users *("Hello Mr X, you have new messages", for instance)*? + If so, you can probably configure the reverse proxy to cache the page that is served for anonymous users *(based on a cookie, like the session cookie, typically)* + It'll mean that Apache+PHP has less to deal with: only identified users -- which might be only a small part of your users. About **using a reverse-proxy as cache**, for a PHP application, you can, for instance, take a look at **[Benchmark Results Show 400%-700% Increase In Server Capabilities with APC and Squid Cache](http://www.ilovebonnie.net/2009/07/14/benchmark-results-show-400-to-700-percent-increase-in-server-capabilities-with-apc-and-squid-cache/)**. *(Yep, they are using Squid, and I was talking about varnish -- that's just another possibility ^^ Varnish being more recent, but more dedicated to caching)* If you do that well enough, and manage to stop re-generating too many pages again and again, maybe you won't even have to optimize any of your code ;-) At least, maybe not in any kind of rush... And it's always better to perform optimizations when you are not under too much presure... As a sidenote: you are saying in the OP: > A site I built with Kohana was slammed with > an enormous amount of traffic yesterday, This is the kind of **sudden situation where a reverse-proxy can literally save the day**, if your website can deal with not being up to date by the second: * install it, configure it, let it always *-- every normal day --* run: + Configure it to not keep PHP pages in cache; or only for a short duration; this way, you always have up to date data displayed * And, the day you take a slashdot or digg effect: + Configure the reverse proxy to keep PHP pages in cache; or for a longer period of time; maybe your pages will not be up to date by the second, but it will allow your website to survive the digg-effect! About that, **[How can I detect and survive being “Slashdotted”?](https://stackoverflow.com/questions/218264/how-can-i-detect-and-survive-being-slashdotted)** might be an interesting read. # On the PHP side of things: First of all: are you using a **recent version of PHP**? There are regularly improvements in speed, with new versions ;-) For instance, take a look at **[Benchmark of PHP Branches 3.0 through 5.3-CVS](http://sebastian-bergmann.de/archives/745-Benchmark-of-PHP-Branches-3.0-through-5.3-CVS.html)**. Note that performances is quite a good reason to use PHP 5.3 *([I've made some benchmarks (in French)](https://blog.pascal-martin.fr/post/bench-php-5.2-vs-php-5.3-cpu/), and results are great)*... *Another pretty good reason being, of course, that PHP 5.2 has reached its end of life, and is not maintained anymore!* ## Are you using any opcode cache? * I'm thinking about **APC - Alternative PHP Cache**, for instance *([pecl](https://pecl.php.net/package/APC), [manual](https://www.php.net/apc))*, which is the solution I've seen used the most -- and that is used on all servers on which I've worked. + See also: **[Slides APC Facebook](https://www.scribd.com/document/88689/Apc-Facebook)**, + Or **[Benchmark Results Show 400%-700% Increase In Server Capabilities with APC and Squid Cache](http://www.ilovebonnie.net/2009/07/14/benchmark-results-show-400-to-700-percent-increase-in-server-capabilities-with-apc-and-squid-cache/)**. * It can really lower the CPU-load of a server a lot, in some cases *(I've seen CPU-load on some servers go from 80% to 40%, just by installing APC and activating it's opcode-cache functionality!)* * Basically, execution of a PHP script goes in two steps: + Compilation of the PHP source-code to opcodes *(kind of an equivalent of JAVA's bytecode)* + Execution of those opcodes + APC keeps those in memory, so there is less work to be done each time a PHP script/file is executed: only fetch the opcodes from RAM, and execute them. * You might need to take a look at **APC's [configuration options](https://php.net/manual/en/apc.configuration.php)**, by the way + there are quite a few of those, and some can have a great impact on both speed / CPU-load / ease of use for you + For instance, disabling `[apc.stat](https://php.net/manual/en/apc.configuration.php#ini.apc.stat)` can be good for system-load; but it means modifications made to PHP files won't be take into account unless you flush the whole opcode-cache; about that, for more details, see for instance [To stat() Or Not To stat()?](https://www.brandonsavage.net/to-stat-or-not-to-stat/) ## Using cache for data As much as possible, it is better to **avoid doing the same thing over and over again**. The main thing I'm thinking about is, of course, SQL Queries: many of your pages probably do the same queries, and the results of some of those is probably almost always the same... Which means lots of *"useless"* queries made to the database, which has to spend time serving the same data over and over again. Of course, this is true for other stuff, like Web Services calls, fetching information from other websites, heavy calculations, ... It might be very interesting for you to identify: * Which queries are run lots of times, always returning the same data * Which other *(heavy)* calculations are done lots of time, always returning the same result And store these data/results in some kind of cache, so they are easier to get -- *faster* -- and you don't have to go to your SQL server for "nothing". Great caching mechanisms are, for instance: * **APC**: in addition to the opcode-cache I talked about earlier, it allows you to store data in memory, * And/or **[memcached](http://www.danga.com/memcached/)** *([see also](https://www.php.net/memcache))*, which is very useful if you literally have **lots** of data and/or are **using multiple servers**, as it is distributed. * of course, you can think about files; and probably many other ideas. I'm pretty sure your framework comes with some cache-related stuff; you probably already know that, as you said *"I will be using the Cache-library more in time to come"* in the OP ;-) ## Profiling Now, a nice thing to do would be to use the **[Xdebug](https://xdebug.org/)** extension to **profile your application**: it often allows to find a couple of weak-spots quite easily -- at least, if there is any function that takes lots of time. **[Configured properly](https://xdebug.org/docs/profiler)**, it will generate profiling files that can be analysed with some graphic tools, such as: * **[KCachegrind](http://kcachegrind.sourceforge.net/html/Home.html)**: my favorite, but works only on Linux/KDE * **[Wincachegrind](https://sourceforge.net/projects/wincachegrind/)** for windows; it does a bit less stuff than KCacheGrind, unfortunately -- it doesn't display callgraphs, typically. * **[Webgrind](https://github.com/jokkedk/webgrind)** which runs on a PHP webserver, so works anywhere -- but probably has less features. For instance, here are a couple screenshots of KCacheGrind: [![KCacheGrind : main screen](https://i.stack.imgur.com/PT9h7.png)](http://extern.pascal-martin.fr/so/kcachegrind/kcachegrind-1.png) (source: [pascal-martin.fr](http://extern.pascal-martin.fr/so/kcachegrind/kcachegrind-1-small.png)) [![KCacheGrind : Callgraph exported as an image](https://i.stack.imgur.com/JYf9U.png)](http://extern.pascal-martin.fr/so/kcachegrind/kcachegrind-2.png) (source: [pascal-martin.fr](http://extern.pascal-martin.fr/so/kcachegrind/kcachegrind-2-small.png)) *(BTW, the callgraph presented on the second screenshot is typically something neither WinCacheGrind nor Webgrind can do, if I remember correctly ^^ )* *(Thanks @Mikushi for the comment)* Another possibility that I haven't used much is the the **[xhprof](https://pecl.php.net/package/xhprof)** extension : it also helps with profiling, can generate callgraphs -- but is lighter than Xdebug, which mean you should be able to install it on a production server. You should be able to use it alonside **[XHGui](https://github.com/preinheimer/xhprof)**, which will help for the visualisation of data. # On the SQL side of things: Now that we've spoken a bit about PHP, note that it is **more than possible that your bottleneck isn't the PHP-side of things**, but the database one... At least two or three things, here: * You should determine: + What are the most frequent queries your application is doing + Whether those are optimized *(using the **right indexes**, mainly?)*, using the **[`EXPLAIN`](https://dev.mysql.com/doc/refman/8.0/en/explain.html)** instruction, if you are using MySQL - See also: **[Optimizing SELECT and Other Statements](https://dev.mysql.com/doc/refman/5.1/en/select-optimization.html)** - You can, for instance, activate [`log_slow_queries`](https://dev.mysql.com/doc/refman/5.1/en/server-options.html#option_mysqld_log-slow-queries) to get a list of the requests that take *"too much"* time, and start your optimization by those. + whether you could cache some of these queries *(see what I said earlier)* * Is your MySQL well configured? I don't know much about that, but there are some configuration options that might have some impact. + **[Optimizing the MySQL Server](https://dev.mysql.com/doc/refman/5.1/en/optimizing-the-server.html)** might give you some interesting informations about that. Still, the two most important things are: * Don't go to the DB if you don't need to: **cache as much as you can**! * When you have to go to the DB, use efficient queries: use indexes; and profile! # And what now? If you are still reading, what else could be optimized? Well, there is still room for improvements... A couple of architecture-oriented ideas might be: * Switch to an n-tier architecture: + Put MySQL on another server *(2-tier: one for PHP; the other for MySQL)* + Use several PHP servers *(and load-balance the users between those)* + Use another machines for static files, with a lighter webserver, like: - [lighttpd](https://www.lighttpd.net/) - or [nginx](https://nginx.org/) -- this one is becoming more and more popular, btw. + Use several servers for MySQL, several servers for PHP, and several reverse-proxies in front of those + Of course: install [memcached](https://memcached.org/) daemons on whatever server has any amount of free RAM, and use them to cache as much as you can / makes sense. * Use something "more efficient" that Apache? + I hear more and more often about **[nginx](https://nginx.org/)**, which is supposed to be great when it comes to PHP and high-volume websites; I've never used it myself, but you might find some interesting articles about it on the net; - for instance, **[PHP performance III -- Running nginx](http://till.klampaeckel.de/blog/archives/30-PHP-performance-III-Running-nginx.html)**. - See also: **[PHP-FPM - FastCGI Process Manager](https://php-fpm.org/)**, which is bundled with PHP >= 5.3.3, and does wonders with nginx. Well, maybe some of those ideas are a bit overkill in your situation ^^ But, still... Why not study them a bit, just in case ? ;-) # And what about Kohana? Your initial question was about optimizing an application that uses Kohana... Well, I've posted some **ideas that are true for any PHP application**... Which means they are true for Kohana too ;-) *(Even if not specific to it ^^)* I said: use cache; Kohana seems to support some [caching stuff](http://docs.kohanaphp.com/libraries/cache) *(You talked about it yourself, so nothing new here...)* If there is anything that can be done quickly, try it ;-) I also said you shouldn't do anything that's not necessary; is there anything enabled by default in Kohana that you don't need? Browsing the net, it seems there is at least something about XSS filtering; do you need that? Still, here's a couple of links that might be useful: * [Kohana General Discussion: Caching?](http://forum.kohanaphp.com/comments.php?DiscussionID=133) * [Community Support: Web Site Optimization: Maximum Website Performance using Kohana](http://forum.kohanaphp.com/comments.php?DiscussionID=1435) # Conclusion? And, to conclude, a simple thought: * How much will it cost your company to pay you 5 days? *-- considering it is a reasonable amount of time to do some great optimizations* * How much will it cost your company to buy *(pay for?)* a second server, and its maintenance? * What if you have to scale larger? + How much will it cost to spend 10 days? more? optimizing every possible bit of your application? + And how much for a couple more servers? I'm not saying you shouldn't optimize: you definitely should! But **go for "quick" optimizations that will get you big rewards** first: using some opcode cache might help you get between 10 and 50 percent off your server's CPU-load... And it takes only a couple of minutes to set up ;-) On the other side, spending 3 days for 2 percent... Oh, and, btw: before doing anything: **put some monitoring stuff in place**, so you know what improvements have been made, and how! Without monitoring, you will have no idea of the effect of what you did... Not even if it's a real optimization or not! For instance, you could use something like **[RRDtool](http://oss.oetiker.ch/rrdtool/)** + **[cacti](https://www.cacti.net/)**. And showing your boss some nice graphics with a 40% CPU-load drop is always great ;-) Anyway, and to really conclude: **have fun!** *(Yes, optimizing is fun!)* *(Ergh, I didn't think I would write that much... Hope at least some parts of this are useful... And I should remember this answer: might be useful some other times...)*
Use [XDebug](http://www.xdebug.org/) and [WinCacheGrind](http://sourceforge.net/projects/wincachegrind/) or [WebCacheGrind](http://code.google.com/p/webgrind/) to profile and analyze slow code execution. [![WebCacheGrind](https://i.stack.imgur.com/NKrGI.png)](https://i.stack.imgur.com/NKrGI.png) (source: [jokke.dk](http://jokke.dk/media/2008-webgrind/webgrind_small.png)) ![WinCacheGrind](https://sourceforge.net/dbimage.php?id=24706)
Optimizing Kohana-based Websites for Speed and Scalability
[ "", "php", "optimization", "performance", "scalability", "kohana", "" ]
I would like to POST multipart/form-data encoded data. I have found an external module that does it: <http://atlee.ca/software/poster/index.html> however I would rather avoid this dependency. Is there a way to do this using the standard libraries? thanks
The standard library [does not currently support that](http://bugs.python.org/issue3244). There is [cookbook recipe](https://github.com/ActiveState/code/tree/master/recipes/Python/146306_Http_client_POST_using/) that includes a fairly short piece of code that you just may want to copy, though, along with long discussions of alternatives.
It's an old thread but still a popular one, so here is my contribution using only standard modules. The idea is the same than [here](http://code.activestate.com/recipes/146306/) but support Python 2.x and Python 3.x. It also has a body generator to avoid unnecessarily memory usage. ``` import codecs import mimetypes import sys import uuid try: import io except ImportError: pass # io is requiered in python3 but not available in python2 class MultipartFormdataEncoder(object): def __init__(self): self.boundary = uuid.uuid4().hex self.content_type = 'multipart/form-data; boundary={}'.format(self.boundary) @classmethod def u(cls, s): if sys.hexversion < 0x03000000 and isinstance(s, str): s = s.decode('utf-8') if sys.hexversion >= 0x03000000 and isinstance(s, bytes): s = s.decode('utf-8') return s def iter(self, fields, files): """ fields is a sequence of (name, value) elements for regular form fields. files is a sequence of (name, filename, file-type) elements for data to be uploaded as files Yield body's chunk as bytes """ encoder = codecs.getencoder('utf-8') for (key, value) in fields: key = self.u(key) yield encoder('--{}\r\n'.format(self.boundary)) yield encoder(self.u('Content-Disposition: form-data; name="{}"\r\n').format(key)) yield encoder('\r\n') if isinstance(value, int) or isinstance(value, float): value = str(value) yield encoder(self.u(value)) yield encoder('\r\n') for (key, filename, fd) in files: key = self.u(key) filename = self.u(filename) yield encoder('--{}\r\n'.format(self.boundary)) yield encoder(self.u('Content-Disposition: form-data; name="{}"; filename="{}"\r\n').format(key, filename)) yield encoder('Content-Type: {}\r\n'.format(mimetypes.guess_type(filename)[0] or 'application/octet-stream')) yield encoder('\r\n') with fd: buff = fd.read() yield (buff, len(buff)) yield encoder('\r\n') yield encoder('--{}--\r\n'.format(self.boundary)) def encode(self, fields, files): body = io.BytesIO() for chunk, chunk_len in self.iter(fields, files): body.write(chunk) return self.content_type, body.getvalue() ``` **Demo** ``` # some utf8 key/value pairs fields = [('প্রায়', 42), ('bar', b'23'), ('foo', 'ން:')] files = [('myfile', 'image.jpg', open('image.jpg', 'rb'))] # iterate and write chunk in a socket content_type, body = MultipartFormdataEncoder().encode(fields, files) ```
Python standard library to POST multipart/form-data encoded data
[ "", "python", "encoding", "post", "urllib", "multipart", "" ]
I'm trying to implement unit testing for aproject, it uses a legacy "utility" project that is littered with static methods and many of the classes are final or their methods are final. I'm not able to update the legacy project at all. JMock and EasyMock both choke on final methods, and I don't see a nice way to test the static calls. What techniques are there to test these?
If you're able to refactor your code, you can wrap your calls to the final/static methods in simple instance methods, for example: ``` protected Foo doBar(String name) { return Utility.doBar(name); } ``` This allows you to override your wrapper method in the unit test to return a mock instance of Foo. Alternatively you can use [Powermock](http://code.google.com/p/powermock/), which extends Easymock (and Mockito) to allow mocking of final and static methods: > PowerMock is a framework that extend other mock libraries such as EasyMock with more powerful capabilities. PowerMock uses a custom classloader and bytecode manipulation to enable mocking of static methods, constructors, final classes and methods, private methods, removal of static initializers and more. Here's an [example](http://code.google.com/p/powermock/source/browse/trunk/modules/module-test/powermock/junit4-test/src/test/java/samples/junit4/singleton/MockStaticTest.java) test mocking a static final method, the example shows how to mock some other types too: ``` @Test public void testMockStaticFinal() throws Exception { mockStatic(StaticService.class); String expected = "Hello altered World"; expect(StaticService.sayFinal("hello")).andReturn("Hello altered World"); replay(StaticService.class); String actual = StaticService.sayFinal("hello"); verify(StaticService.class); assertEquals("Expected and actual did not match", expected, actual); // Singleton still be mocked by now. try { StaticService.sayFinal("world"); fail("Should throw AssertionError!"); } catch (AssertionError e) { assertEquals("\n Unexpected method call sayFinal(\"world\"):", e.getMessage()); } } ```
How about a level of indirection / Dependency Injection? Since the legacy utility project is your dependency, create an interface to separate it out from your code. Now your real/production implementation of this interface delegates to the legacy utility methods. ``` public LegacyActions : ILegacyActions { public void SomeMethod() { // delegates to final/static legacy utility method } } ``` For your tests, you can create a mock of this interface and avoid interacting with the legacy utility thingie.
How can I test final and static methods of a utility project?
[ "", "java", "junit", "" ]
Is there any study or set of benchmarks showing the performance degradation due to specifying -fno-strict-aliasing in GCC (or equivalent in other compilers)?
It will vary a lot from compiler to compiler, as different compilers implement it with different levels of aggression. GCC is fairly aggressive about it: enabling strict aliasing will cause it to think that pointers that are "obviously" equivalent to a human (as in, `foo *a; bar *b = (bar *) a;`) cannot alias, which allows for some very aggressive transformations, but can obviously break non-carefully written code. Apple's GCC disables strict aliasing by default for this reason. LLVM, by contrast, does not even *have* strict aliasing, and, while it is planned, the developers have said that they plan to implement it as a fall-back case when nothing else can judge equivalence. In the above example, it would still judge a and b equivalent. It would only use type-based aliasing if it could not determine their relationship in any other way. In my experience, the performance impact of strict aliasing mostly has to do with loop invariant code motion, where type information can be used to prove that in-loop loads can't alias the array being iterated over, allowing them to be pulled out of the loop. YMMV.
What I can tell you from experience (having tested this with a large project on PS3, PowerPC being an architecture that due to it's many registers can actually benefit from SA quite well) is that the optimizations you're going to see are generally going to be very local (scope wise) and small. On a 20MB executable it scraped off maybe 80kb of the .text section (= code) and this was all in small scopes & loops. This option can make your generated code a bit more lightweight and optimized than it is right now (think in the 1 to 5 percent range), but do not expect any big results. Hence, the effect of using -fno-strict-aliasing is probably not going to be a big influence on your performance, at all. That said, having code that requires -fno-strict-aliasing is a suboptimal situation at best.
Performance impact of -fno-strict-aliasing
[ "", "c++", "c", "performance", "compiler-construction", "" ]
I have set file permissions to 777 yet I cannot write to the file with PHP. I can clearly see in my FTP client that the file has 0777 permissions and when I do: ``` echo (true === is_writable('file.txt')) ? 'yes' : 'no'; ``` I get 'no'; I also tried: ``` echo (true === chmod('file.txt', 0777)) ? 'yes' : 'no'; ``` With the same result. The directory listing goes something like this: ``` public_html public 0777 css 0755 js 0755 file.txt 0777 ``` And I'm using .htaccess file to redirect all traffic to the public subfolder. Of course, I have excluded the file from rewriting (it is accessible from the browser I checked): ``` RewriteRule ^(file).* - [L] ``` Why is that?
I guess Apache runs as a different user/group than the user/group owning the file. In which case, the file itself needs to be `0777`. `public` only needs to be `0777` if you plan on adding files to the folder using PHP. Even if the folder itself is not `0777`, if the file is and the folder has at least `5` for the user (`read/execute`), you should be able to write to the file. In the end, your file tree should look like this: ``` public_html public file.txt 0777 ``` Naturally, you won't be able to change those permissions using PHP, but you can do so from your FTP client. If it still isn't working, PHP might be running in safe mode or you might be using an extension such as PHP Suhosin. You might get better result changing the owner of the file to the same user/group that is running the script. To get the user/group id of the executing user, you may use the following: ``` <?php echo getmyuid().':'.getmygid(); //ex:. 0:0 ?> ``` Then, you may use `chown` (in the terminal) to change the owner of the file: ``` > chown 0:0 file.txt ```
In opencart i faced this error after installing vqmod and giving all necessary permissions. after researching a bit, found it. "MODS CACHE PATH NOT WRITEABLE" is actually refering to vqmod folder itself and not the cache folder. ``` sudo chmod -R 777 vqmod ``` in your root directory.....
Permissions set to 777 and file still not writeable
[ "", "php", "apache", "mod-rewrite", "" ]
I have created a .NET C# component that I am going to sell as a developers tool. My question is, how do I add my own custom context help to the methods and properties. So, when I press F1 over a method I want it to go to a specific web page. Is this even possible?
**Use the Visual Studio SDK and the help integration kit** Part of the Visual Studio SDK is the Help Integration project type. Information about [integrating with help here](http://msdn.microsoft.com/en-us/library/bb165415.aspx) (MSDN). Same applies for VS 2005 and 2008. Here's a [link to the download](http://www.microsoft.com/downloads/details.aspx?familyid=3eaeb657-98dd-4959-b946-9719fec3a3ce&displaylang=en), for earlier versions of VS (before '05). There's an [entire development center](http://msdn.microsoft.com/en-us/vsx/default.aspx) about the Visual Studio SDK. The effort feels a lot higher than shipping a .Chm and/or IntelliSense files, but I understand you'd like to add examples, etc. **Consider if it's worth the effort** Are you providing enough information in the IntelliSense documentation files (.xml) for all of your component's assemblies? More often than not, that's sufficient to provide a lot of information, including additional remarks, notes, etc. I may just be biased to my development workflow and that of my co-workers, but I can't remember the last time that I saw anyone press "F1" in Visual Studio. Plus, if you really ever do want a full-blown .Chm help file, your XML documentation comments can be turned into that with little effort thanks to tools like [Sandcastle](http://www.codeplex.com/Sandcastle) and formerly NDoc.
Aside from the traditional F1 help, I find that Sandcastle created CHM files are extremely helpful when deploying any reusable libraries and frameworks. [GhostDoc](http://submain.com/products/ghostdoc.aspx) has proven quite useful for creating the in-code XML needed for Sandcastle CHM files. Sandcastle also has the option of creating MSDN-style HTML help files as well as the tried-and-true CHM.
How do I add context help to an assembly
[ "", "c#", ".net", "" ]
It is quite easy to load HTML content from your custom URLs/Web services using JQuery or any other similar framework. I've used this approach many times and till now and found the performance satisfactory. But all the books, all the experts are trying to get me to use JSON instead of generated HTML. How's it much more superior than HTML? **Is it very much faster? Does it have a very much lesser load on the server?** On the other side I have some reasons for using generated HTML. 1. It's simple markup, and often just as compact or actually more compact than JSON. 2. It's less error prone cause all you're getting is markup, and no code. 3. It will be faster to program in most cases cause you won't have to write code separately for the client end. Which side are you on and why?
I'm a bit on both sides, actually : * When what I need on the javascript side is **data**, I use JSON * When what I need on the javascript side is **presentation** on which I will not do any calculation, I generally use HTML The main advantage of using HTML is when you want to replace a full portion of your page with what comes back from the Ajax request : * Re-building a portion of page in JS is (quite) hard * You probably already have some templating engine on the server side, that was used to generate the page in the first place... Why not reuse it ? I generally don't really take into consideration the "performance" side of things, at least on the server : * On the server, generating a portion of HTML or some JSON won't probably make that much of a difference * About the size of the stuff that goes through the network : well, you probably don't use hundreds of KB of data/html... Using gzip on whatever you are transferring is what's going to make the biggest difference *(not choosing between HTML and JSON)* * One thing that could be taken into consideration, though, is what resources you'll need on the client to recreate the HTML *(or the DOM structure)* from the JSON data... compare that to pushing a portion of HTML into the page ;-) Finally, one thing that definitly matters : * How long will it take you to develop a new system that will send data as JSON + code the JS required to inject it as HTML into the page ? * How long will it take to just return HTML ? And how long if you can re-use some of your already existing server-side code ? And to answer another answer : if you need to update more than one portion of the page, there is still the solution/hack of sending all those parts inside one big string that groups several HTML portions, and extract the relevant parts in JS. For instance, you could return some string that looks like this : ``` <!-- MARKER_BEGIN_PART1 --> here goes the html code for part 1 <!-- MARKER_END_PART1 --> <!-- MARKER_BEGIN_PART2 --> here goes the html code for part 2 <!-- MARKER_END_PART2 --> <!-- MARKER_BEGIN_PART3 --> here goes the json data that will be used to build part 3 from the JS code <!-- MARKER_END_PART3 --> ``` That doesn't look really good, but it's definitly useful *(I've used it quite a couple of times, mostly when the HTML data were too big to be encapsulated into JSON)* : you are sending HTML for the portions of the page that need presentation, and you are sending JSON for the situation you need data... ... And to extract those, the JS substring method will do the trick, I suppose ;-)
I mainly agree with the opinions stated here. I just wanted to summarize them as: * It is bad practice to send HTML if you end up parsing it client-side to do some calculations over it. * It is bad practice to send JSON if all you'll end up doing is to incorporate it into the page's DOM tree.
Why is it a bad practice to return generated HTML instead of JSON? Or is it?
[ "", "javascript", "jquery", "html", "ajax", "json", "" ]
I'm debugging a multi-threaded Python program with Wing IDE. When I press the pause button, it pauses only one thread. I've tried it ten times and it always pauses the same thread, in my case called "ThreadTimer Thread", while the other threads keep on running. I want to pause these other threads so I could step with them. How do I do that?
I don't know if multi-thread debugging is possible with Wing IDE. However you maybe interested in [Winpdb](http://winpdb.org/about/) which has this capability
Per [the docs](http://www.wingware.com/doc/debug/threading), all threads that are running Python code are stopped (by default, i.e., unless you're going out of the way to achieve a different effect). Are the threads that you see as not getting stopped running non-Python code (I/O, say: that gives its own issues), or are you doing something else than running in a pristine install without the tweaks the docs describe to only pause some of the threads...?
Debugging multi-threaded Python with Wing IDE
[ "", "python", "multithreading", "debugging", "ide", "" ]
I am trying to get the top 2 results per day, where the "top" results are the rows with the highest "MPR". My table looks like this: ``` date symbol MPR 8/7/2008 AA 0.98 8/7/2008 AB 0.97 8/7/2008 AC 0.96 ... 8/7/2008 AZ 0.50 8/8/2008 AA 0.88 8/8/2008 AB 0.87 8/8/2008 AC 0.86 ... 8/8/2008 AZ 0.40 ... many other days ``` I would like the result set to be: ``` date symbol MPR 8/7/2008 AA 0.98 8/7/2008 AB 0.97 8/8/2008 AA 0.88 8/8/2008 AB 0.87 ``` I have tried using the TOP keyword, but this only gives me the top 2 rows, and I'm trying to do the top 2 rows *per date*. I am using Microsoft Access. I'd appreciate any help! :-)
<http://www.rogersaccesslibrary.com/forum/forum_posts.asp?TID=233> Check page 5 Here is the solution: ``` SELECT t1.date, t1.symbol, t1.MPR FROM table1 t1 WHERE t1.MPR IN ( SELECT TOP 2 t2.MPR FROM table1 t2 WHERE t2.date = t1.date ORDER BY t2.MPR DESC ) ```
Here you go: ``` SELECT YourTable.DateStamp, YourTable.Symbol, Max(YourTable.MPR) AS MaxOfMBR FROM YourTable GROUP BY YourTable.DateStamp, YourTable.Symbol, YourTable.MPR HAVING YourTable.MPR In (SELECT TOP 2 MPR FROM YourTable T2 WHERE YourTable.DateStamp = T2.DateStamp ORDER BY MPR DESC) ORDER BY YourTable.DateStamp, YourTable.MPR DESC; ``` The trick here is to use an aggregate query, and then in the HAVING statement (basically the "WHERE" of an aggregate query), you use a subquery to pull the top 2 values from the MPR column. I made a quick DB in Access 2007 and this worked fine. EDIT: Clarification on the usage of MAX here. You're returning the MAX of a group, not the MAX value of the column for a particular day. Therefore, you get the correct number of records (2) per date.
top X results per day with sql in access
[ "", "sql", "ms-access", "" ]
I have always thought of JavaScript as a client-side scripting tool for augmenting the functionality of HTML, which in turn is usually generated by some other server-side technology - Java, .NET, Rails, Django, PHP, etc. Recently though I have heard people talk about JavaScript as an "application language". I understand that applications like Gmail have taken JavaScript to the next stage of evolution and have made the browser much more like a full-featured application. But as far as I know, there are no server-side technologies like the ones I mentioned earlier that are JavaScript based. So even in the case of a Rich Internet Application, the "application language" is really the one on the backend that interacts with the database and performs URL routing, etc. Is my understanding outdated and is JavaScript now capable of performing backend processing or are we willing to call it an "application language" simply because its current sophistication in what it can perform on the front-end is such that the backend processing has become secondary?
[Serverside Javascript](http://en.wikipedia.org/wiki/Server-side_JavaScript) has been possible for a [long time now](http://aspjavascript.com). I maintain code with it every day. It's way better than classic ASP (at least I can have "real" objects, and try-catch, etc). Another great thing is that you can avoid recoding your form validation code in different languages. I just use a javascript file like this: ``` <!--//<% //code //%>--> ``` That allows you to both include code with `<!--#include file='name'-->` and with `<script src='name' />`. On the downside it could be lot easier to "break" your validation code by looking at it (if you weren't careful enough). **Never put sensitive information in there outside the validation code.** Also, you can choose the file extension that you want, but **never** save serverside javascript that does database access as `.js`. `.asp` files are by default executed and not sent as plain text. That is not true for `.js` files, which are only executed if they are included in an `.asp` file.
I disagree. With the advent of web services you can write your entire application client side if you want and simply interact with web services via AJAX. I wouldn't recommend this, but it could be done. Now you might consider the web service as part of the application, but I think the point could be argued that it's no more part of the application than your database technology.
Is JavaScript an application language?
[ "", "javascript", "web-applications", "language-features", "rich-internet-application", "" ]
I'm looking into how to implement logging in my C# app - its a DLL class library. What logging frameworks are most widely used - what would give users of my DLL the most flexibility and configurability? Is there a C# equivalent of log4j?
**2009 Answer:** Equivalent of log4j for .NET platform is [log4net](http://logging.apache.org/log4net/index.html) and I am guessing it's widely used. --- **2019 Answer:** Here are a variety of alternatives from <https://github.com/quozd/awesome-dotnet/blob/master/README.md#logging>: * [Essential Diagnostics](https://github.com/sgryphon/essential-diagnostics) - Extends the inbuilt features of System.Diagnostics namespace to provide flexible logging * [NLog](https://github.com/nlog/NLog/) - NLog - Advanced .NET and Silverlight logging * [Logazmic](https://github.com/ihtfw/Logazmic) - Open source NLog viewer for Windows * [ELMAH](https://elmah.github.io/) - Official ELMAH site * [Elmah MVC](https://github.com/alexbeletsky/elmah-mvc) - Elmah for MVC * [Logary](http://logary.github.io/) - Logary is a high performance, multi-target logging, metric, tracing and health-check library for Mono and .NET. .NET's answer to DropWizard. Supports many targets, built for micro-services. * [Log4Net](https://logging.apache.org/log4net/) - The Apache log4net library is a tool to help the programmer output log statements to a variety of output targets * [com.csutil.Log](https://github.com/cs-util-com/cscore#logging) - A lightweight zero config Log wrapper that can be combined with other logging libraries like Serilog for more complex usecases. * [Serilog](https://github.com/serilog/serilog) - A no-nonsense logging library for the NoSQL era. Combines the best of traditional and structured diagnostic logging in an easy-to-use package. * [StackExchange.Exceptional](https://github.com/NickCraver/StackExchange.Exceptional) - Error handler used for the Stack Exchange network * [Semantic Logging Application Block (SLAB)](https://github.com/MicrosoftArchive/semantic-logging) - Extends the inbuilt features of System.Diagnostics.Tracing namespace (EventSource class) to log to several sinks including Azure Tables, Databases, files (JSON, XML, text). Supports in-process and out-of-process logging through ETW, and Rx for real-time filtering/aggregating of events. * [Foundatio](https://github.com/FoundatioFx/Foundatio#logging) - A fluent logging API that can be used to log messages throughout your application. * [Exceptionless](https://github.com/exceptionless/Exceptionless.Net) - Exceptionless .NET Client * [Loupe](https://onloupe.com) - Centralized .NET logging and monitoring. **[Proprietary]** **[Free Tier]** * [elmah.io](https://elmah.io) - Cloud logging for .NET web applications using ELMAH. Find bugs before you go live. Powerful search, API, integration with Slack, GitHub, Visual Studio and more. **[[Free for OSS](https://elmah.io/sponsorship/opensource)]** **[$]** * [BugSnag](https://docs.bugsnag.com/platforms/dotnet/) - Logs errors. Includes useful diagnostic info like stack trace, session, release, etc. Has a free tier. **[Free for OSS][$]**
Have used NLog successfully in numerous projects.
What's the most widely-used logging framework in C#?
[ "", "c#", "logging", "" ]
One SEO advice we got was to move all javascript to external files, so the code could be removed from the text. For fixed scripts this is not a problem, but some scripts need to be generated as they depend on some ClientId that is generated by asp.net. Can I use the ScriptManager (from asp.net Ajax or from Telerik) to send this script to the browser or do I need to write my own component for that? I found only ways to combine fixed files and/or embedded resources (also fixed).
How about registering the ClientIDs in an inline Javascript array/hash, and have your external JS file iterate through that?
Spiderbots do not read JavaScript blocks. This advice is plain wrong.
Move generated javascript out of rendered html
[ "", "asp.net", "javascript", "seo", "scriptmanager", "" ]
Is there an event that fires when JavaScript files are loaded? The problem came up because YSlow recommends to move JavaScript files to the bottom of the page. This means that `$(document).ready(function1)` is fired before the js file that contains the code for `function1` is loaded. How to avoid this kind of situation?
I don't have a reference for it handy, but script tags are processed in order, and so if you put your `$(document).ready(function1)` in a script tag after the script tags that define function1, etc., you should be good to go. ``` <script type='text/javascript' src='...'></script> <script type='text/javascript' src='...'></script> <script type='text/javascript'> $(document).ready(function1); </script> ``` Of course, another approach would be to ensure that you're using only one script tag, in total, by combining files as part of your build process. (Unless you're loading the other ones from a CDN somewhere.) That will also help improve the perceived speed of your page. EDIT: Just realized that I didn't actually answer your question: ~~I don't think there's a cross-browser event that's fired, no.~~ *There is if you work hard enough, see below.* You can test for symbols and use setTimeout to reschedule: ``` <script type='text/javascript'> function fireWhenReady() { if (typeof function1 != 'undefined') { function1(); } else { setTimeout(fireWhenReady, 100); } } $(document).ready(fireWhenReady); </script> ``` ...but you shouldn't have to do that if you get your script tag order correct. --- Update: You can get load notifications for `script` elements you add to the page dynamically if you like. To get broad browser support, you have to do two different things, but as a combined technique this works: ``` function loadScript(path, callback) { var done = false; var scr = document.createElement('script'); scr.onload = handleLoad; scr.onreadystatechange = handleReadyStateChange; scr.onerror = handleError; scr.src = path; document.body.appendChild(scr); function handleLoad() { if (!done) { done = true; callback(path, "ok"); } } function handleReadyStateChange() { var state; if (!done) { state = scr.readyState; if (state === "complete") { handleLoad(); } } } function handleError() { if (!done) { done = true; callback(path, "error"); } } } ``` In my experience, error notification (`onerror`) is not 100% cross-browser reliable. Also note that some browsers will do both mechanisms, hence the `done` variable to avoid duplicate notifications.
When they say "The bottom of the page" they don't literally mean the bottom: they mean just before the closing `</body>` tag. Place your scripts there and they will be loaded before the DOMReady event; place them afterwards and the DOM will be ready before they are loaded (because it's complete when the closing `</html>` tag is parsed), which as you have found will not work. If you're wondering how I know that this is what they mean: I have worked at Yahoo! and we put our scripts just before the `</body>` tag :-) EDIT: also, see T.J. Crowder's reply and make sure you have things in the correct order.
How to detect if javascript files are loaded?
[ "", "javascript", "jquery", "" ]
I'm working more and more with desktop applications, and my GUIs SUCK. I'm familiar with the basics of GUI design, but am having trouble putting them into practice. What I'm looking for are good (or at least decent) guides to building (**not designing!**) a GUI in Visual Studio. Failing that (I've not found much via the usual sources), I have to ask: is it possible/worth the effort to build a GUI with VS2K5's 'Design' view? That's what I've been largely using, since I'm a visual person. **Specifically, I am looking for help in the 'nuts & bolts' of IMPLEMENTING a completed design** I am not adverse to installing extra tools if needed, but my preference is to stick with things you get through a vanilla install of VS2k5 if possible.
The Visual Studio designer for **WinForms** works really well. I use it all the time when creating WinForms apps. The alternative approach is to define the UI elements in code, which is quite painful. OTOH, in my opinion the VS designer experience for **WPF** and **WebForms** (ASP.NET) is not nearly as good as with WinForms. Fortunately, for WPF and WebForms apps, if you don't like the designer you can at least fall back to using declarative markup, which is a lot better than defining the UI elements in code (unfortunately WinForms does not have declarative markup language). Using the VS WinForms designer, here are a couple tips to improve your experience: * Learn how to use the [Anchor property](https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-6165908.html). Learning this along with the Dock property probably improved my WinForms design experience more than anything else. * When in the designer, always have the [Document Outline](http://coolthingoftheday.blogspot.com/2005/11/document-outline-window-in-vs-2005-is.html) view open, which shows you the control hierarchy of your form in a tree view... really helpful, especially when renaming controls.
If you already have your design layed out and planned, then implementing it should be the easy part. With WinForms, it really is drag and drop (and setting some properties, such as for docking and anchoring). The trick I found that really helped getting through implementation is to completely and totally mock out the interface on paper. I mean EVERYTHING: every menu, button, label, grid, etc. should be sketched out. After that, it's just a matter of dragging the controls on to a form, renaming them to something sensible, and making sure that window sizing doesn't throw your controls out of place. If you don't have a fully realized design to work from when creating the GUI, you will have a very hard time since you will still be making design decision that will get in the way of the construction. EDIT: If you're willing to pay, <http://www.learnvisualstudio.net/> has several videos on the topic of making simple GUIs for a basic application, usually oriented towards a particular control (DataGridView, ListView, etc.).
Good resources for GUI creation in Visual Studio
[ "", "c#", "visual-studio", "user-interface", "" ]
I've got files with spaces in their names that are already on my server. I want to rename them with underscores. I've tried putting a slash before the space, and I've tried replacing the space with %20. Still PHP gives me: > No such file or directory. Here's my code: ``` $dir = './'; $dhandle = opendir($dir); $old_files = array(); if ($dhandle) { while (false !== ($fname = readdir($dhandle))) { if ( ($fname != '.') && ($fname != '..') ) { $old_files[] = (is_dir( "./$fname" )) ? "(Dir) {$fname}" : $fname; } } closedir($dhandle); } $new_files = str_replace(' ', '_', $old_files); $x = 0; foreach($old_files as $file) { rename(rawurlencode($file), $new_files[$x++]); } ```
Are you sure the no such file error does not happen if you don't attempt the rename? A good first step when debugging is to simplify the problem until it's no longer buggy. I can't tell if you did this because it wasn't working at first or not, but you definitely should not be using `rawurlencode()` on a local filename, that's guaranteed to screw things up. Additionally, I'm curious what you're doing with `"(Dir) {$fname}"` - that seems to also be a bug. I suspect more likely what you want to do is: ``` if ( ($fname != '.') && ($fname != '..') && !is_dir("./$fname" )) { $old_files[] = $fname; } ``` You should also realize, however, that what `dir` returns is the filename *relative to the directory passed* so you need to make sure your `is_dir()` and rename operations take that into account. So more than likely you want to say: ``` is_dir($dir.'/'.$fname); ``` and ``` rename($dir.'/'.$file,$dir.'/'.$new_files[$x++]); ```
Add a: ``` print "$file\n"; ``` before the rename statement to see what you're getting. Also, you should add a strstr($fname, ' ') to your if statement before adding the file to the array so you only operate on filenames containing a space: ``` if ( ($fname != '.') && ($fname != '..') && !is_dir("./$fname" ) && strstr($fname, ' ')) { $old_files[] = $fname; } ```
Using PHP to rename files with spaces
[ "", "php", "rename", "filenames", "spaces", "" ]
Given the following markup. ``` <div id="example"> <div> <div> <input type='hidden'></input> </div> </div> </div> ``` How can I quickly get the hidden input element given I have the ID for the top most div element with the ID 'example'? I can hack away at it so I can just iterate through each child element until I hit the input, however, I'd like to improve on that and utilize Prototype and simply jump to that hidden input given the div. Thanks!
``` $$('#example input[type=hidden]').first() ```
Prototype provides a whole bunch of ways to do this: ``` // This, from Bill's answer, is probably the fastest, since it uses the // Browser's optimized selector engine to get straight to the element $$('#example input[type=hidden]').first(); // This isn't bad either. You still use the browser's selector engine // To get straight to the #example element, then you must traverse a // (small) DOM tree. // // element.down(selector) selects the first node matching the selector which // is an decendent of element $('example').down('input'); // Here, you'll get an array containing all the inputs under 'example'. In your HTML // there is only one. $('example').select('input') // You can also use element.select() to combine separate groups of elements, // For instance, if you needed all the form elements: $('example').select('input', 'textarea', 'select'); ```
Traversing to a specific child element with Prototype
[ "", "javascript", "prototypejs", "" ]
I'm trying to serialize a class that derives from **BindingList(Floor)**, where **Floor** is a simple class that only contains a property **Floor.Height** Here's a simplified version of my class ``` [Serializable] [XmlRoot(ElementName = "CustomBindingList")] public class CustomBindingList:BindingList<Floor> { [XmlAttribute("publicField")] public string publicField; private string privateField; [XmlAttribute("PublicProperty")] public string PublicProperty { get { return privateField; } set { privateField = value; } } } ``` I'll serialize an instance of CustomBindingList using the following code. ``` XmlSerializer ser = new XmlSerializer(typeof(CustomBindingList)); StringWriter sw = new StringWriter(); CustomBindingList cLIst = new CustomBindingList(); Floor fl; fl = new Floor(); fl.Height = 10; cLIst.Add(fl); fl = new Floor(); fl.Height = 10; cLIst.Add(fl); fl = new Floor(); fl.Height = 10; cLIst.Add(fl); ser.Serialize(sw, cLIst); string testString = sw.ToString(); ``` Yet **testString** above ends getting set to the following XML: ``` <CustomBindingList xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"> <Floor Height="10" /> <Floor Height="10" /> <Floor Height="10" /> </CustomBindingList>" ``` How do I get "publicField" or "publicProperty to serialize as well?
XML serialization handles collections in a specific way, and never serializes the fields or properties of the collection, only the items. You could either : * implement IXmlSerializable to generate and parse the XML yourself (but it's a lot of work) * wrap your BindingList in another class, in which you declare your custom fields (as suggested by speps)
The short answer here is that .NET generally expects something to **be** a collection **xor** to have properties. This manifests in a couple of places: * xml serialization; properties of collections aren't serialized * data-binding; you can't data-bind to properties on collections, as it implicitly takes you to the first item instead In the case of xml serialization, it makes sense if you consider that it might just be a `SomeType[]` at the client... where would the extra data go? The common solution is to *encapsulate* a collection - i.e. rather than ``` public class MyType : List<MyItemType> // or BindingList<...> { public string Name {get;set;} } public class MyType { public string Name {get;set;} public List<MyItemType> Items {get;set;} // or BindingList<...> } ``` Normally I wouldn't have a `set` on a collection property, but `XmlSerializer` demands it...
Public fields/properties of a class derived from BindingList<T> wont serialize
[ "", "c#", "serialization", "xml-serialization", "bindinglist", "" ]
I would like to generate a line number for each line in the results of a sql query. How is it possible to do that? Example: In the request ``` select distinct client_name from deliveries ``` I would like to add a column showing the line number I am working on sql server 2005.
It depends on the database you are using. One option that works for SQL Server, Oracle and MySQL: ``` SELECT ROW_NUMBER() OVER (ORDER BY SomeField) AS Row, * FROM SomeTable ``` Change SomeField and SomeTable is according to your specific table and relevant field to order by. It is preferred that SomeField is unique in the context of the query, naturally. In your case the query would be as follows (Faiz crafted such a query first): ``` SELECT ROW_NUMBER() OVER (ORDER BY client_name) AS row_number, client_name FROM (SELECT DISTINCT client_name FROM deliveries) TempTable ``` I think it won't work for SQLite (if someone can correct me here I would be grateful), I'm not sure what's the alternative there.
You can use the ROW\_NUMBER function for this. Check the syntax for this here <http://msdn.microsoft.com/en-us/library/ms186734.aspx> ``` SELECT FirstName, LastName, ROW_NUMBER() OVER(ORDER BY FirstName) AS 'Row#' FROM Sales.vSalesPerson; ``` For your query, ``` SELECT client_name, ROW_NUMBER() Over (Order By client_name) AS row_number FROM (select distinct client_name from deliveries) SQ ``` will work.
SQL to output line number in results of a query
[ "", "sql", "sql-server", "sql-server-2005", "" ]
I have an iFrame, content of which is inside another iFrame. I want to get the inside iFrame's `src` content. How can I do this using javascript?
The outer page: ``` <html> <body> <iframe id="ifr1" src="page1.htm"></iframe> <iframe id="ifr2" src="http://www.google.com"></iframe> </body> </html> ``` page1.htm: ``` <html> <body> <script type="text/javascript"> document.write(parent.document.getElementById('ifr2').src); </script> </body> </html> ```
iframeInstance.contentWindow.document - this document loaded from SRC url. and vice verse - to get from inner document to parent use: parent.document
How to get iFrame src content using javascript?
[ "", "javascript", "iframe", "" ]
I seem to be asking a lot of SQL questions at the moment. (I would normally write a program to sort the data into a report table, however at the moment that is not possible, and needs to be done using SQL) **The Question** I need a where clause that returns results with the next working day. i.e. Monday 01/01/01 the next working day would be Tuesday 02/01/01 which could be achieved with a simple date add. However on a Friday 05/01/01 the next working day is Monday 08/01/01. Is there anything built in to help cope with this easily? Thanks for your advice.
You could do this with a simple day check and add 3 days rather than one if its a Friday. However, do you need to take into consideration public holidays though?
The key is to use the [DATEPART(weekday,@date)](http://msdn.microsoft.com/es-es/library/ms174420.aspx) function, it'll return the day of the week, so if it's saturday or sunday you just add one or two to the current date to get the desired result. You can create a user defined function to do so easily, for example [Pinal Dave](http://blog.sqlauthority.com/2007/07/23/sql-server-udf-function-to-get-previous-and-next-work-day-exclude-saturday-and-sunday/) has this ``` CREATE FUNCTION dbo.udf_GetPrevNextWorkDay (@dtDate DATETIME, @strPrevNext VARCHAR(10)) RETURNS DATETIME AS BEGIN DECLARE @intDay INT DECLARE @rtResult DATETIME SET @intDay = DATEPART(weekday,@dtDate) --To find Previous working day IF @strPrevNext = 'Previous' IF @intDay = 1 SET @rtResult = DATEADD(d,-2,@dtDate) ELSE IF @intDay = 2 SET @rtResult = DATEADD(d,-3,@dtDate) ELSE SET @rtResult = DATEADD(d,-1,@dtDate) --To find Next working day ELSE IF @strPrevNext = 'Next' IF @intDay = 6 SET @rtResult = DATEADD(d,3,@dtDate) ELSE IF @intDay = 7 SET @rtResult = DATEADD(d,2,@dtDate) ELSE SET @rtResult = DATEADD(d,1,@dtDate) --Default case returns date passed to function ELSE SET @rtResult = @dtDate RETURN @rtResult END GO ```
SQL - WHERE clause Return results with next working day
[ "", "sql", "t-sql", "reporting-services", "" ]
If I have the following in my html: ``` <div style="height:300px; width:300px; background-color:#ffffff;"></div> ``` And this in my css style sheet: ``` div { width:100px; height:100px; background-color:#000000; } ``` Is there any way, with javascript/jquery, to remove all of the inline styles and leave only the styles specified by the css style sheet?
`$('div').attr('style', '');` or `$('div').removeAttr('style');` (From [Andres's Answer](https://stackoverflow.com/questions/1229688/how-can-i-erase-all-inline-styles-with-javascript-and-leave-only-the-styles-speci/1229796#1229796)) To make this a little smaller, try this: `$('div[style]').removeAttr('style');` This should speed it up a little because it checks that the divs have the style attribute. Either way, this might take a little while to process if you have a large amount of divs, so you might want to consider other methods than javascript.
**Plain JavaScript:** You don't need jQuery to do something trivial like this. Just use the [`.removeAttribute()`](https://developer.mozilla.org/en-US/docs/Web/API/Element.removeAttribute) method. Assuming you are just targeting a single element, you can easily use the following: [**(example)**](http://jsfiddle.net/9ypaers0/) ``` document.querySelector('#target').removeAttribute('style'); ``` If you are targeting multiple elements, just loop through the selected collection of elements: [**(example)**](http://jsfiddle.net/en1ux4jc/) ``` var target = document.querySelectorAll('div'); Array.prototype.forEach.call(target, function(element){ element.removeAttribute('style'); }); ``` [`Array.prototype.forEach()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach) - IE9 and above / [`.querySelectorAll()`](https://developer.mozilla.org/en-US/docs/Web/API/Document.querySelectorAll) - IE 8 (partial) IE9 and above.
How can I erase all inline styles with javascript and leave only the styles specified in the css style sheet?
[ "", "javascript", "jquery", "css", "inline", "" ]
I have HTML something like this ``` <div id="foo"> <select> <option> one </option> </select> </div> ``` when I use ``` document.getElementById('foo').innerHTML = document.getElementById('foo').innerHTML.replace("<option> one </option>", "<option> two </option>") ; ``` The innerHTML get replaced but it does not get reflected in the browser. If I alert innerHTML I can see that it has been changed now but in the browser it still shows old option. Is there any way to make this change recognized by the browser ? Thanks in advance.
works fine for me in Firefox 3.5 **[Working Demo](http://jsbin.com/ogiga)** **EDIT:** You must be using IE. You need to create a new option and add it to the element, or amend the text of the existing option **[Working Demo](http://jsbin.com/ikuzi)** - tested and working in FireFox and IE 7. ``` var foo = document.getElementById('foo'); var select = foo.getElementsByTagName('select'); select[0].options[0].text = ' two '; ```
Better to give an id to the select tag and use new option to add an item. ``` var sel =document.getElementById ( "selectElementID" ); var elOptNew = document.createElement('option'); elOptNew.text = 'Insert' + 2; elOptNew.value = 'insert' + 2; sel.options.add ( elOptNew ); ``` If you need to replace an option ``` sel.options[indexNumber].text = 'text_to_assign'; sel.options[indexNumber].value = 'value_to_assign'; ```
innerHTML replace does not reflect
[ "", "javascript", "internet-explorer", "innerhtml", "" ]
Is there a de-facto standard library for creating ASCII "tables" in PHP? I want some PHP code that, when handed an array or other data structure will output tables that look something like the mysql command line client's results ``` +--------+---------------------+----------------------------------+ | fld_id | fld_name | fld_email | +--------+---------------------+----------------------------------+ | 1 | A value | another value | | 2 | A value | | | 3 | A value | another value | +--------+---------------------+----------------------------------+ ``` Not rocket science, or even computer science, but certainly tedious science that someone's already solved.
While it's not the *defacto* standard, the [`Zend_Text_Table`](http://framework.zend.com/manual/en/zend.text.table.introduction.html) component of the Zend Framework does exactly this. It has the added bonus of being highly configurable and modular; for example it affords you control over all sorts of formatting details. Also, it adheres to strict OOP principals, if that matters to you. While the fact that it is part of a larger library may be intimidating, the component is fairly decoupled, the only dependency I can see is on the `Zend_Loader_PluginLoader`, for its pluggable rendering engine. Most importantly, it fully supports UTF-8.
This is what you are looking for: <http://code.google.com/p/php-text-table/>
PHP ASCII Table Library
[ "", "php", "reporting-services", "ascii", "" ]
I am trying to configure a JMS server (OpenJMS) into a Spring application and when I refer the resources using the notation "jms/<> I get a "name" not bound exception. Any clue what is missing? ``` javax.naming.NameNotFoundException: Name jms is not bound in this Context at org.apache.naming.NamingContext.lookup(NamingContext.java:768) at org.apache.naming.NamingContext.lookup(NamingContext.java:138) at org.apache.naming.NamingContext.lookup(NamingContext.java:779) at org.apache.naming.NamingContext.lookup(NamingContext.java:138) ``` The bean is defined as: ``` <bean id="connectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean"> <property name="jndiTemplate" ref="jmsProvider"/> <property name="jndiName" value="jms/RefreshTopic_CF"/> <property name="resourceRef" value="true" /> </bean> ``` I have the JMS lib in class path and the openjms server is running.
In the web.xml we couldn't refer the as an interface (javax.jms.Topic) we had to use the exact class. This was a problem with OpenJMS and not with Websphere. **Not allowed:** ``` <resource-ref id="ResourceRef_125180"> <description>Topic</description> <res-ref-name>jms/MyTopic</res-ref-name> <res-type>javax.jms.Topic</res-type> <res-auth>Container</res-auth> <res-sharing-scope>Shareable</res-sharing-scope> </resource-ref> ``` **allowed:** ``` <resource-ref id="ResourceRef_125180"> <description>Topic</description> <res-ref-name>jms/MyTopic</res-ref-name> <res-type>org.exolab.jms.client.JmsTopic</res-type> <res-auth>Container</res-auth> <res-sharing-scope>Shareable</res-sharing-scope> </resource-ref> ```
It seems you either * Didn't configured the OpenJMS to use the same JNDI tree the spring is looking at - have a look [here](http://openjms.sourceforge.net/config/jndi.html) * Looking for the wrong path in the JNDI. As a hunch, drop the "jms/" from the jndiName.
JNDI Context :: Name jms not bound in this Context
[ "", "java", "spring", "jms", "openjms", "" ]
I have a seemingly simple question, but can't find the answer. I have a webpage, which may have resulted from a POST request and may have an anchor (#) in the URL. I want to reload this page *as a GET request* in JavaScript. So it's similar to [this question](https://stackoverflow.com/questions/570015/how-do-i-reload-a-page-without-a-postdata-warning-in-javascriptate), but I actually want to avoid the POST, not just the warning about it. So, for example, if the page resulted from a POST request to "<http://server/do/some?thing#>" I want to reload the URL "<http://server/do/some?thing>" as a GET. If I try ``` window.location.reload(true); ``` that causes IE to try a POST. If I instead do: ``` window.location = window.location.href; ``` this does nothing when the URL has an anchor. Do I really need to do string manipulation myself to get rid of the "#whatever" or is there an easier, "better" way to do this?
The best I've come up with so far is: ``` function reloadAsGet() { var loc = window.location; window.location = loc.protocol + '//' + loc.host + loc.pathname + loc.search; } ```
Try the following: ``` location.replace(location.href) ```
JavaScript to reload the page as GET request
[ "", "javascript", "refresh", "" ]
I have 4 forms (almost similar with few diference) to take customer service requests. All those forms have similar validations. Now I am developing a website in asp.net 3.5 and I have very short time for delivering that. I want an approach whether to use Ajax tabcontrol with 4 tabs with 4 different usercontrols or single form and just give look and feel of tab.
I use a single form object with this and just give it a tabular look. Works great. I have several recent websites that I have taken this approach to.
If you use a single form, you're essentially tasking your server side with parsing and making sense of the data. you may run into all kinds of edge-cases where some fields on the real form will come from several "logical" forms, and not make sense. My recommendation: if you have 4 separate logical functions, create 4 separate forms. They don't have to necessarily reside on 4 different pages - you just show the relevant one when the tab it corresponds to is pressed. That way, when you submit to the server-side, it already knows which form to expect, and won't be surprised by fields that shouldn't be there.
whether to use Ajax tabcontrol or use images to give tab control look
[ "", "c#", "asp.net", "" ]
I am using php / mysql and protype.js to delete record from a table. The problem is that the record in the database is not deleted. index.php: ``` <a href="javascript: deleteId('<?php echo $studentVo->id?>')">Delete</a></td> ``` Script is ``` function deleteId(id) { alert("ID : "+id); new Ajax.Request('delete.php?action=Delete&id='+id,{method:'post'}); $(id).remove(); // because <tr id='".$row[id]."'> :) } ``` delete.php ``` <?php /* Database connection */ include('configuration.php'); echo "hello,..."; if(isset($_POST['id'])){ $ID = $_POST['id']; $sql = 'DELETE FROM student where id="'.$ID.'"'; mysql_query($sql); } else { echo '0'; } ?> ``` `alert("ID : "+id);` is working properly but the code after that is not.
You are using a GET request, from JS : ``` {method:'get'} ``` And your PHP code uses data he thinks arrives as POST : ``` $ID = $_POST['id']; ``` You should use the same method on both sides. *(As you are modifying / deleting data, you should probably use POST)* As a sidenote, you should definitly escape/protected/check the data you are using in the SQL query, to avoid SQL injections, using, for instance, [intval](http://php.net/intval) as you are working with an integer ; you'd use [mysql\_real\_escape\_string](http://php.net/manual/en/function.mysql-real-escape-string.php) if you were working with a string. Another way would be to stop using the old `mysql` extension, and start using [mysli](http://php.net/mysqli) or [PDO](http://php.net/pdo), which means you could use prepared statements ([mysqli](http://php.net/manual/en/mysqli.prepare.php), [pdo](http://php.net/manual/en/pdo.prepare.php)) **EDIT after the comment** : you also, now that the request is made in POST, need to change the way parameters are passed : they should not be passed in the URL anymore. I suppose that something like this should work : ``` var myAjax = new Ajax.Request( 'delete.php', { method: 'post', parameters: {action: id} }); ``` Or you could also use something like this, building the parameters string yourself : ``` var myAjax = new Ajax.Request( 'delete.php', { method: 'post', parameters: 'action=' + id }); ``` *(Not tested, so you might have to change a few things ;-) )* For more informations, take a look at [`Ajax.Request`](http://www.prototypejs.org/api/ajax/request) and [Ajax options](http://www.prototypejs.org/api/ajax/options) :-)
It seems like your ajax request is using GET but your delete script is trying to retrieve the id via POST. Try setting `{method:'get'}` to `{method:'post'}`.
Delete records from database with an Ajax request
[ "", "php", "ajax", "prototypejs", "" ]
When generating XML in C#, Is there a problem with generating it as a string? In the past I've found generating XML programatically very verbose and convoluted. Creating the xml through string concatenation/a string builder seems much easier but, it feels like bad practice. Should I generate XML as a string?
The XDocument, XElement and XAttribute classes make xml generation in C# much easier to do. Than using the XmlDocument or XmlWriter. As an example, to produce this: ``` <RootElement> <ChildElement Attribute1="Hello" Attribute2="World" /> <ChildElement Attribute1="Foo" Attribute2="Bar" /> </RootElement> ``` You can do this: ``` XDocument xDocument = new XDocument( new XElement("RootElement", new XElement("ChildElement", new XAttribute("Attribute1", "Hello"), new XAttribute("Attribute2", "World") ), new XElement("ChildElement", new XAttribute("Attribute1", "Foo"), new XAttribute("Attribute2", "Bar") ) ) ); ```
Have you tryed Linq to Xml? it is not very verbose: ``` XElement xml = new XElement("contacts", new XElement("contact", new XAttribute("id", "1"), new XElement("firstName", "first"), new XElement("lastName", "last") ), new XElement("contact", new XAttribute("id", "2"), new XElement("firstName", "first2"), new XElement("lastName", "last2") ) ); Console.Write(xml); ```
Should I generate XML as a string in C#?
[ "", "c#", "xml", "string", "" ]
What I'm trying to make is a check list for a lotto game, which is a sort of bingo for my family. I will first try to explain what the check list does and why, excuse my technical english, I'm dutch, so some words can be wrong :) I have a list with a couple of people who play the lotto/bingo game. All players pick 10 numbers and once a week there is a draw of 6 numbers, I try to explain step by step what the code has to do. 1 - 10 people's numbers should be checked 2 - 6 numbers are added every week which should be compared with the numbers of the people. 3 - font should be colored green when there is a match. 4 - font should stay red when there is no match Here is the code I have this far, [a live version is at the link](http://www.coldcharlie.nl/lotto_test.html). The code beneath works great, but the problem is that the code is designed to compare var A with var B, this is a bottleneck, because it's a 1 on 1 action. I can't add more people without adding a Draw day. Now my question. What should be done to add more people (A1, A2, A3 etc etc.) without adding a draw date like B2. I hope this is clear enough. :) ``` <script type = "text/javascript"> var a1 = ["2","3","8","12","23", "37", "41", "45", "48"] var a2 = ["2","14","3","12","24", "37", "41", "46", "48"] var b1 = ["2","5", "11","16","23","45", "46"]; var b2 = ["1","23", "11","14","23","42", "46"]; for (var i = 0; i< a1.length; i++) { for (var j = 0; j< b1.length; j++) { if (a1[i] == b1[j]) { a1[i]= "g"+ a1[i]; } } } for (var i = 0; i< a2.length; i++) { for (var j = 0; j< b2.length; j++) { if (a2[i] == b2[j]) { a2[i]= "g"+ a2[i]; } } } // john document.write("<font color = '#FFFFFF'>" + "<b>" + "John &nbsp&nbsp " + "</b>"); for (var i = 0; i< a1.length; i++) { if (a1[i].substr(0,1) == "g") { a1[i] = a1[i].substr(1,20); document.write("<font color = '#00FF00'>", a1[i] + " &nbsp&nbsp "); } else { document.write("<font color = '#FF0000'>", a1[i] + " &nbsp&nbsp "); } } // Michael document.write("<br><br>"); document.write("<font color = '#FFFFFF'>" + "<b>" + "Michael &nbsp&nbsp " + "</b>"); for (var i = 0; i< a2.length; i++) { if (a2[i].substr(0,1) == "g") { a2[i] = a2[i].substr(1,20); // The Draw document.write("<font color = '#00FF00'>", a2[i] + " &nbsp&nbsp "); } else { document.write("<font color = '#FF0000'>", a2[i] + " &nbsp&nbsp "); } } document.write("<br><br>"); document.write("<br><br>"); document.write("<font color = '#FFFFFF'>" + "<b>" + "Draw day 1 " + "</b>"); document.write("<br>"); document.write("<font color = '#FFFFFF'>" + "<b>" + "Sat 08-08-2009 " + "</b>"); document.write("<br><br>"); for (var j = 0; j< b1.length; j++) { document.write("<font color = '#FFFFFF'>", b1[j] + " &nbsp&nbsp "); } document.write("<br><br>"); document.write("<br><br>"); document.write("<font color = '#FFFFFF'>" + "<b>" + "Draw day 2 " + "</b>"); document.write("<br>"); document.write("<font color = '#FFFFFF'>" + "<b>" + "Sat 15-08-2009 " + "</b>"); document.write("<br><br>"); for (var j = 0; j< b2.length; j++) { document.write("<font color = '#FFFFFF'>", b2[j] + " &nbsp&nbsp "); } </script> ```
In addition to rewriting the code (refactoring) so the array comparison into a function as Miky D did, you can make the comparison more efficient by using an object to hold the winning numbers. Note that this code isn't the final version; there are further refinements. ``` var guesses = [["2","3","8","12","23", "37", "41", "45", "48"], ["2","14","3","12","24", "37", "41", "46", "48"]]; var draws = [ {2:1, 5:1, 11:1, 16:1, 23:1, 45:1, 46:1}, {1:1, 23:1, 11:1, 14:1, 23:1, 42:1, 46:1}]; function checkArray(guesses, draw) { for (var i = 0; i< guesses.length; ++i) { if (draw[guesses[i]]) { guesses[i] = 'g' + guesses[i]; } } } checkArray(guesses[0], draws[1]); ``` By turning the winning numbers into the indices rather than the values, you can get rid of a loop. Also, 'a' and 'b' aren't very descriptive names. Short names gain you nothing but obfuscation. By marking successful and successful guesses differently (currently, you prepend 'g' to successes), you can also simplify the code to display the results. The `<font>` tag has been deprecated for awhile, so this refinement uses `<span>`s with a class that you can style. ``` function checkArray(guesses, draw) { var results = {} for (var i = 0; i< guesses.length; ++i) { if (draw.picks[guesses[i]]) { results[guesses[i]] = 'win'; } else { results[guesses[i]] = 'loss'; } } return results; } ... document.write('<span class="name">John</span>'); var results = checkArray(guesses[0], draws[1]); for (var p in results) { document.write('<span class="'+results[i]+'">'+p+'</span>'); } ``` Since `document.write` is also deprecated, I'll replace it with the modern equivalents, [`document.createElement`](https://developer.mozilla.org/en/DOM/document.createElement) and [`Node.appendChild`](https://developer.mozilla.org/En/DOM/Node.appendChild). If you think the resulting code is too verbose, you can instead use [`innerHTML`](http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx), though its use is [controversial](http://domscripting.com/blog/display/35). Since player names are closely tied to player picks, I'll also index the player picks by player name. Put the following in a file named "lotto.js" in the same folder as the web page. ``` function Result(guesses) { for (var i = 0; i< guesses.length; ++i) { this[guesses[i]] = ''; } } function checkDraw(guesses, draw, results) { for (var i = 0; i< guesses.length; ++i) { if (draw.picks[guesses[i]]) { results[guesses[i]] = 'picked'; } } return results; } function appendTo(elt, parent) { if (parent) { document.getElementById(parent).appendChild(elt); } else { document.body.appendChild(elt); } } function printResults(name, results, parent) { var resultElt = document.createElement('div'); resultElt.appendChild(document.createElement('span')); resultElt.firstChild.appendChild(document.createTextNode(name)); resultElt.firstChild.className='name'; var picks = document.createElement('ol'); picks.className='picks'; for (var p in results) { picks.appendChild(document.createElement('li')); picks.lastChild.appendChild(document.createTextNode(p)); picks.lastChild.className = results[p]; } resultElt.appendChild(picks); appendTo(resultElt, parent); } function printResultsFor(name, draws, parent) { var player = players[name]; var results = new Result(player); for (var i=0; i<draws.length; ++i) { checkDraw(player, draws[i], results); } printResults(name, results, parent); } function printDraw(which, draw, parent) { var drawElt = document.createElement('div'); drawElt.className='draw'; drawElt.appendChild(document.createElement('h3')); drawElt.lastChild.appendChild(document.createTextNode('Draw '+which)); drawElt.lastChild.className='drawNum'; drawElt.appendChild(document.createElement('div')); drawElt.lastChild.className='date'; drawElt.lastChild.appendChild(document.createTextNode(draw.when)); var picks = document.createElement('ol'); picks.className='picks'; for (var p in draw.picks) { picks.appendChild(document.createElement('li')); picks.lastChild.appendChild(document.createTextNode(p)); } drawElt.appendChild(picks); appendTo(drawElt, parent); } ``` Here's the corresponding HTML page: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html> <head> <style type="text/css"> body { font-family: Verdana, Arial, Helvetica, sans-serif; color: white; background-color: #333; } .picks, .picks * { display: inline; margin: 0; padding: 0; list-style-type: none; } .picks * { margin: auto 0.25em; } #Results .picks * { color: red; } .name, .picks .name { color: white; font-weight: bold; margin-right: 0.5em; } #Results .picked { color: lime; } .drawNum, #Draws H3 { margin-bottom: 0; } </style> <script type="text/javascript" src="lotto.js"></script> </head> <body> <div id="Results"></div> <div id="Draws"></div> <script type="text/javascript"> var players = {John: [2, 3, 8, 12, 23, 37, 41, 45, 48], Michael: [2, 14, 3, 12, 24, 37, 41, 46, 48]}; var draws = [ {when: 'Sat 08-08-2009', picks:{2:1, 5:1, 11:1, 16:1, 23:1, 45:1, 46:1}}, {when: 'Sat 15-08-2009', picks:{1:1, 23:1, 11:1, 14:1, 23:1, 42:1, 46:1}}]; for (name in players) { printResultsFor(name, draws, 'Results'); } for (var i=0; i<draws.length; ++i) { printDraw(i+1, draws[i]); } </script> </body> </html> ``` You can refine the CSS to get the exact styling you want. The code could be further refactored to use OOP, which would simplify creating new players and draws, but it's more involved so I won't go in to it here. Update: The above code was rewritten so that each player's guesses is compared to every draw. The [live sample version](http://libertatia.exofire.net/others/bingo/) of the code has been refactored almost beyond recognition to use OOP. It also uses features you probably haven't seen before, such as [JS closures](http://robertnyman.com/2008/10/09/explaining-javascript-scope-and-closures/), [higher order functions](http://en.wikipedia.org/wiki/Higher-order_function) and CSS [generated content and counters](http://www.w3.org/TR/CSS2/generate.html). It's longer and harder to understand but more flexible and a little easier to use.
you should use === as comparison operator For example let x = 5: ``` x == 8 // yield false ``` whereas: ``` x == "5" // yield **true** ``` === is like saying "is exactly equal to" (by value **and** type) ``` x === 5 // yield true x === "5" // yield false ```
Compare array in javascript
[ "", "javascript", "" ]
I have the php code below which help me get a photo's thumbnail image path in a script It will take a supplied value like this from a mysql DB '2/34/12/thepicture.jpg' It will then turn it into this '2/34/12/thepicture\_thumb1.jpg' I am sure there is a better performance way of doing this and I am open to any help please Also on a page with 50 user's this would run 50 times to get 50 different photos ``` // the photo has it is pulled from the DB, it has the folders and filename as 1 $photo_url = '2/34/12/thepicture_thumb1.jpg'; //build the full photo filepath $file = $site_path. 'images/userphoto/' . $photo_url; // make sure file name is not empty and the file exist if ($photo_url != '' && file_exists($file)) { //get file info $fil_ext1 = pathinfo($file); $fil_ext = $fil_ext1['extension']; $fil_explode = '.' . $fil_ext; $arr = explode($fil_explode, $photo_url); // add "_thumb" or else "_thumb1" inbetween // the file name and the file extension 2/45/12/photo.jpg becomes 2/45/12/photo_thumb1.jpg $pic1 = $arr[0] . "_thumb" . $fil_explode; //make sure the thumbnail image exist if (file_exists("images/userphoto/" . $pic1)) { //retunr the thumbnail image url $img_name = $pic1; } } ``` 1 thing I am curious about is how it uses pathinfo() to get the files extension, since the extension will always be 3 digits, would other methods of getting this value better performance?
Performance-wise, if you're calling built-in PHP functions the performance is excellent because you're running compiled code behind the scenes. Of course, calling all these functions when you don't need to isn't a good idea. In your case, the `pathinfo` function returns the various paths you need. You call the `explode` function on the original name when you can build the file name like this (note, the 'filename' is only available since PHP 5.2): ``` $fInfo = pathinfo($file); $thumb_name = $fInfo['dirname'] . '/' . $fInfo['filename'] . '_thumb' . $fInfo['extension']; ``` If you don't have PHP 5.2, then the simplest way is to ignore that function and use `strrpos` and `substr`: ``` // gets the position of the last dot $lastDot = strrpos($file, '.'); // first bit gets everything before the dot, // second gets everything from the dot onwards $thumbName = substr($file, 0, $lastDot) . '_thumb1' . substr($file, $lastDot); ```
Is there a performance problem with this code, or are you just optimizing prematurely? Unless the performance is bad enough to be a usability issue and the profiler tells you that this code is to blame, there are much more pressing issues with this code. To answer the question: "How can I improve this PHP code?" **Add whitespace.**
How can I improve this PHP code?
[ "", "php", "" ]
I would like to detect when a device is connected to an ethernet port of the machine that my application is running on. I know how to do this with a USB port but the problem is, the Port isn't USB! If it was a USB device I would simply override WndProc and catch the message, if it is WM\_DEVICECHANGE, then i'm on to a winner, I was wondering if it was as simple as this with any device that may be plugged into the port? I don't want to know if there is anything happening, or if the device is working, just simply to find if there has been an insertion or removal.
I never used it myself, but I think that the [`NetworkChange.NetworkAvailabilityChanged`](http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkchange.networkavailabilitychanged.aspx) event might fit your needs. **Update** A brief investigation indicates that [NetworkChange.NetworkAddressChanged](http://msdn.microsoft.com/en-us/library/system.net.networkinformation.networkchange.networkaddresschanged.aspx) might work better: ``` public static void Main() { NetworkChange.NetworkAddressChanged += (s, e) => { NetworkInterface[] nics = NetworkInterface.GetAllNetworkInterfaces(); foreach (var item in nics) { Console.WriteLine("Network Interface: {0}, Status: {1}", item.Name, item.OperationalStatus.ToString()); } }; string input = string.Empty; while (input != "quit") { input = Console.ReadLine(); } } ```
I'm not sure if that's exactly suited for your needs, but you could have a look at the `System.Net.NetworkInformation.NetworkChange` class, which has 2 events that you could use : * `NetworkAddressChanged` * `NetworkAvailabilityChanged` In the event handler, you can check whether the network interface involved is an Ethernet port
Detecting Ethernet Port insertion/removal in my winforms application?
[ "", "c#", ".net", "winforms", "" ]
Is there a standard (preferably Apache Commons or similarly non-viral) library for doing "glob" type matches in Java? When I had to do similar in Perl once, I just changed all the "`.`" to "`\.`", the "`*`" to "`.*`" and the "`?`" to "`.`" and that sort of thing, but I'm wondering if somebody has done the work for me. Similar question: [Create regex from glob expression](https://stackoverflow.com/questions/445910/create-regex-from-glob-expression)
There's nothing built-in, but it's pretty simple to convert something glob-like to a regex: ``` public static String createRegexFromGlob(String glob) { String out = "^"; for(int i = 0; i < glob.length(); ++i) { final char c = glob.charAt(i); switch(c) { case '*': out += ".*"; break; case '?': out += '.'; break; case '.': out += "\\."; break; case '\\': out += "\\\\"; break; default: out += c; } } out += '$'; return out; } ``` this works for me, but I'm not sure if it covers the glob "standard", if there is one :) Update by Paul Tomblin: I found a perl program that does glob conversion, and adapting it to Java I end up with: ``` private String convertGlobToRegEx(String line) { LOG.info("got line [" + line + "]"); line = line.trim(); int strLen = line.length(); StringBuilder sb = new StringBuilder(strLen); // Remove beginning and ending * globs because they're useless if (line.startsWith("*")) { line = line.substring(1); strLen--; } if (line.endsWith("*")) { line = line.substring(0, strLen-1); strLen--; } boolean escaping = false; int inCurlies = 0; for (char currentChar : line.toCharArray()) { switch (currentChar) { case '*': if (escaping) sb.append("\\*"); else sb.append(".*"); escaping = false; break; case '?': if (escaping) sb.append("\\?"); else sb.append('.'); escaping = false; break; case '.': case '(': case ')': case '+': case '|': case '^': case '$': case '@': case '%': sb.append('\\'); sb.append(currentChar); escaping = false; break; case '\\': if (escaping) { sb.append("\\\\"); escaping = false; } else escaping = true; break; case '{': if (escaping) { sb.append("\\{"); } else { sb.append('('); inCurlies++; } escaping = false; break; case '}': if (inCurlies > 0 && !escaping) { sb.append(')'); inCurlies--; } else if (escaping) sb.append("\\}"); else sb.append("}"); escaping = false; break; case ',': if (inCurlies > 0 && !escaping) { sb.append('|'); } else if (escaping) sb.append("\\,"); else sb.append(","); break; default: escaping = false; sb.append(currentChar); } } return sb.toString(); } ``` I'm editing into this answer rather than making my own because this answer put me on the right track.
Globbing is ~~also planned for~~ implemented in Java 7. See [`FileSystem.getPathMatcher(String)`](http://docs.oracle.com/javase/7/docs/api/java/nio/file/FileSystem.html#getPathMatcher(java.lang.String)) and [the "Finding Files" tutorial](http://java.sun.com/docs/books/tutorial/essential/io/find.html).
Is there an equivalent of java.util.regex for "glob" type patterns?
[ "", "java", "glob", "" ]
I just wanted to share this Query class and get your thoughts on it. The Query class helps execute queries against a dbconnection. I haven't included the implementation, it's a bit much to post. Here's an example call, you'll get the idea: ``` OrdersDataTable table = new Query(connection) .Table("Orders") .Fields("OrderID,CustomerID,Description,Amount") .GreaterThan("OrderID", 1000) .OrderBy("OrderID") .Execute<OrdersDataTable>(); ``` Here's the reasons I like the class: * No need to write the ADO.NET Command code. Calling this class takes up less lines than the ADO.NET equivilent. * Each member function returns this so multiple calls can be chained together. I'm not sure if there is a name for this pattern. Do you know? * Handles MySql, OleDb and SqlServer dialects. * Seems more readable to me than the ADO.NET equivilent. * Order of calls is irrelevant. All parameters are buffered in internal collections and read when Execute is called. * My scenario requires me to communicate with multiple database products so I would like to write the query once in a generic manner and just pass in the given connection. It would be alot trouble to leverage db-specific features like stored procs. I have a DAL that uses this class internally. The UI would make a call into the DAL, passing a few query params and the DataTable is returned. The class has really helped reduce LOC the DAL implementation as well as made it more readable. Here's a sample DAL call: ``` OrdersDataTable orders = Orders.GetByOrderId( 1 ) ``` And the impl: ``` public static OrdersDataTable GetByOrderId( int id ) { return new Query(connection) .Table("Orders") .Fields("OrderID,CustomerID,Description,Amount") .Equals("OrderID", id) .Execute<OrdersDataTable>(); } ``` Thanks! Edit: Thanks everyone for the great feedback. Many of you suggested LinqToSql. I did not choose Linq because Microsoft currently only supports Sql Server. I need to query Jet, MySql and Sql Server tables. Someone asked how AND and OR clauses are constructed. Here an example of each ``` //and example public static OrdersDataTable GetByOrderIdAndCustomerId( int orderId, int customerId ) { return new Query(connection) .Table("Orders") .Fields("OrderID,CustomerID,Description,Amount") .Equals("OrderID", orderId) .Equals("CustomerID", customerId) .Execute<OrdersDataTable>(); } //or example public static OrdersDataTable GetByOrderIdOrCustomerId( int orderId, int customerId ) { return new Query(connection) .Table("Orders") .Fields("OrderID,CustomerID,Description,Amount") .OrBegin .Equals("OrderID", orderId) .Equals("CustomerID", customerId) .OrEnd .Execute<OrdersDataTable>(); } ```
It looks like you've written a very nice little ORM (object relational mapper) with an implementation of the Repository (or close to) pattern. You also took advantage of the design pattern called Fluent Interfaces which is what is allowing you to do .Table .Fields cascading from each other. All 3 of these patterns are very good to be included in modern software system design as you already notice they greatly reduce the LOC, enhance maintainability and greatly improve test ability. I also like that you constructed your functionality to be able to return strongly typed objects using generics correctly. **Edit:** The only possible area I could see for improvement would to be change the fact every call is a new Query and perhaps change your code to use a dependency injection framework that will inject the correct provider and when the object is called that it will initiated a database transaction for the query. If your code already pretty much does that internally in the Query class that could be called "Poor man's dependency injection" or atleast it's very similar (depending on your implementation) which if it's already working for you and you don't intend to really grow out your types of database support the Poor man's DI should be just fine. I'm just not a fan of the new keyword in any usage anymore since it usually causes high levels of code coupling that a DI framework alleviates (or it's for method hiding with is a bad bad design decision). **In response to Mark's answer**, I'm usually never a fan of code generation it always seems to become a point of failure however he does have a very good point to reduce the amount of magic strings involved. I would instead choose to use the Lambda operator and expressions to handle this though, so you could achieve this: ``` public static OrdersDataTable GetByOrderId( int id ) { return new Query(connection) .Table(x => Inflector.Pluralize(x.GetType()) .Fields(x=> { x.OrderID, x.CustomerID, x.Description, x.Amount }) .Equals(x=>x.OrderID, id) .Execute<OrdersDataTable>(); } ``` This will remove all of the magic string refactoring issues allowing you to leverage Microsoft's built in refactoring tools much easier or Resharper's (of course resharper can find magic strings during refactoring). Inflector is a free library (can't remember if it's OSS or not) that includes functionality for dealing with text, the Pluralize method will take a word and make it... plural if you couldn't guess. Where this is useful is when you have like Story where you can't just go GetType() + "s" since Storys isn't correct and Inflector will correctly return you "Stories".
I usually try and stay away from these functional ways of doing things. It can be confusing sometimes to track down issues when they arise. I would just use LINQ and accomplish the same task with more readable code.
My Query class. Your opinion?
[ "", "c#", "ado.net", "" ]
What is the easiest way to activate PHP and MySQL on Mac OS 10.6 (Snow Leopard), 10.7 (Lion), 10.8 (Mountain Lion)? I'd prefer to use any bundled versions before resorting to downloading from the PHP or MySQL websites. That also rules out MAMP and similar. I'm comfortable at the command line in Terminal.
Open a good text editor (I'd recommend TextMate, but the free TextWrangler or vi or nano will do too), and open: ``` /etc/apache2/httpd.conf ``` Find the line: ``` "#LoadModule php5_module libexec/apache2/libphp5.so" ``` And uncomment it (remove the #). Download and install the latest MySQL version from mysql.com. Choose the x86\_64 version for Intel (unless your Intel Mac is the original Macbook Pro or Macbook, which are not 64 bit chips. In those cases, use the 32 bit x86 version). Install all the MySQL components. Using the pref pane, start MySQL. In the Sharing System Pref, turn on (or if it was already on, turn off/on) Web Sharing. You should now have Apache/PHP/MySQL running. In 10.4 and 10.5 it was necessary to modify the php.ini file to point to the correct location of mysql.sock. There are reports that this is fixed in 10.6, but that doesn't appear to be the case for all of us, given some of the comments below.
To complete your setup or MySQL: ``` sudo vim /etc/profile ``` 1. Add alias ``` alias mysql=/usr/local/mysql/bin/mysql alias mysqladmin=/usr/local/mysql/bin/mysqladmin ``` 2. Then set your root password ``` mysqladmin -u root password 'yourPassword' ``` 3. Then you can login with ``` mysql -u root -p ```
Easiest way to activate PHP and MySQL on Mac OS 10.6 (Snow Leopard), 10.7 (Lion), 10.8 (Mountain Lion)?
[ "", "php", "mysql", "macos", "osx-snow-leopard", "osx-lion", "" ]
I have a static class which calls a static Logger class, e.g ``` static class DoesStuffStatic { public static void DoStuff() { try { //something } catch(Exception e) { //do stuff; Logger.Log(e); } } } static class Logger { public static void Log(Exception e) { //do stuff here } } ``` How do I inject the Logger into my static class? Note: I've read [Dependency Injection in .NET with examples?](https://stackoverflow.com/questions/743951/help-with-dependency-injection-in-net), but this seems to use an instance logger.
You can't inject a static logger. You have to either change it to an instance logger (if you can), or wrap it in an instance logger (that will call the static). Also it is fairly hard to inject anything to a static class (because you don't control the static constructor in any way) - that's why I tend to pass all the objects I want to inject as parameters.
This is not necessarily so. As long as your static logger exposes a method for: * Injection of the classes you WANT injected, or * Injection of the DI Container in an appropriate method call prior to running it (say in something like the asp.net global.asax Application\_Start method), then you should be fine. Here's an example. Take the following class for DI: ``` public class Logger : ILogger { public void Log(string stringToLog) { Console.WriteLine(stringToLog); } } public interface ILogger { void Log(string stringToLog); } ``` And here's our static class which needs a logger: ``` public static class SomeStaticClass { private static IKernel _diContainer; private static ILogger _logger; public static void Init(IKernel dIcontainer) { _diContainer = dIcontainer; _logger = _diContainer.Get<ILogger>(); } public static void Log(string stringToLog) { _logger.Log(stringToLog); } } ``` Now, in a global startup for your app (in this case, in my global.asax.cs), you can instantiate your DI Container, then hand that off to your static class. ``` public class Global : Ninject.Web.NinjectHttpApplication { protected override IKernel CreateKernel() { return Container; } static IKernel Container { get { var standardKernel = new StandardKernel(); standardKernel.Bind<ILogger>().To<Logger>(); return standardKernel; } } void Application_Start(object sender, EventArgs e) { SomeStaticClass.Init(Container); SomeStaticClass.Log("Dependency Injection with Statics is totally possible"); } ``` And presto! You are now up and running with DI in your static classes. Hope that helps someone. I am re-working an application which uses a LOT of static classes, and we've been using this successfully for a while now.
Dependency injection with a static logger, static helper class
[ "", "c#", "unit-testing", "static", "dependency-injection", "" ]
This question is specific to using PHPUnit. PHPUnit automatically converts php errors to exceptions. **Is there a way to test the return value of a method that happens to trigger a php error (either built-in errors or user generated errors via *trigger\_error*)?** Example of code to test: ``` function load_file ($file) { if (! file_exists($file)) { trigger_error("file {$file} does not exist", E_USER_WARNING); return false; } return file_get_contents($file); } ``` This is the type of test I want to write: ``` public function testLoadFile () { $this->assertFalse(load_file('/some/non-existent/file')); } ``` The problem I am having is that the triggered error causes my unit test to fail (as it should). But if I try to catch it, or set an expected exception any code that after the error is triggered never executes so I have no way of testing the return value of the method. This example doesn't work: ``` public function testLoadFile () { $this->setExpectedException('Exception'); $result = load_file('/some/non-existent/file'); // code after this point never gets executed $this->assertFalse($result); } ``` Any ideas how I could achieve this?
There is no way to do this within one unit test. It is possible if you break up testing the return value, and the notice into two different tests. PHPUnit's error handler catches PHP errors and notices and converts them into Exceptions--which by definition stops program execution. The function you are testing never returns at all. You can, however, temporarily disable the conversion of errors into exceptions, even at runtime. This is probably easier with an example, so, here's what the two tests should look like: ``` public function testLoadFileTriggersErrorWhenFileNotFound() { $this->setExpectedException('PHPUnit_Framework_Error_Warning'); // Or whichever exception it is $result = load_file('/some/non-existent/file'); } public function testLoadFileRetunsFalseWhenFileNotFound() { PHPUnit_Framework_Error_Warning::$enabled = FALSE; $result = load_file('/some/non-existent/file'); $this->assertFalse($result); } ``` This also has the added bonus of making your tests clearer, cleaner and self documenting. **Re: Comment:** That's a great question, and I had no idea until I ran a couple of tests. It looks as if it will *not* restore the default/original value, at least as of PHPUnit 3.3.17 (the current stable release right now). So, I would actually amend the above to look like so: ``` public function testLoadFileRetunsFalseWhenFileNotFound() { $warningEnabledOrig = PHPUnit_Framework_Error_Warning::$enabled; PHPUnit_Framework_Error_Warning::$enabled = false; $result = load_file('/some/non-existent/file'); $this->assertFalse($result); PHPUnit_Framework_Error_Warning::$enabled = $warningEnabledOrig; } ``` **Re: Second Comment:** That's not completely true. I'm looking at PHPUnit's error handler, and it works as follows: * If it is an `E_WARNING`, use `PHPUnit_Framework_Error_Warning` as an exception class. * If it is an `E_NOTICE` or `E_STRICT` error, use `PHPUnit_Framework_Error_Notice` * Else, use `PHPUnit_Framework_Error` as the exception class. So, yes, errors of the `E_USER_*` are not turned into PHPUnit's \*\_Warning or \*\_Notice class, they are still transformed into a generic `PHPUnit_Framework_Error` exception. **Further Thoughts** While it depends exactly on how the function is used, I'd probably switch to throwing an actual exception instead of triggering an error, if it were me. Yes, this would change the logic flow of the method, and the code that uses the method... right now the execution does not stop when it cannot read a file. But that's up to you to decide whether the requested file not existing is truly *exceptional* behaviour. I tend to use exceptions way more than errors/warnings/notices, because they are easier to handle, test and work into your application flow. I usually reserve the notices for things like depreciated method calls, etc.
Use a `phpunit.xml` configuration file and disable the notice/warning/error to Exception conversion. More [details in the manual](http://www.phpunit.de/manual/current/en/appendixes.configuration.html). It's basically something like this: ``` <phpunit convertErrorsToExceptions="false" convertNoticesToExceptions="false" convertWarningsToExceptions="false"> </phpunit> ```
test the return value of a method that triggers an error with PHPUnit
[ "", "php", "unit-testing", "exception", "phpunit", "" ]
I know that `==` has some issues when comparing two `Strings`. It seems that `String.equals()` is a better approach. Well, I'm doing JUnit testing and my inclination is to use `assertEquals(str1, str2)`. Is this a reliable way to assert two Strings contain the same content? I would use `assertTrue(str1.equals(str2))`, but then you don't get the benefit of seeing what the expected and actual values are on failure. On a related note, does anyone have a link to a page or thread that plainly explains the problems with `str1 == str2`?
You should **always** use `.equals()` when comparing `Strings` in Java. JUnit calls the `.equals()` method to determine equality in the method `assertEquals(Object o1, Object o2)`. So, you are definitely safe using `assertEquals(string1, string2)`. (Because `String`s are `Object`s) [Here is a link to a great Stackoverflow question](https://stackoverflow.com/questions/1111296/when-s-is-false-but-equals-s-is-true) regarding some of the differences between `==` and `.equals()`.
`assertEquals` uses the `equals` method for comparison. There is a different assert, `assertSame`, which uses the `==` operator. To understand why `==` shouldn't be used with strings you need to understand what `==` does: it does an identity check. That is, `a == b` checks to see if `a` and `b` refer to the *same object*. It is built into the language, and its behavior cannot be changed by different classes. The `equals` method, on the other hand, can be overridden by classes. While its default behavior (in the `Object` class) is to do an identity check using the `==` operator, many classes, including `String`, override it to instead do an "equivalence" check. In the case of `String`, instead of checking if `a` and `b` refer to the same object, `a.equals(b)` checks to see if the objects they refer to are both strings that contain exactly the same characters. Analogy time: imagine that each `String` object is a piece of paper with something written on it. Let's say I have two pieces of paper with "Foo" written on them, and another with "Bar" written on it. If I take the first two pieces of paper and use `==` to compare them it will return `false` because it's essentially asking "are these the same piece of paper?". It doesn't need to even look at what's written on the paper. The fact that I'm giving it two pieces of paper (rather than the same one twice) means it will return `false`. If I use `equals`, however, the `equals` method will read the two pieces of paper and see that they say the same thing ("Foo"), and so it'll return `true`. The bit that gets confusing with Strings is that the Java has a concept of "interning" Strings, and this is (effectively) automatically performed on any string literals in your code. This means that if you have two equivalent string literals in your code (even if they're in different classes) they'll actually both refer to the same `String` object. This makes the `==` operator return `true` more often than one might expect.
Is Java's assertEquals method reliable?
[ "", "java", "string", "junit", "junit4", "" ]
I am looking for a way to Show/ Hide some of the Radio buttons of a Radio button group using JavaScript. How can this be achieved? Thanks
The *id* attribute identifies the individual radio buttons. All of them will be related to the group by the *name* attribute You can get the individual radio buttons using something like ``` var rbtn = document.getElementById('radioButton1'); ``` Then set the display or visibility style to hide or show. ``` rbtn.style.display = 'none'; // 'block' or 'inline' if you want to show. ```
``` document.getElementById('myRadioButtonId').style.display = 'none'; //hide it document.getElementById('myRadioButtonId').style.display = 'block'; //show it ```
Dynamically Show/Hide Radio buttons of a Radio button group using JavaScript
[ "", "javascript", "html", "" ]
What happens if we serialize a static class? Can more than one instance of the static class be created if we serialize it? ``` [Serializable] public static class MyClass { public static MyClass() { } public static bool IsTrue() { return true; } } ``` Suppose I XmlSerialize the object to a XML file, and at a later time I de-serialize back to a object. Another copy exists in the memory (created when somone instintiated the static calss for the first time). Will, there be two copy of the of the object? If yes, can we stop that? Does it apply to any class which follows the singleton pattern?
There are never *any* instances of static classes: they are both abstract and sealed in the IL, so the CLR will prevent any instances being created. Therefore there is nothing to serialize. Static fields are never serialized, and that's the only sort of state that a static class can have. Your question about XML serialization makes no sense, as no-one can ever have created an instance of the static class to start with.
You can't serialize `static` classes (or any class whatsoever) using built-in .NET serialization features. You can only serialize *instances* of classes.
Serialize a Static Class?
[ "", "c#", "serialization", "singleton", "" ]
I want to add a xml file to my Java ee project and use it in my code but when I address the file from src directory it does not understand my address and search for file in bin directory of tomcat. My project is using wicket framwork and JavaEE. does any one know how to address the file or where should I place the file to access is from project?
If your xml file is a resource that must be accessed server-side only, then the best choice is to place it in the WEB-INF directory inside your war, or in some subdirectory inside the WEB-INF. This way you ensure the resource will not be accessible by the web. Then you can retrieve it using [ServletContext.getResource](http://java.sun.com/j2ee/1.4/docs/api/javax/servlet/ServletContext.html#getResource(java.lang.String)), as pointed out by Peter D. For example, in a servlet you can retrieve it this way (exception handling omitted): ``` String path = "/WEB-INF/my.xml"; URL url = getServletConfig().getServletContext().getResource(path); InputStream in = url.openStream(); // read content from input stream... ```
Inside your servlet you can: ``` this.getServletContext().getResource( path ); public java.net.URL getResource(java.lang.String path) throws java.net.MalformedURLException ``` Returns a URL to the resource that is mapped to a specified path. The path must begin with a "/" and is interpreted as relative to the current context root. This method allows the servlet container to make a resource available to servlets from any source. Resources can be located on a local or remote file system, in a database, or in a .war file. The servlet container must implement the URL handlers and URLConnection objects that are necessary to access the resource. This method returns null if no resource is mapped to the pathname. Some containers may allow writing to the URL returned by this method using the methods of the URL class. The resource content is returned directly, so be aware that requesting a .jsp page returns the JSP source code. Use a RequestDispatcher instead to include results of an execution. This method has a different purpose than java.lang.Class.getResource, which looks up resources based on a class loader. This method does not use class loaders.
how to add a file to Java EE projects?
[ "", "java", "" ]
I'm developing an application using Visual C# Express Edition - what is the downside to using the express editions? Are there any limitations on what I can build and release? Will my users be able to tell I'm using the Express Edition?
It won't impact your users, other than by making *you* less productive by prohibiting add-ons such as [ReSharper](http://en.wikipedia.org/wiki/ReSharper), [TestDriven.NET](http://www.testdriven.net/), etc. and not having some of the built-in features of the commercial editions. To put it another way: if a word processor didn't have a spell checker, you could still make sure that your documents were spelled correctly, so readers wouldn't know - but it's a lot quicker (usually!) if the tool has it built in...
Here is a huge comparison chart of all versions of Visual Studio, from Express until Team System. [Visual Studio 2008 Product Comparison Guide](http://www.microsoft.com/downloads/details.aspx?FamilyId=727BCFB0-B575-47AB-9FD8-4EE067BB3A37&displaylang=en)
What is the downside to using the Visual Studio Express Editions?
[ "", "c#", "visual-studio", "" ]
I would like to set the Culture of a WPF application to a specific one based on user preferences. I can do this for the current thread via `Thread.CurrentThread.Current(UI)Culture`, but is there any way to do this globally for the application (so it affects all threads by default)?
there is no way to set it for all threads in the application, however if you are creating the threads in your application you can set the culture for everyone by yourself as you mentioned above To set the Culture to the Main Application use the following snippet code: ``` Dim newCulture As CultureInfo = new CultureInfo("fr-FR") CurrentThread.CurrentCulture = newCulture ```
Try putting ``` <UICulture>en-US</UICulture> ``` ... in your csproj file.
How can i globally set the Culture in a WPF Application?
[ "", "c#", ".net", "wpf", "xaml", "localization", "" ]
I have to make a loop to generate a 5 randomly-picked-letter string, and then create a text file under that name, lets say in C:// , how will I do that? Both the generating name and creating a file in the directory. I think I have to pick 5 random numbers from the ascii codes add them to an array and then convert them to the character equivalents to be able to use it as a name. Idk how I'll convert them to character and make up a string with them, could you help me?
If you want to create the file names youself, put the characters that you want to use in a string and pick from that: ``` // selected characters string chars = "2346789ABCDEFGHJKLMNPQRTUVWXYZabcdefghjkmnpqrtuvwxyz"; // create random generator Random rnd = new Random(); string name; do { // create name name = string.Empty; while (name.Length < 5) { name += chars.Substring(rnd.Next(chars.Length), 1); } // add extension name += ".txt"; // check against files in the folder } while (File.Exists(Path.Compbine(folderPath, name))) ```
Look at the GetTempFileName and GetRandomFileName methods of the [System.IO.Path](http://msdn.microsoft.com/en-us/library/system.io.path.aspx) class. * [GetRandomFileName](http://msdn.microsoft.com/en-us/library/system.io.path.getrandomfilename.aspx) creates a "cryptographically strong" file name, and is the closer one to what you asked for. * [GetTempFileName](http://msdn.microsoft.com/en-us/library/system.io.path.gettempfilename.aspx) creates a unique file name in a directory -- and also creates a zero-byte file with that name too -- helping ensure its uniqueness. This might be closer to what you might actually need.
How to generate a random named text file in C#?
[ "", "c#", "ascii", "random", "text-files", "" ]
Oracle doesn't support the TIME datatype, but you can use DATE to store a TIME. My problem: ``` select to_date('2009-06-30', 'YYYY-MM-DD') as "DATE", to_date('16:31:59', 'HH24:MI:SS') as "TIME" from dual ``` yields: ``` DATE TIME 2009-06-30 2009-08-01 ``` when I run it through JDBC (in SQuirrel SQL, in fact). "2009-08-01" isn't a very useful time. In my code, I can use `ResultSet.getTime()`. But how can I get the time in a generic query? Is there a way to cast the result?
Oracle does not have a "Time" datatype. It has a DATE, which is the date and time accurate to the second. It also has a Timestamp with greater accuracy. When you perform a to\_date() call, you get back a...DATE! Depending upon how you have your NLS settings established you can have the text for that date show however you want. The NLS settings control things like date formats, timestamp formats, currency characters, decimal separators, etc. Obviously your NLS settings are defined to show the DATE data as yyyy-mm-dd. If you're trying to do generic JDBC stuff with Oracle DATEs, you need to specify a "static" value for the "day" portion of the date, and then specify the time as well. Consider this example: ``` String sql = "Select to_date('1970-01-01 ' || ? ,'YYYY-MM-DD HH24:MI:SS) as MY_TIME from dual"; Connection conn = null; //get Connection from somewhere PreparedStatement stmt = conn.prepareStatement(sql); stmt.setString(1, "16:31:59"); ResultSet rs = stmt.executeQuery(); rs.next(); //get to first element of result set; java.sql.Time myTime = rs.getTime(1); ``` The result of myTime will be a java.sql.Time value containing the value for 16:31:59. Remember to keep the day portion some constant value (like the 1970-01-01 above) so that queries with the Time in the where clause will work properly.
The DATE type is stored as a fractional value -- the date as the integer portion, and the time of day as the fractional portion. So, every DATE has the time, which you can extract with something like this. ``` select TO_CHAR(sysdate, 'DD-MON-YYYY HH24:MI:SS') from dual; ```
How to convert Oracle "TIME" to JDBC Time in query?
[ "", "sql", "oracle", "date", "jdbc", "time", "" ]
I need to perform some action in wordpress admin panel programmatically but can't manage how to login to Wordpress using C# and HttpWebRequest. Here is what I do: ``` private void button1_Click(object sender, EventArgs e) { string url = "http://localhost/wordpress/wp-login.php"; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url); CookieContainer cookies = new CookieContainer(); SetupRequest(url, request, cookies); //request.Accept = "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8"; //request.Headers["Accept-Language"] = "uk,ru;q=0.8,en-us;q=0.5,en;q=0.3"; //request.Headers["Accept-Encoding"] = "gzip,deflate"; //request.Headers["Accept-Charset"] = "windows-1251,utf-8;q=0.7,*;q=0.7"; string user = "test"; string pwd = "test"; request.Credentials = new NetworkCredential(user, pwd); string data = string.Format( "log={0}&pwd={1}&wp-submit={2}&testcookie=1&redirect_to={3}", user, pwd, System.Web.HttpUtility.UrlEncode("Log In"), System.Web.HttpUtility.UrlEncode("http://localhost/wordpress/wp-admin/")); SetRequestData(request, data); ShowResponse(request); } private static void SetupRequest(string url, HttpWebRequest request, CookieContainer cookies) { request.CookieContainer = cookies; request.UserAgent = "Mozilla/5.0 (Windows; U; Windows NT 6.0; uk; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)"; request.KeepAlive = true; request.Timeout = 120000; request.Method = "POST"; request.Referer = url; request.ContentType = "application/x-www-form-urlencoded"; } private void ShowResponse(HttpWebRequest request) { HttpWebResponse response = (HttpWebResponse)request.GetResponse(); responseTextBox.Text = (((HttpWebResponse)response).StatusDescription); responseTextBox.Text += "\r\n"; StreamReader reader = new StreamReader(response.GetResponseStream()); responseTextBox.Text += reader.ReadToEnd(); } private static void SetRequestData(HttpWebRequest request, string data) { byte[] streamData = Encoding.ASCII.GetBytes(data); request.ContentLength = streamData.Length; Stream dataStream = request.GetRequestStream(); dataStream.Write(streamData, 0, streamData.Length); dataStream.Close(); } ``` But unfortunately in responce I get only HTML source code of login page and it seems that cookies don't contain session ID. All requests which I perform after that code also return HTML source of login page so I can assume that it does not login correctly. Can anybody help me to solve that problem or give working example? --- Main thing which I want to achieve is scanning for new images in Nextgen Gallery plugin for Wordpress. Is there XML-RPC way of doing that? Thanks in advance.
Thanks to everyone. I managed how to make it work only when using sockets. Wordpress sends several **Set-Cookie** headers but `HttpWebRequest` handles only one instance of such header so some cookies are lost. When using sockets I can get all needed cookies and login to admin panel.
Since WordPress implement a redirect, leaving the page (redirecting) prevents the webrequest from getting the proper cookie. in order to get the relevant cookie, one must prevent redirects. ``` request.AllowAutoRedirect = false; ``` than use the cookie-conatainer for login. see the following code: (based on an example from Albahari's C# book) ``` string loginUri = "http://www.someaddress.com/wp-login.php"; string username = "username"; string password = "pass"; string reqString = "log=" + username + "&pwd=" + password; byte[] requestData = Encoding.UTF8.GetBytes(reqString); CookieContainer cc = new CookieContainer(); var request = (HttpWebRequest)WebRequest.Create(loginUri); request.Proxy = null; request.AllowAutoRedirect = false; request.CookieContainer = cc; request.Method = "post"; request.ContentType = "application/x-www-form-urlencoded"; request.ContentLength = requestData.Length; using (Stream s = request.GetRequestStream()) s.Write(requestData, 0, requestData.Length); using (HttpWebResponse response = (HttpWebResponse)request.GetResponse()) { foreach (Cookie c in response.Cookies) Console.WriteLine(c.Name + " = " + c.Value); } string newloginUri = "http://www.someaddress.com/private/"; HttpWebRequest newrequest = (HttpWebRequest)WebRequest.Create(newloginUri); newrequest.Proxy = null; newrequest.CookieContainer = cc; using (HttpWebResponse newresponse = (HttpWebResponse)newrequest.GetResponse()) using (Stream resSteam = newresponse.GetResponseStream()) using (StreamReader sr = new StreamReader(resSteam)) File.WriteAllText("private.html", sr.ReadToEnd()); System.Diagnostics.Process.Start("private.html"); ```
How to login to wordpress programmatically?
[ "", "c#", "wordpress", "httpwebrequest", "httpwebresponse", "" ]
Is it possible to define a C/C++ macro "`BUILD(a, i)`" which expands to "`x[0], x[1], x[2], ..., x[i]`" ? Like in ``` #define BUILD(x, 0) x[0] #define BUILD(x, 1) x[0], x[1] #define BUILD(x, 2) x[0], x[1], x[2] ... ``` It seems BOOST\_PP\_ENUM\_PARAMS could do the job. I suppose I could just #include boost, but I'm interested in knowing how and why it works, anyone can explain? I would like to call a function `f(int, ...)` which takes N int arguments `x[i]`, 0 <= i < N. Where N is known to be `ceil(sizeof(A) / sizeof(B))`. So unfortunately, I cannot use varargs or templates.
It is possible, but you have to do some manual work and have an upper limit. ``` #define BUILD0(x) x[0] #define BUILD1(x) BUILD0(x), x[1] #define BUILD2(x) BUILD1(x), x[2] #define BUILD3(x) BUILD2(x), x[3] #define BUILD(x, i) BUILD##i(x) ``` And note that `i` should be an integer literal, not a constant computed value. BTW, the preprocessor is more powerful than what is usually though, but the use of that power is quite tricky. Boost provides a library which eases some things, including iteration. See [Boost Preprocessor Library](http://www.boost.org/doc/libs/1_39_0/libs/preprocessor/doc/index.html). There is another library for such things, but its name escapes me at the moment. Edit: The boost preprocessor library uses a similar technique. With additional tricks to solve some corner cases problems, share implementation macros between higher level facilities, work around compiler bugs, etc... the usual boost complexity which is normal in the context of a general purpose library but which at times prevents easy understanding of the implementation principles. Probably the most noticeable trick is to add an indirection level so that if the second parameter can be a macro, it is expanded. I.e. with ``` #define BUILD_(x, i) BUILD##i(x) #define BUILD(x, i) BUILD_(x, i) ``` one can make the call ``` #define FOO 42 BUILD(x, FOO) ``` which isn't possible with what I exposed.
No, it isn't - macros cannot be recursive. And the macros you posted are not variadic, which means "having different numbers of parameters".
Macro recursive expansion to a sequence
[ "", "c++", "c-preprocessor", "" ]
I'd like to know how to get hold of the kind of Operating System the jvm is running on. It has to be "secure" as well, so `System.getProperty("os.name")` is not really an option because it can be trivially circumvented with the -D directive. By "secure" I mean nontrivial to circumvent. It's for a desktop application. The user could always deobfuscate, decompile, edit and recompile the code, but that is significantly harder than passing -D to the jvm. We want to make tinkering nontrivial, not impossible (since that can't be done).
First, it's impossible to protect code from being manipulated arbitrarily by its runtime environment. But in order to make it at least hard to fool your check, the best bet is probably some sort of file system based [OS fingerprinting](http://en.wikipedia.org/wiki/TCP/IP_stack_fingerprinting). [File.listRoots()](http://java.sun.com/javase/6/docs/api/java/io/File.html#listRoots()) is your starting point; on a Unix-like system it will return a single root containing characteristic directories like /etc, /usr, etc. On Windows, it will return multiple results, but AFAIK the OS installation drive is not necessarily C: and the characteristic directories differ across Windows versions and locales - be careful not to assume that everyone runs an English version of Vista. You could invest a lot of work into recognizing different versions of Windows and Linux, as well as BSD or MacOS - and it would probably take a lot less work to remove the check from the compiled code once it's out there.
The system properties are the only way that I know of to obtain operating system information. Even the OperatingSystemMXBean takes its values from the os.X system properties. If someone can tinker with how your application is launched, you have bigger problems than if os.name is correct. However, if you're worried about malicious code setting that property while your application is running, you can use the Java Security Manager to ensure that the properties are guarded safely.
Name of the Operating System in java (not "os.name")
[ "", "java", "operating-system", "jvm", "runtime.exec", "" ]
I have class(Customer) which holds more than 200 string variables as property. I'm using method with parameter of key and value. I trying to supply key and value from xml file. For this, value has to be substituted by Customer class's property(string variables). ie ``` Customer { public string Name{return _name}; public string Address{return _address}; } CallInput { StringTempelate tempelate = new StringTempelate(); foreach(item in items) tempelate .SetAttribure(item.key, item.Value --> //Say this value is Name, so it has to substitute Customer.Name } ``` is it possible?
You can use reflection to set the properties 'by name'. ``` using System.Reflection; ... myCustomer.GetType().GetProperty(item.Key).SetValue(myCustomer, item.Value, null); ``` You can also read the properties with GetValue, or get a list of all property names using GetType().GetProperties(), which returns an array of PropertyInfo (the Name property contains the properties name)
Well, you can use [`Type.GetProperty(name)`](http://msdn.microsoft.com/en-us/library/system.type.getproperty.aspx) to get a [`PropertyInfo`](http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.aspx), then call [`GetValue`](http://msdn.microsoft.com/en-us/library/system.reflection.propertyinfo.getvalue.aspx). For example: ``` // There may already be a field for this somewhere in the framework... private static readonly object[] EmptyArray = new object[0]; ... PropertyInfo prop = typeof(Customer).GetProperty(item.key); if (prop == null) { // Eek! Throw an exception or whatever... // You might also want to check the property type // and that it's readable } string value = (string) prop.GetValue(customer, EmptyArray); template.SetTemplateAttribute(item.key, value); ``` Note that if you do this a lot you may want to convert the properties into `Func<Customer, string>` delegate instances - that will be *much* faster, but more complicated. See my blog post about [creating delegates via reflection](https://codeblog.jonskeet.uk/2008/08/09/making-reflection-fly-and-exploring-delegates) for more information.
string to variable name
[ "", "c#", "" ]
How do I save MailMessage object to the disk? The MailMessage object does not expose any Save() methods. I dont have a problem if it saves in any format, \*.eml or \*.msg. Any idea how to do this?
For simplicity, I'll just quote an explanation from a [Connect item](http://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=94725): > You can actually configure the > SmtpClient to send emails to the file > system instead of the network. You can > do this programmatically using the > following code: > > ``` > SmtpClient client = new SmtpClient("mysmtphost"); > client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory; > client.PickupDirectoryLocation = @"C:\somedirectory"; > client.Send(message); > ``` > > You can also set this up in your > application configuration file like > this: ``` <configuration> <system.net> <mailSettings> <smtp deliveryMethod="SpecifiedPickupDirectory"> <specifiedPickupDirectory pickupDirectoryLocation="C:\somedirectory" /> </smtp> </mailSettings> </system.net> </configuration> ``` > After sending the email, you should > see email files get added to the > directory you specified. You can then > have a separate process send out the > email messages in batch mode. You should be able to use the empty constructor instead of the one listed, as it won't be sending it anyway.
Here's an extension method to convert a MailMessage to a stream containing the EML data. Its obviously a bit of a hack as it uses the file system, but it works. ``` public static void SaveMailMessage(this MailMessage msg, string filePath) { using (var fs = new FileStream(filePath, FileMode.Create)) { msg.ToEMLStream(fs); } } /// <summary> /// Converts a MailMessage to an EML file stream. /// </summary> /// <param name="msg"></param> /// <returns></returns> public static void ToEMLStream(this MailMessage msg, Stream str) { using (var client = new SmtpClient()) { var id = Guid.NewGuid(); var tempFolder = Path.Combine(Path.GetTempPath(), Assembly.GetExecutingAssembly().GetName().Name); tempFolder = Path.Combine(tempFolder, "MailMessageToEMLTemp"); // create a temp folder to hold just this .eml file so that we can find it easily. tempFolder = Path.Combine(tempFolder, id.ToString()); if (!Directory.Exists(tempFolder)) { Directory.CreateDirectory(tempFolder); } client.UseDefaultCredentials = true; client.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory; client.PickupDirectoryLocation = tempFolder; client.Send(msg); // tempFolder should contain 1 eml file var filePath = Directory.GetFiles(tempFolder).Single(); // stream out the contents using (var fs = new FileStream(filePath, FileMode.Open)) { fs.CopyTo(str); } if (Directory.Exists(tempFolder)) { Directory.Delete(tempFolder, true); } } } ``` You can then take the stream thats returned and do as you want with it, including saving to another location on disk or storing in a database field, or even emailing as an attachment.
How to save MailMessage object to disk as *.eml or *.msg file
[ "", "c#", ".net", "email", "mailmessage", "eml", "" ]
I have an application which has been running happily under Java 1.5 for around a year. We've just had the boxes updated and had Java 1.6 installed. After deploying the app to the new server we've found the application is throwing an exception when it tries to transform some XML. We couldn't understand why this was happening until we deployed it locally and the same happened. After changing the SDK to v1.5 the problem stopped and the application runs fine. Here's the method's source: ``` import java.io.StringWriter; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.Transformer; import javax.xml.transform.TransformerConfigurationException; import javax.xml.transform.TransformerException; import javax.xml.transform.TransformerFactory; import javax.xml.transform.dom.DOMSource; import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Element; import org.w3c.dom.Node; public static String xmlToString(Node node) { try { Source source = new DOMSource(node); StringWriter stringWriter = new StringWriter(); Result result = new StreamResult(stringWriter); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.transform(source, result); return stringWriter.getBuffer().toString(); } catch (TransformerConfigurationException e) { e.printStackTrace(); } catch (TransformerException e) { e.printStackTrace(); } return null; } ``` It's crashing on the "transformer.transform(source, result);" line with exception: ``` Exception in thread "main" java.lang.AbstractMethodError: org.apache.xerces.dom.DocumentImpl.getXmlStandalone()Z at com.sun.org.apache.xalan.internal.xsltc.trax.DOM2TO.setDocumentInfo(DOM2TO.java:373) at com.sun.org.apache.xalan.internal.xsltc.trax.DOM2TO.parse(DOM2TO.java:127) at com.sun.org.apache.xalan.internal.xsltc.trax.DOM2TO.parse(DOM2TO.java:94) at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transformIdentity(TransformerImpl.java:662) at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:708) at com.sun.org.apache.xalan.internal.xsltc.trax.TransformerImpl.transform(TransformerImpl.java:313) ``` Does anyone know of any changes made to Java between the two versions which would cause this? What would be the easiest fix? Thanks for your help.
I don't remember if it was between 1.4 and 1.5 or 1.5 and 1.6, but the Xalan libraries that shipped with the JVM from Sun changed their package name. I ran into something similar about 2 years ago. I think what I had to do was explicitly ship my own xalan implementation to fix the problem. UPDATE: This might have been what I was thinking of, though it still could be related to your problem [link text](http://blog.andrewbeacock.com/2006/12/xalan-classes-go-missing-once-java-is.html)
This problem is known to occur on JDK 1.6 with an older xerces.jar which, when on classpath, provides its own DocumentBuilderFactory. The problem does not occur when using the platform default factory. You may want to check your WEB-INF/lib or equivalent.
Java method works in 1.5 but not 1.6
[ "", "java", "xml", "incompatibility", "java-6", "java-5", "" ]
Is this how PHP implemented random number generating? Say I want to calculate a yes or a no. Everytime I have a certain probability percentage (say: 0,05% for this example). I do: ``` $possibilities = 100 / $probabilityPercentage; //$possibilities = 2000 $yes = rand(1,$possibilities); $yesCheck = $possiblities; //OPTION 1 $yesCheck = rand(1,$possibilities); //OPTION 2 ($yesCheck == $yes) ? return true : return false; ``` **Does it give the same results with either option?**
Let the data speak for itself. Code ``` vinko@parrot:~$ more rand.php <?php $randrandsum = 0; $randconstsum = 0; $count = 20; for ($j = 0; $j < $count; $j++) { $randrand = 0; $randconst = 0; for ($i = 0; $i < 10000000; $i++ ){ $a = rand(1,1000); $b = rand(1,1000); if ($a == $b) $randrand++; } for ($i = 0; $i < 10000000; $i++ ){ $a = rand(1,1000); $c = 1000; if ($c == $a) $randconst++; } $randrandsum += $randrand; $randconstsum += $randconst; print ($j+1)." RAND-RAND: $randrand RAND-CONST: $randconst\n"; } print "AVG RAND-RAND: ".($randrandsum/$count); print " AVG RAND-CONST: ".($randconstsum/$count)."\n"; ?> ``` Test run ``` vinko@parrot:~$ php rand.php 1 RAND-RAND: 10043 RAND-CONST: 10018 2 RAND-RAND: 9940 RAND-CONST: 10132 3 RAND-RAND: 9879 RAND-CONST: 10042 4 RAND-RAND: 9878 RAND-CONST: 9965 5 RAND-RAND: 10226 RAND-CONST: 9867 6 RAND-RAND: 9866 RAND-CONST: 9992 7 RAND-RAND: 10069 RAND-CONST: 9953 8 RAND-RAND: 9967 RAND-CONST: 9862 9 RAND-RAND: 10009 RAND-CONST: 10060 10 RAND-RAND: 9809 RAND-CONST: 9985 11 RAND-RAND: 9939 RAND-CONST: 10057 12 RAND-RAND: 9945 RAND-CONST: 10013 13 RAND-RAND: 10090 RAND-CONST: 9936 14 RAND-RAND: 10000 RAND-CONST: 9867 15 RAND-RAND: 10055 RAND-CONST: 10088 16 RAND-RAND: 10129 RAND-CONST: 9875 17 RAND-RAND: 9846 RAND-CONST: 10056 18 RAND-RAND: 9961 RAND-CONST: 9930 19 RAND-RAND: 10063 RAND-CONST: 10001 20 RAND-RAND: 10047 RAND-CONST: 10037 AVG RAND-RAND: 9988.05 AVG RAND-CONST: 9986.8 ``` Given the above results I'd say that for all practical purposes, both options are equivalent, giving the expected 1/1000 result on both cases.
Yes, rand(1,1000) = 1000 is just as probable as rand(1,1000) = rand(1,1000). Imagine rolling two dices. After you rolled the first one, what is the probability the second one will equal the first when rolled? 1/6. Now write down a number between 1 and 6 and roll a dice. What is the probability the dice will equal what you have just written? 1/6.
PHP - Is rand(1,1000) = 1000 as probable as rand(1,1000) = rand(1,1000)?
[ "", "php", "random", "" ]
1. Create a new ASP.NET MVC Web Application 2. Create an ASP.NET App\_Code Folder 3. Inside the new folder, create a class with an Extension Method. For example: ``` static public class BugMVCExtension { public static int ToInt(this string str) { return Convert.ToInt32(str); } } ``` 4. Choose a View and try to use this new Extension Method You will get this Exception: ``` CS0121: The call is ambiguous between the following methods or properties: '*MvcApplication1.App_code.BugMVCExtentions.ToInt(string)*' and '*MvcApplication1.App_code.BugMVCExtentions.ToInt(string)*' ``` Anyone here has more information about it? Is it wrong to create an App\_code in an ASP.NET MVC(?) Web Applications?
MVC projects created in Visual Studio use Web application project model by default. `App_Code` is mostly used by Web site model. I suggest reading about differences between them ([another question covers this](https://stackoverflow.com/questions/398037/asp-net-web-site-or-web-application) and it's also covered extensively on MSDN). If you add a source file to `App_Code` in a Web application project, Visual Studio will compile it to a DLL (since it's included in the project) and puts it in `/bin`. At run time, the ASP.NET compiler sees `App_Code` and tries to compile the source in a different assembly. As a consequence, two separate classes with identical names will exist in two different assemblies and when the ASP.NET parser tries to compile the `.aspx` file, it'll fail to choose one. ### Update: Are those two (extension method and the class you're instantiating) in a single .cs file? Otherwise, probably, the class you're instantiating is in a source file with **Build Action** (right click on file, click properties) set to **Content** which tells Visual Studio to skip it in the build process (in that case, you won't be able to reference it in other .cs files that are outside `App_Code` but you'll be able to use it in the view since it'll only come to life at run time.) If the build action is **Compile**, you'll get an error. The issue is definitely not specific to extension methods. Visual Studio seems to be smart enough to set it to Content by default for source files added to `App_Code`.
Do not use the app\_code folder. Use any other folder name. IE. appCode or ApplicationsCode. The name in the folder implies some compilation at runtime that leads to have duplicated code.
The call is ambiguous between the following methods or properties (bug??)
[ "", "c#", ".net", "asp.net-mvc", ".net-3.5", "" ]
I have these two methods for thread-exclusive access to a `CMyBuffer` object: Header: ``` class CSomeClass { //... public: CMyBuffer & LockBuffer(); void ReleaseBuffer(); private: CMyBuffer m_buffer; CCriticalSection m_bufferLock; //... } ``` Implementation: ``` CMyBuffer & CSomeClass::LockBuffer() { m_bufferLock.Lock(); return m_buffer; } void CSomeClass::ReleaseBuffer() { m_bufferLock.Unlock(); } ``` Usage: ``` void someFunction(CSomeClass & sc) { CMyBuffer & buffer = sc.LockBuffer(); // access buffer sc.ReleaseBuffer(); } ``` * What I like about this is, that the user has to make only one function call and can only access the buffer after having locked it. * What I don't like is that the user has to release explicitly. **Update**: These additional disadvantages were pointed out by Nick Meyer and Martin York: * The user is able to release the lock and then use the buffer. * If an exception occurs before releasing the lock, the buffer remains locked. I'd like to do it with a `CSingleLock` object (or something similar), which unlocks the buffer when the object goes out of scope. How could that be done?
Use an object that represents the buffer. When this obejct is initialized get the lock and when it is destroyed release the lock. Add a cast operator so it can be used in place of the buffer in any function call: ``` #include <iostream> // Added to just get it to compile struct CMyBuffer { void doStuff() {std::cout << "Stuff\n";}}; struct CCriticalSection { void Lock() {} void Unlock() {} }; class CSomeClass { private: CMyBuffer m_buffer; CCriticalSection m_bufferLock; // Note the friendship. friend class CSomeClassBufRef; }; // The interesting class. class CSomeClassBufRef { public: CSomeClassBufRef(CSomeClass& parent) :m_owned(parent) { // Lock on construction m_owned.m_bufferLock.Lock(); } ~CSomeClassBufRef() { // Unlock on destruction m_owned.m_bufferLock.Unlock(); } operator CMyBuffer&() { // When this object needs to be used as a CMyBuffer cast it. return m_owned.m_buffer; } private: CSomeClass& m_owned; }; void doStuff(CMyBuffer& buf) { buf.doStuff(); } int main() { CSomeClass s; // Get a reference to the buffer and auto lock. CSomeClassBufRef b(s); // This call auto casts into CMyBuffer doStuff(b); // But you can explicitly cast into CMyBuffer if you need. static_cast<CMyBuffer&>(b).doStuff(); } ```
One way to do this would be using [RAII](http://en.wikipedia.org/wiki/Resource_Acquisition_Is_Initialization): ``` class CMyBuffer { public: void Lock() { m_bufferLock.Lock(); } void Unlock() { m_bufferLock.Unlock(); } private: CCriticalSection m_bufferLock; }; class LockedBuffer { public: LockedBuffer(CMyBuffer& myBuffer) : m_myBuffer(myBuffer) { m_myBuffer.Lock(); } ~LockedBuffer() { m_myBuffer.Unlock(); } CMyBuffer& getBuffer() { return m_myBuffer; } private: CMyBuffer& m_myBuffer; }; class CSomeClass { //... public: LockedBuffer getBuffer(); private: CMyBuffer m_buffer; }; LockedBuffer CSomeClass::getBuffer() { return LockedBuffer(m_buffer); } void someFunction(CSomeClass & sc) { LockedBuffer lb = sc.getBuffer(); CMyBuffer& buffer = lb.getBuffer(); //Use the buffer, when lb object goes out of scope buffer lock is released } ```
How can I provide access to this buffer with CSingleLock?
[ "", "c++", "multithreading", "mfc", "locking", "buffer", "" ]
> **Possible Duplicates:** > [Why would a sql query have “where 1 = 1”](https://stackoverflow.com/questions/517107/why-would-a-sql-query-have-where-1-1) > [Why would someone use WHERE 1=1 AND <conditions> in a SQL clause?](https://stackoverflow.com/questions/242822/why-would-someone-use-where-11-and-conditions-in-a-sql-clause) I've seen that a lot in different query examples and it goes to probably all SQL engines. If there is a query that has no conditions defined people (and specially ORM frameworks) often add always-true condition `WHERE 1 = 1` or something like that. So instead of ``` SELECT id, name FROM users; ``` they use ``` SELECT id, name FROM users WHERE 1 = 1; ``` The only possible reason I could think of if you are adding conditions dynamically you don't have to worry about stripping the initial `AND` but still quite often this `1 = 1` condition is stripped if there is an actual condition in the query. Actual example from CakePHP (generated by framework): (no conditions) ``` SELECT `User`.`id`, `User`.`login` FROM `users` AS `User` WHERE 1 = 1 ORDER BY `User`.`id` ASC; ``` (with condition) ``` SELECT `User`.`id`, `User`.`login` FROM `users` AS `User` WHERE `User`.`login` = 'me@example.com' LIMIT 1; ``` Is there any reason for adding that extra condition?
Yeah, it's typically because it starts out as 'where 1 = 0', to force the statement to fail. It's a more naive way of wrapping it up in a transaction and not committing it at the end, to test your query. (This is the preferred method).
It's also a common practice when people are **building the sql query programmatically**, it's just easier to start with 'where 1=1 ' and then appending ' and customer.id=:custId' depending if a customer id is provided. So you can always append the next part of the query starting with 'and ...'.
What is the purpose of using WHERE 1=1 in SQL statements?
[ "", "sql", "conditional-statements", "where-clause", "" ]
I am using VSTS 2008 + C# + .Net 2.0 to develop a Windows Forms application. In the default Form1 I have a button, and click the button will invoke another Form -- Form2. My question is, I want to make Form2 always on the top, i.e. user must response Form2 (fill in informaiton in Form2 and close it) until the user could continue to deal with Form1. How to implement this feature? Here is my current code. ``` public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { Form2 form2 = new Form2(); form2.Visible = true; } } ```
The best option to do exactly what you want is to make form2 a dialog box. You do this by calling its ``` form2.ShowDialog() ``` method.
try this ``` this.TopMost = true; ```
how to make a Windows Form always display on the top?
[ "", "c#", ".net", "winforms", "visual-studio-2008", "" ]
Excuse my ignorance but I'm having a tough time figuring this out. I'm trying to take the result from one mysql command, and use it in another command. Here's my code, it doesnt work. ``` //select the event end date of event ID $sql = "SELECT enddate FROM mm_eventlist_dates WHERE id = $id"; $result = mysql_query($sql); //plug in the event end date, find event that starts the next day $sql = "SELECT id FROM mm_eventlist_dates WHERE startdate = date_add($result, INTERVAL 1 DAY)"; $result = mysql_query($sql); $row = mysql_fetch_array($result); echo "Next Event ID" . $row['id']; ``` I'm so lost. Please help! Thanks, Nick
If I understand what you're trying to accomplish, it looks like you want to find all the events that start the day after a given event. Correct? In that case, what you want to do is a self-join, that is, join a table to itself. You need to give at least one occurrence of the table an alias so SQL can tell them apart. So maybe something like this: ``` SELECT e2.id FROM mm_eventlist_dates e1 join mm_eventlist_dates e2 on e2.startdate = date_add(e1.enddate, INTERVAL 1 DAY) where e1.id=$id ```
Is there a reason that you can't combine them in to one query? ``` SELECT m1.id FROM mm_eventlist_dates m1 JOIN mm_eventlist_dates m2 ON m1.startdate = date_add(m2.enddate, INTERVAL 1 DAY) WHERE m2.id = $id ```
Use the result of one Mysql command in Another Mysql Command?
[ "", "php", "mysql", "" ]
Let's say I have base class `FooParent`, and it has a numerous amount of `FooChildren`. At runtime I must create an instance of one of the `FooChildren`. How would I do this? I realize I could create a huge map (and use delegates) or a huge `switch/case` statement, but that just seems a bit sloppy. In something like PHP, I can easily create a class dynamically like this: ``` $className="FooClass"; $myNewFooClass=new $className; //makes a new instance of FooClass ``` (you can also do this using reflection). Does .NET have anything like this? Is reflection an option, and does it have any performance penalties? If not, what other options do I have? The type of class will be determined by a JSON request. The variable could be anything I want..it could be an integer if I wanted to do an enum, or it could be the full class name. I haven't created it yet so I'm undecided.
You can do it with reflection if you really want, but there will be performance penalties. Whether they're significant or not will depend on your exact situation. Depending on exactly what you want to do, I'd quite possibly go with either a switch/case statement or a map, as you suggest. In particular, that would be useful if you need to pass different arguments to different constructors based on the type you're constructing - doing that via reflection would be a bit of a pain in that you'd already be special-casing different types. --- EDIT: Okay, so we now know that there will always be a parameterless constructor. In that case, your JSON could easily contain the class name without the namespace (if they're all in the same namespace) and your method could look something like this: ``` public FooParent CreateFoo(string name) { if (name == null) { throw new ArgumentNullException("name"); } string fullName = "Some.NameSpace." + name; // This is assuming that the type will be in the same assembly // as the call. If that's not the case, we can look at that later. Type type = Type.GetType(fullName); if (type == null) { throw new ArgumentException("No such type: " + type); } if (!typeof(FooParent).IsAssignableFrom(type)) { throw new ArgumentException("Type " + type + " is not compatible with FooParent."); } return (FooParent) Activator.CreateInstance(type); } ``` --- Where do you determine the name to use? If it's passed in somewhere, a switch statement can be very simple when reformatted away from the norm a little: ``` public FooParent CreateFoo(string name) { switch (name) { case "Foo1": return new Foo1(); case "Foo2": return new Foo2(); case "Foo3": return new Foo3(); case "Foo4": return new Foo4(); case "FooChild1": return new FooChild1(); default: throw new ArgumentException("Unknown Foo class: " + name); } } ``` Mind you, having just written that out I'm not sure it has any real benefit (other than performance) over using `Type.GetType(name)` and then `Activator.CreateInstance(type)`. How does the caller know the class name to pass in? Will that definitely be dynamic? Is there any chance you could use generics? The more you could tell us about the situation, the more helpful we could be.
As long as all your FooChildren have parameterless constructors, you can do this with reflection. ``` Activator.CreateInstance<FooChildType>(); ``` If you don't actually have a reference to the type, and all you have is a string with the name of the class, you can do: ``` Activator.CreateInstance("FooChildClassName", "Fully.Qualified.AssemblyName"); ``` There is a performance penalty with reflection, but I wouldn't get hung up about it if this turns out to be the simplest solution for you, and your performance is acceptable.
Dynamic class initialization in .NET
[ "", "c#", "reflection", "" ]
I have a check box that I want to accurately measure so I can position controls on a dialog correctly. I can easily measure the size of the text on the control - but I don't know the "official" way of calculating the size of the check box and the gap before (or after) the text.
I'm pretty sure the width of the checkbox is equal to ``` int x = GetSystemMetrics( SM_CXMENUCHECK ); int y = GetSystemMetrics( SM_CYMENUCHECK ); ``` You can then work out the area inside by subtracting the following ... ``` int xInner = GetSystemMetrics( SM_CXEDGE ); int yInner = GetSystemMetrics( SM_CYEDGE ); ``` I use that in my code and haven't had a problem thus far ...
Short answer: ![enter image description here](https://i.stack.imgur.com/VvZbE.png) # Long Version From MSDN [Layout Specifications: Win32](http://msdn.microsoft.com/en-us/library/windows/desktop/bb226818%28v=vs.85%29.aspx), we have the specifications of the dimensions of a checkbox. It is **12 dialog units** from the left edge of the control to the start of the text: ![enter image description here](https://i.stack.imgur.com/2OFfi.jpg) And a checkbox control is 10 dialog units tall: | Surfaces and Controls | Height (DLUs) | Width (DLUs) | | --- | --- | --- | | Check box | 10 | As wide as possible (usually to the margins) to accommodate localization requirements. | First we calculate the size of a horizontal and a vertical dialog unit: ``` const dluCheckBoxInternalSpacing = 12; //12 horizontal dlus const dluCheckboxHeight = 10; //10 vertical dlus Size dialogUnits = GetAveCharSize(dc); Integer checkboxSpacing = MulDiv(dluCheckboxSpacing, dialogUnits.Width, 4); Integer checkboxHeight = MulDiv(dluCheckboxHeight, dialogUnits.Height, 8); ``` Using the handy helper function: ``` Size GetAveCharSize(HDC dc) { /* How To Calculate Dialog Base Units with Non-System-Based Font http://support.microsoft.com/kb/125681 */ TEXTMETRIC tm; GetTextMetrics(dc, ref tm); String buffer = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; Size result; GetTextExtentPoint32(dc, buffer, 52, out result); result.Width = (result.X/26 + 1) / 2; //div uses trunc rounding; we want arithmetic rounding result.Height = tm.tmHeight; return result; } ``` Now that we know how many pixels (`checkboxSpacing`) to add, we calculate the label size as normal: ``` textRect = Rect(0,0,0,0); DrawText(dc, Caption, -1, textRect, DT_CALCRECT or DT_LEFT or DT_SINGLELINE); chkVerification.Width = checkboxSpacing+textRect.Right; chkVerification.Height = checkboxHeight; ``` ![enter image description here](https://i.stack.imgur.com/VvZbE.png) # Bonus Reading ## What's a dialog unit? A dialog is a unit of measure based on the user's preferred font size. A dialog unit is defined such that the *average character* is 4 dialog units wide by 8 dialog units high: [![enter image description here](https://i.stack.imgur.com/yRvvQ.png)](https://i.stack.imgur.com/yRvvQ.png) This means that dialog units: * change with selected font * changed with selected DPI setting * are not square > **Note**: Any code released into public domain. No attribution required.
How to get size of check and gap in check box?
[ "", "c++", "windows", "winapi", "checkbox", "" ]
I want to grab the docstring in my commandline application, but every time I call the builtin help() function, Python goes into interactive mode. How do I get the docstring of an object and **not** have Python grab focus?
Any docstring is available through the `.__doc__` property: ``` >>> print str.__doc__ ``` In python 3, you'll need parenthesis for printing: ``` >>> print(str.__doc__) ```
You can use `dir(`{insert class name here}`)` to get the contents of a class and then iterate over it, looking for methods or other stuff. This example looks in a class `Task`for methods starting with the name `cmd` and gets their docstring: ``` command_help = dict() for key in dir( Task ): if key.startswith( 'cmd' ): command_help[ key ] = getattr( Task, key ).__doc__ ```
Python Get Docstring Without Going into Interactive Mode
[ "", "python", "interactive", "" ]
I have this html code and want to use the text in the divs who are children to "divHiddenTexts" for a javascript slider and I want search engines be able to find the text. What I don't want is a penalty for hiding the text with CSS which is discussed in this question [SEO : Is h1 tag that’s hidden using display:none given prominence by Search engines ?](https://stackoverflow.com/questions/753951/seo-is-h1-tag-thats-hidden-using-displaynone-given-prominence-by-search-engin) **My question is:** Will I get penalised if I hide text with javascript instead? By adding the class "hidden" in a DOM ready function. I have read that search bots don't have javascript turned on so they will see the text without finding it "spam-like" right? ``` <div id="divHiddenTexts" class="hidden"> <div> Some text...bla bla bla </div> <div> Some other text...more blaha. </div> <div> Even more text... </div> </div> ```
Search engines are concerned about spamming. They have complex algorithms to detect various spamming techniques, such as stuffing a page with keywords which are then hidden by some means. In your case the content is a perfectly legitimate part of the page, which is then manipulated by JavaScript. Even if search engines were able to detect that the text was being concealed by scripting, it would still not come under the category of spamming, and would not be penalised. There's a lot of rubbish talked about this subject, much of it based on endlessly-recycled speculation by unknowledgeable people, usually traceable back to some article from seven or eight years ago that isn't even really relevant anymore (and was probably written by a spammer complaining about getting caught). The technique you are using is perfectly OK, and will not damage your site's ranking.
See Matt Cutts' video: [How not to hide text](http://www.youtube.com/watch?v=Wzu9mUJj9GU) Google is getting good at detecting things like hidden text. However, it's not necessarily going to have a negative impact. If you have a Javascript menu, for example, they can't penalise you for that since its a fair use of hiding/unhiding.
Will search engines penalise text hidden by javascript?
[ "", "javascript", "css", "seo", "" ]
For one of my projects I would like to use PHP to read an SWF file on the server and get the dimensions of the stage of the SWF. So, the SWF file is not yet embedded in the page. Does anybody know if this is possible and which route I should take?
Use [getimagesize()](http://www.php.net/getimagesize) , it works perfectly with swf files.
See this (SWF Header Parser Class - licensed under LGPL): <http://www.phpclasses.org/browse/package/1653.html> The website says this: > This class is meant to parse the > header of Shockwave Flash animation > files (.swf) to extract metadata > information like the width and height > of animation, compression status and > uncompressed size, frame rate and > total number of frames. > > This class parses Flash files using > only PHP code, so no special extension > is necessary. > > Supports both, compressed and > uncompressed SWF Flash movies
Get SWF file information using PHP (or javascript)
[ "", "php", "flash", "" ]
I am using Java NIO for my socket connections, and my protocol is text based, so I need to be able to convert Strings to ByteBuffers before writing them to the SocketChannel, and convert the incoming ByteBuffers back to Strings. Currently, I am using this code: ``` public static Charset charset = Charset.forName("UTF-8"); public static CharsetEncoder encoder = charset.newEncoder(); public static CharsetDecoder decoder = charset.newDecoder(); public static ByteBuffer str_to_bb(String msg){ try{ return encoder.encode(CharBuffer.wrap(msg)); }catch(Exception e){e.printStackTrace();} return null; } public static String bb_to_str(ByteBuffer buffer){ String data = ""; try{ int old_position = buffer.position(); data = decoder.decode(buffer).toString(); // reset buffer's position to its original so it is not altered: buffer.position(old_position); }catch (Exception e){ e.printStackTrace(); return ""; } return data; } ``` This works most of the time, but I question if this is the preferred (or simplest) way to do each direction of this conversion, or if there is another way to try. Occasionally, and seemingly at random, calls to `encode()` and `decode()` will throw a `java.lang.IllegalStateException: Current state = FLUSHED, new state = CODING_END` exception, or similar, even if I am using a new ByteBuffer object each time a conversion is done. Do I need to synchronize these methods? Any better way to convert between Strings and ByteBuffers? Thanks!
Check out the [`CharsetEncoder`](http://docs.oracle.com/javase/7/docs/api/java/nio/charset/CharsetEncoder.html) and [`CharsetDecoder`](http://docs.oracle.com/javase/7/docs/api/java/nio/charset/CharsetDecoder.html) API descriptions - You should follow a **specific sequence of method calls** to avoid this problem. For example, for `CharsetEncoder`: 1. Reset the encoder via the `reset` method, unless it has not been used before; 2. Invoke the `encode` method zero or more times, as long as additional input may be available, passing `false` for the endOfInput argument and filling the input buffer and flushing the output buffer between invocations; 3. Invoke the `encode` method one final time, passing `true` for the endOfInput argument; and then 4. Invoke the `flush` method so that the encoder can flush any internal state to the output buffer. By the way, this is the same approach I am using for NIO although some of my colleagues are converting each char directly to a byte in the knowledge they are only using ASCII, which I can imagine is probably faster.
Unless things have changed, you're better off with ``` public static ByteBuffer str_to_bb(String msg, Charset charset){ return ByteBuffer.wrap(msg.getBytes(charset)); } public static String bb_to_str(ByteBuffer buffer, Charset charset){ byte[] bytes; if(buffer.hasArray()) { bytes = buffer.array(); } else { bytes = new byte[buffer.remaining()]; buffer.get(bytes); } return new String(bytes, charset); } ``` Usually buffer.hasArray() will be either always true or always false depending on your use case. In practice, unless you really want it to work under any circumstances, it's safe to optimize away the branch you don't need.
Java: Converting String to and from ByteBuffer and associated problems
[ "", "java", "string", "character-encoding", "nio", "bytebuffer", "" ]
I'm using the OutputCache attribute to cache my action's html output at the server-side. Fine, it works, but now I have a situation where the content changes rarely, but when it does, it's critical for the user to see the new data the very next request. So, is there a way to abort the page cache duration programmatically?
Yes, it is possible using [HttpResponse.RemoveOutputCacheItem Method](http://msdn.microsoft.com/en-us/library/914c7ktw.aspx). Check this question: * [SO - How to programmatically clear outputcache for controller action method](https://stackoverflow.com/questions/1167890/how-to-programmatically-clear-outputcache-for-controller-action-method)
You could also use [HttpCachePolicy.AddValidationCallback()](http://msdn.microsoft.com/en-us/library/system.web.httpcachepolicy.addvalidationcallback.aspx). The general idea is that when the page is rendered and inserted into the cache, this callback is inserted along with the page. Upon page retrieval from the cache, the callback is invoked and makes the final determination as to whether the cached page is stale (and should be booted) or valid (and should be served). See the [AuthorizeAttribute source](http://aspnet.codeplex.com/SourceControl/changeset/view/22929#266447) for an example. If a page becoming stale is *really* rare, though, you may be better served by the RemoveOutputCacheItem() method as mentioned in the other response.
Abort OutputCache duration programmatically in asp.net mvc
[ "", "c#", "asp.net-mvc", "model-view-controller", "caching", "outputcache", "" ]
Is there a way in pylab to display the X and Y axis? I know using grid() will display them, but it comes with numerous other lines all given the same emphasis.
It sounds like your problem has been addressed in the new [Matplotlib 0.99](http://matplotlib.sourceforge.net/users/whats_new.html) with the Axis spine placement feature. Take a [look at the examples](http://matplotlib.sourceforge.net/examples/pylab_examples/spine_placement_demo.html#pylab-examples-spine-placement-demo).
If you are looking to name the axis you can using the label function: ``` import pylab pylab.xlabel("X") pylab.ylabel("Y") pylab.plot(range(10)) pylab.show() ``` Anyway, I'm pretty sure the x and y axis are automatically generated. [matplotlib axes documentation](http://matplotlib.sourceforge.net/api/pyplot_api.html#matplotlib.pyplot.axes) If you just want an empty plot then: ``` pylab.plot([None], [None]) ``` this will give you the x and y axis with both going from 0 to 1. Now if you would like to change the range of either of those then you can: ``` pylab.xlim(xmin=0, xmax=100) pylab.ylim(ymin=0, ymax=100) ``` hope that helps.
Displaying X and y axis in pylab
[ "", "python", "matplotlib", "" ]
If I have something like: ``` enum { kCP_AboutBox_IconViewID = 1, kCP_AboutBox_AppNameViewID = 2, kCP_AboutBox_VersionViewID = 3, kCP_AboutBox_DescriptionViewID = 4, kCP_AboutBox_CopyrightViewID = 5 }; ``` in my .cpp can it go in the .h? More so, what other lesser know things can you put in a .h besides class definitions, variables, etc, etc
A .h file is essentially just code which, at compile time, is placed above any .cpp (or .h file for that matter) that it's included in. Therefore you CAN just place any code from the .cpp file into the .h and it should compile fine. However it's the design which is important. Your code (e.g. your enum) SHOULD be placed in the .h file if you need to expose it to the code you're including the .h file. However if the enum is only specific to the code in your header's .cpp implementation, then you should encapsulate it just within the .cpp file.
Remember to use header include guards in headers like: ``` #ifndef header_name_h #define header_name_h ... #endif ``` This helps you to keep to the one definition rule when multiple headers include your header. **Update:** I have since found that the latest versions of Visual Studio *and* gcc both allow: ``` #pragma once ``` Also, Never Ever have: ``` using namespace <name>; ``` in a header as this can cause strange ambiguity problems.
Enums: Can they do in .h or must stay in .cpp?
[ "", "c++", "header", "" ]
I'm fundamentally sick of writing data access layers. I see it as a boring and pointless endeavour. I envisage a development environment where I can just create my Entities/Models and start building the application. The time taken to write the DAL, procedures, etc... just eats my enthusiasm for a project. What I want is a generic repository interface for my data. Something like: ``` public interface IRepository { //Get individual TEntity item by id TEntity GetItem<TIdentifier, TEntity>(TIdentifier id); //Get individual TEntity item by the expression TEntity GetItem<TIdentifier, TEntity, TArg>(Expression<Func<TArg, TEntity>> expression); //Get individual TEntity item by the expression TEntity GetItem<TIdentifier, TEntity, TArg1, TArg2>(Expression<Func<TArg1, TArg2, TEntity>> expression); //Get all TEntity items IList<TEntity> GetList<TEntity>(); //Get all TEntity items, filtered by the expression IList<TEntity> GetList<TEntity, TArg>(Expression<Func<TArg, IList<TEntity>>> expression); //Get all TEntity items, filtered by the expression IList<TEntity> GetList<TEntity, TArg1, TArg2>(Expression<Func<TArg1, TArg2, IList<TEntity>>> expression); TIdentifier CreateItem... bool UpdateItem... bool DeleteItem... } ``` I'm specifically interested in something that would work for * Azure Data Services * SQL Server * sqLite ...but the theory would apply to any data repository Has anyone come across a ready built solution or do I have to fix the problem by writing more data access layers than I ever wanted to shake a stick at. Note: I know about ORM's, I want something that removes the requirement to write any of the DAL or stored procs.
Take a look at NHibernate, Castle ActiveRecord, SubSonic, LinqToSql, ... You say you know about ORMs, but they do pretty much exactly what your question asks for, at least to the extent possible.
I know you said that you know about ORM's and don't want them, but could you deal with something where the data access methods you write are written in `LINQ`? I've found that I like writing `LINQ` statements over `SQL` statements. If you're open to this, I would check out Entity Framework, LINQ to SQL, [NHibernate](https://www.hibernate.org/343.html), etc. **Edit:** If you want to use Azure, check out this link: <http://social.msdn.microsoft.com/Forums/en-US/windowsazure/thread/74a0a57e-d979-48ed-b534-f449bac0f90d>
Automatic Data Access Layer
[ "", "c#", ".net", "data-access", "" ]
Are there any solutions that will convert all foreign characters to A-z equivalents? I have searched extensively on Google and could not find a solution or even a list of characters and equivalents. The reason is I want to display A-z only URLs, plus plenty of other trip ups when dealing with these characters.
You can use [iconv](http://www.php.net/manual/en/function.iconv.php), which has a special transliteration encoding. > When the string "//TRANSLIT" is appended to tocode, transliteration is activated. This means that when a character cannot be represented in the target character set, it can be approximated through one or several characters that look similar to the original character. -- <http://www.gnu.org/software/libiconv/documentation/libiconv/iconv_open.3.html> [See here](http://drupal.org/node/63924) for a complete example that matches your use case.
If you are using iconv then make sure your locale is set correctly before you try the transliteration, otherwise some characters will not be correctly transliterated ``` setlocale(LC_CTYPE, 'en_US.UTF8'); ```
PHP Transliteration
[ "", "php", "transliteration", "" ]
I have an application that allows you to send event data to a custom script. You simply lay out the command line arguments and assign what event data goes with what argument. The problem is that there is no real flexibility here. Every option you map out is going to be used, but not every option will necessarily have data. So when the application builds the string to send to the script, some of the arguments are blank and python's OptionParser errors out with "error: --someargument option requires an argument" Being that there are over 200 points of data, it's not like I can write separate scripts to handle each combination of possible arguments (it would take 2^200 scripts). Is there a way to handle empty arguments in python's optionparser?
Sorry, misunderstood the question with my first answer. You can accomplish the ability to have optional arguments to command line flags use the *callback* action type when you define an option. Use the following function as a call back (you will likely wish to tailor to your needs) and configure it for each of the flags that can optionally receive an argument: ``` import optparse def optional_arg(arg_default): def func(option,opt_str,value,parser): if parser.rargs and not parser.rargs[0].startswith('-'): val=parser.rargs[0] parser.rargs.pop(0) else: val=arg_default setattr(parser.values,option.dest,val) return func def main(args): parser=optparse.OptionParser() parser.add_option('--foo',action='callback',callback=optional_arg('empty'),dest='foo') parser.add_option('--file',action='store_true',default=False) return parser.parse_args(args) if __name__=='__main__': import sys print main(sys.argv) ``` Running from the command line you'll see this: ``` # python parser.py (<Values at 0x8e42d8: {'foo': None, 'file': False}>, []) # python parser.py --foo (<Values at 0x8e42d8: {'foo': 'empty', 'file': False}>, []) # python parser.py --foo bar (<Values at 0x8e42d8: {'foo': 'bar', 'file': False}>, []) ```
I don't think `optparse` can do this. [`argparse`](http://argparse.googlecode.com/) is a different (non-standard) module that can [handle situations like this](http://argparse.googlecode.com/svn/trunk/doc/argparse-vs-optparse.html#more-nargs-options) where the options have optional values. With `optparse` you have to either have to specify the option including it's value or leave out both.
Parsing empty options in Python
[ "", "python", "optparse", "optionparser", "" ]
I'm going to be generating API docs using Sandcastle - I couldn't find any guides on how to do this on there website. Does anyone have any quickstart guides they would recommend?
I'd suggest using [SHFB](http://www.codeplex.com/SHFB) (if you can), as it makes it really easier. SHFB comes with documentation, but you will be able to use it's common features without any tutorial.
I am also a strong support of [SHFB](http://shfb.codeplex.com/), so much so that in September 2010 I wrote a sizable article on Sandcastle and SHFB entitled [Taming Sandcastle: A .NET Programmer's Guide to Documenting Your Code](http://www.simple-talk.com/dotnet/.net-tools/taming-sandcastle-a-.net-programmers-guide-to-documenting-your-code/) wherein I describe usage tips and a lot of the potential pitfalls one is likely to encounter. In October 2010 I followed that up with a [one-page wall chart](http://www.red-gate.com/products/ants_performance_profiler/code_profiling_made_easy_sandcastlechart.htm?utm_source=simpletalk&utm_medium=email-reflector&utm_content=sandcastlechart&utm_campaign=antsperformanceprofiler) that summarizes the XML documentation comment lexicon for SHFB. From my research for the article, here is a complete list of other useful resources: * Eric Woodruff’s [Sandcastle Help File Builder Documentation](http://www.ewoodruff.us/shfbdocs/Index.aspx) (SHFB Creator) * C# Programming Guide: [Recommended Tags for Documentation Comments](http://msdn.microsoft.com/en-us/library/5ast78ax.aspx) (MSDN) * Wm. Eric Brunsen’s [XML Documentation Comments Guide](http://www.dynicity.com/Products/XMLDocComments.aspx) (Dynicity) * Anson Horton’s [XML Documentation in C#](http://cyrino.members.winisp.net/9112006/XMLDocs.doc) (Microsoft C# Compiler Program Manager)
Is there a good quick start guide for generating API docs with Sandcastle?
[ "", "c#", "documentation-generation", "sandcastle", "" ]
I'm using my Mac most time at work. At home there's my Windows computer, where I program with Visual Studio my .NET/C# stuff. **Because I want to program outside, it would be great to have an equivalent IDE for my Mac.** **Which software are the best solution in my case to have a similar workplace with the same functionality?** I prefer open source, but commercial software is okay too.
MonoDevelop from: <http://monodevelop.com/> There is no equivalent to Visual Studio. However, for writing C# on Mac or Linux, you can't get better than MonoDevelop. The Mac build is pre beta. [From the MonoDevelop site on Mac](http://monodevelop.com/Download/Mac_Preview): > The Mac OS X port of MonoDevelop is under active development and has not seen a stable release yet. Recent work described by Michael Hutchinson has focussed on improving the usability and stability of Monodevelop on the Mac. This work will be released in MonoDevelop 2.2. Right now it's not finished, and is very much an alpha.
The question is quite old so I feel like I need to give a more up to date response to this question. Based on MonoDevelop, the best IDE for building C# applications on the Mac, for pretty much any platform is <http://xamarin.com/>
Best equivalent VisualStudio IDE for Mac to program .NET/C#
[ "", "c#", ".net", "macos", "ide", "" ]
Is there a good (and hopefully free?) source library to use for PHP for creating and displaying reports? I would love one that would allow the user to view it in a nice format for saving and printing (like PDF?). Also I would prefer one that is just files, not one that needs to be installed on the server itself as some of the people I create sites for are on shared server hosts.
Don't know if you would call this reporting but I have found these gems over the years: * <http://pchart.sourceforge.net/> * <http://devzone.zend.com/article/4044-Dynamically-Generating-PDF-Files-with-PHP-and-Haru-> * <http://phppowerpoint.codeplex.com/> * <http://phpexcel.codeplex.com/> * <http://sourceforge.net/projects/phprtf/> * <http://www.phpconcept.net/pclzip/index.en.php> * <http://www.maani.us/charts4/> * <http://sourceforge.net/projects/tcpdf/> * <http://code.google.com/p/ofcgwt/w/list> * <http://sourceforge.net/projects/phpreports/> <-- Just found this
Here is a pdf generating library for PHP <http://www.fpdf.org/> .
Free reporting library for PHP without installation?
[ "", "php", "report", "" ]
I Think it would be more clearer with this example. We Want to see two methods with diferrent parameters in the processor class. "int Process (int value);" "double Process (double value);" But compiler says for IRoot : 'Generics.IRoot' cannot implement both 'Generics.IProcess' and 'Generics.IProcess' because they may unify for some type parameter substitutions. ``` public class Processor : IRoot<int, double, int, double> { // Here we want 2 methods public int Process(int item) { } public double Process(double item) { } } public interface IProcess<TResult, TItem> { TResult Process(TItem item); } public interface IRoot<TR1, TR2, TItem1, TItem2> : IProcess<TR1, TItem1>, IProcess<TR2, TItem2> { } ```
You could probably use this kind of implementation. You'll loose some generic arguments: ``` public interface IBase<TM, TPkey> where TM : bType where TPkey : new () { TM Get(TPkey key); } public interface IABase<TPK> : IBase<ConcreteTmA, TPK> {} public interface IBBase<TPK> : IBase<ConcreteTmB, TPK> {} public class Root <TPK> : IABase<TPK>, IBBase<TPK> where TM : MType where TPM : PMType where TPK : new() { ConcreteTmA IABase.Get(TPK key) { } ConcreteTmB IBBase.Get(TPK key) { } } ```
Here's my solution. It's based on using differentiation so you can be clear about which interface you want. You have to add an otherwise unused parameter, but that's what tells it which you want. ``` public interface First { } public interface Second { } public class Processor : IRoot<int, double, int, double> { // Here we want 2 methods public int Process ( int item ) { System.Console.WriteLine ( "int Process" ); return item + 1; } public double Process ( double item ) { System.Console.WriteLine ( "double Process" ); return item + 10.748; } } public class TestProcessor : IRoot<int, int, int, int> { int IProcessWithDifferentiator<int, int, First>.Process ( int item ) { System.Console.WriteLine ( "int Process" ); return item + 1; } int IProcessWithDifferentiator<int, int, Second>.Process ( int item ) { System.Console.WriteLine ( "int Process" ); return item + 100302; } } public interface IProcessWithDifferentiator<TResult, TItem, TDiff> { TResult Process ( TItem item ); } public interface IRoot<TR1, TR2, TItem1, TItem2> : IProcessWithDifferentiator<TR1, TItem1, First>, IProcessWithDifferentiator<TR2, TItem2, Second> { } class Program { static void Main ( string [] args ) { Processor p = new Processor (); IProcessWithDifferentiator<int, int, First> one = p; System.Console.WriteLine ( "one.Process(4) = " + one.Process ( 4 ) ); IProcessWithDifferentiator<double, double, Second> two = p; System.Console.WriteLine ( "two.Process(5.5) = " + two.Process ( 5.5 ) ); TestProcessor q = new TestProcessor (); IProcessWithDifferentiator<int, int, First> q1 = q; System.Console.WriteLine ( "q1.Process(4) = " + q1.Process ( 4 ) ); IProcessWithDifferentiator<int, int, Second> q2 = q; System.Console.WriteLine ( "q2.Process(5) = " + q2.Process ( 5 ) ); System.Console.ReadLine (); } } ``` Here's the output. ``` int Process one.Process(4) = 5 double Process two.Process(5.5) = 16.248 int Process q1.Process(4) = 5 int Process q2.Process(5) = 100307 ``` This will work even if you use `IRoot<int,int,int,int>` as you can see above; it knows (because we tell it) which IDifferentiatedProcess to use. (In case it matters, I'm on Visual Studio 2012.)
How to use same interface two times with diferrent template parameters, in an interface?
[ "", "c#", "generics", "" ]
I have a switch statement in one class that generates Command objects, based on if a certain line in a code file matches the particular code for that Command object. like this: ``` switch (line): { case "#CODE1": return new Command1(); case "#CODE2": return new Command2(); } ``` I want to turn it into something like this: ``` switch (line): { case Command1.Code: return new Command1(); case Command2.Code: return new Command2(); } ``` I tried it by creating a public static property of Command1, but the compiler complains... Is there a way to do something along this intent, that the compiler won't complain about?
I think you can do this only with constants... so if it's possible for you, use constant fields instead of public static properties. The difference is that it's treated like a literal at compile time, so if the value changes, you would need to recompile all assemblies that reference the constant.
Switch only works on numeric types and string types, not properties. You can try defining a public string constant on your Command1 and Command2 class, which you should be able to switch on instead. ``` public class Command1 { public string const Code = "#CODE1"; } ```
Using properties in switch statement cases?
[ "", "c#", ".net", "refactoring", "switch-statement", "" ]
I'm trying to match substrings that are enclosed in %'s but `preg_match_all` seems to include several at the same time in the same line. Code looks like this: ``` preg_match_all("/%.*%/", "%hey%_thereyou're_a%rockstar%\nyo%there%", $matches); print_r($matches); ``` Which produces the following output. ``` Array ( [0] => Array ( [0] => %hey%_thereyou're_a%rockstar% [1] => %there% ) ) ``` However I'd like it to produce the following array instead: ``` [0] => %hey% [1] => %rockstar% [2] => %there% ``` What am I missing?
Replace the "`.`" in your regular expression with "`[^%]`": ``` preg_match_all("/%[^%]*%/", "%hey%_thereyou're_a%rockstar%\nyo%there%", $matches); ``` What is happening is that the "`.`" is "greedily" matching as much as it possibly can, including everything up-to the final % on the line. Replacing it with the negated character class "`[^%]`" means that it will instead match anything *except* a percent, which will make it match just the bits that you want. Another option would be to place a "`?`" after the dot, which tells it "don't be greedy": ``` preg_match_all("/%.*?%/", "%hey%_thereyou're_a%rockstar%\nyo%there%", $matches); ``` In the above example, either option will work, however there are times when you may be searching for something larger than a single character, so a negated character class will not help, so the solution is to un-greedify the match.
You're doing a greedy match - use `?` to make it ungreedy: ``` /%.*?%/ ``` If a newline can occur inside the match, add the s (DOTALL) modifier: ``` /%.*?%/s ```
Regex to match string between %
[ "", "php", "regex", "preg-match-all", "" ]
I want to develop my GWT Widget. This widget draws Gantt chart and has drag - drop property. It will be simple form of [Deskera](http://www.deskera.com/) Where can I start to develop this widget? Any advice?
This tutorial covers how to create a GWT module: <http://developerlife.com/tutorials/?p=229>
Take a look at [gChart](http://code.google.com/p/gchart/) and maybe look at the source too. Good example of a custom widget.
How to develop GWT widget?
[ "", "java", "gwt", "gantt-chart", "" ]
IDE Configuration: Visual Studio 2008 + Resharper 4.5.1 + [Agent Smith 1.1.8](http://www.agentsmithplugin.com/). There is no any sophisticated configuration for last to add-ins. Solution description: 33 class libraries + web site with 200+ pages. Symptoms: After an hour of work under tuned on Resharper the IDE starts to throw the OutOfMemoryExection exceptions. Normal work is impossible only reopen Visual Studio can help. Does anybody has such problem? Is it possible to configure Resharper to consume less memory? What Resharper feature does consume the most memory?
If you're on 64-bit Windows (or you're happy to run 32-bit Windows with the /3GB switch), then you can configure Visual Studio to be /LARGEADDRESSAWARE, which, rather than 2GB, will give it 4GB (or 3GB on /3GB) of address space to play with. See, for example, <http://old.stevenharman.net/blog/archive/2008/04/29/hacking-visual-studio-to-use-more-than-2gigabytes-of-memory.aspx>, which gives the following: ``` editbin /LARGEADDRESSAWARE devenv.exe ``` Also, see the JetBrains page on the topic: <http://www.jetbrains.net/confluence/display/ReSharper/OutOfMemoryException%2BFix>
Welcome to the World of ReSharper. This lesson is called, "You get what you pay for". Various features of ReSharper do require knowledge of your entire solution. This information takes memory. The solution-wide analysis may be the most memory-intensive, but even changing the signature of a public method requires knowing all the code that calls that method. One thing you can do sometimes is to use smaller, "sub-solutions". If you are refactoring your DAL layer for instance, you only need the DAL and any unit test projects. What I sometimes do is to select the solution in Solution Explorer and use File->Save Solution As to save it with a different name in the same folder. I then remove projects until I'm left with those I want. Do *not* save the projects you're removing (save them before you start). When you've got the set you want, just do a Save All. If it becomes too much of an annoyance, you can also get ReSharper to display the memory usage in the status bar. That feature has been available for a *long* time.
Resharper throws OutOfMemoryException on big solution
[ "", "c#", "visual-studio", "resharper", "out-of-memory", "" ]
I'd like advice regarding scheduling execution within a Java web application. (currently running on Tomcat, but I'd like to avoid anything tomcat-specific). I think the following defines the aspect of my problem I'm interested in. Consider an application that polls a set of files for updates periodically. I'd like to provide a user interface that allows a user to define the polling interval for a given file independently, and have the execution schedule update according to user input. How can I achieve this safely in a web app?
Look at [Quartz](http://www.quartz-scheduler.org/).
Create a plain-old Java polling process which polls the files. It connects to your webapp's database to get the polling interval, and whatever other settings that can be user defined by the interface. Then create a simple web interface which reads and writes to the same table/database (polling intervals and whatever). Done!
Schedule-based execution in a J2EE Web Application
[ "", "java", "scheduling", "" ]
When do you use which in general? Examples are highly encouraged! I am referring so MySql, but can't imagine the concept being different on another DBMS
ORDER BY alters the order in which items are returned. GROUP BY will aggregate records by the specified columns which allows you to perform aggregation functions on non-grouped columns (such as SUM, COUNT, AVG, etc).
ORDER BY alters the order in which items are returned. GROUP BY will aggregate records by the specified columns which allows you to perform aggregation functions on non-grouped columns (such as SUM, COUNT, AVG, etc). ``` TABLE: ID NAME 1 Peter 2 John 3 Greg 4 Peter SELECT * FROM TABLE ORDER BY NAME = 3 Greg 2 John 1 Peter 4 Peter SELECT Count(ID), NAME FROM TABLE GROUP BY NAME = 1 Greg 1 John 2 Peter SELECT NAME FROM TABLE GROUP BY NAME HAVING Count(ID) > 1 = Peter ```
what is the difference between GROUP BY and ORDER BY in sql
[ "", "sql", "mysql", "database", "" ]
How do I declare and initialize an array in Java?
You can either use array declaration or array literal (but only when you declare and affect the variable right away, array literals cannot be used for re-assigning an array). For primitive types: ``` int[] myIntArray = new int[3]; // each element of the array is initialised to 0 int[] myIntArray = {1, 2, 3}; int[] myIntArray = new int[]{1, 2, 3}; // Since Java 8. Doc of IntStream: https://docs.oracle.com/javase/8/docs/api/java/util/stream/IntStream.html int [] myIntArray = IntStream.range(0, 100).toArray(); // From 0 to 99 int [] myIntArray = IntStream.rangeClosed(0, 100).toArray(); // From 0 to 100 int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).toArray(); // The order is preserved. int [] myIntArray = IntStream.of(12,25,36,85,28,96,47).sorted().toArray(); // Sort ``` For classes, for example `String`, it's the same: ``` String[] myStringArray = new String[3]; // each element is initialised to null String[] myStringArray = {"a", "b", "c"}; String[] myStringArray = new String[]{"a", "b", "c"}; ``` The third way of initializing is useful when you declare an array first and then initialize it, pass an array as a function argument, or return an array. The explicit type is required. ``` String[] myStringArray; myStringArray = new String[]{"a", "b", "c"}; ```
There are two types of array. ## One Dimensional Array Syntax for default values: ``` int[] num = new int[5]; ``` Or (less preferred) ``` int num[] = new int[5]; ``` Syntax with values given (variable/field initialization): ``` int[] num = {1,2,3,4,5}; ``` Or (less preferred) ``` int num[] = {1, 2, 3, 4, 5}; ``` Note: For convenience int[] num is preferable because it clearly tells that you are talking here about array. Otherwise no difference. Not at all. ## Multidimensional array ### Declaration ``` int[][] num = new int[5][2]; ``` Or ``` int num[][] = new int[5][2]; ``` Or ``` int[] num[] = new int[5][2]; ``` ### Initialization ``` num[0][0]=1; num[0][1]=2; num[1][0]=1; num[1][1]=2; num[2][0]=1; num[2][1]=2; num[3][0]=1; num[3][1]=2; num[4][0]=1; num[4][1]=2; ``` Or ``` int[][] num={ {1,2}, {1,2}, {1,2}, {1,2}, {1,2} }; ``` ### Ragged Array (or Non-rectangular Array) ``` int[][] num = new int[5][]; num[0] = new int[1]; num[1] = new int[5]; num[2] = new int[2]; num[3] = new int[3]; ``` So here we are defining columns explicitly. **Another Way:** ``` int[][] num={ {1}, {1,2}, {1,2,3,4,5}, {1,2}, {1,2,3} }; ``` ## For Accessing: ``` for (int i=0; i<(num.length); i++ ) { for (int j=0;j<num[i].length;j++) System.out.println(num[i][j]); } ``` Alternatively: ``` for (int[] a : num) { for (int i : a) { System.out.println(i); } } ``` Ragged arrays are multidimensional arrays. For explanation see multidimensional array detail at [the official java tutorials](http://docs.oracle.com/javase/tutorial/java/nutsandbolts/arrays.html)
How do I declare and initialize an array in Java?
[ "", "java", "arrays", "" ]
I have a java client that is calling a web service operation which takes a certificate "thumbprint" as a parameter. I believe the thumbprint is some kind of SHA1 hash, in hexadecimal string format, of the cert's public key, but I'm not sure. The .NET framework seems to include a simple way to get this value ([X509Certificate2.Thumbprint](http://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2.thumbprint.aspx) property). Viewing a .cer file's properties in Windows also displays the thumbprint, which looks like: ``` a6 9c fd b0 58 0d a4 ee ae 9a 47 75 24 c3 0b 9f 5d b6 1c 77 ``` My question is therefore: Does anybody know how to retrieve or compute this thumbprint string within Java, if I have an instance of a [java.security.cert.X509Certificate](http://docs.oracle.com/javase/7/docs/api/javax/security/cert/X509Certificate.html)?
The SHA-1 hash of the [DER encoding](https://en.wikipedia.org/wiki/X.690#DER_encoding) of the certificate is what .NET is getting with **X509Certificate2.Thumbprint**. As noted on the [remarks on MSDN](https://msdn.microsoft.com/en-us/library/system.security.cryptography.x509certificates.x509certificate2.thumbprint.aspx#Remarks): > The thumbprint is dynamically generated using the SHA1 algorithm and does not physically exist in the certificate. Since the thumbprint is a unique value for the certificate, it is commonly used to find a particular certificate in a certificate store. Java's standard library doesn't provide the thumbprint directly, but you can get it like this: ``` DatatypeConverter.printHexBinary( MessageDigest.getInstance("SHA-1").digest( cert.getEncoded())).toLowerCase(); ``` Here's a full worked example using a conveniently accessible PEM file: 1. Create **stackoverflow.crt.pem**: ``` -----BEGIN CERTIFICATE----- MIIHHjCCBgagAwIBAgIQDhG71w1UtxDQxvVAtrUspDANBgkqhkiG9w0BAQsFADBw MQswCQYDVQQGEwJVUzEVMBMGA1UEChMMRGlnaUNlcnQgSW5jMRkwFwYDVQQLExB3 d3cuZGlnaWNlcnQuY29tMS8wLQYDVQQDEyZEaWdpQ2VydCBTSEEyIEhpZ2ggQXNz dXJhbmNlIFNlcnZlciBDQTAeFw0xNjA1MjEwMDAwMDBaFw0xOTA4MTQxMjAwMDBa MGoxCzAJBgNVBAYTAlVTMQswCQYDVQQIEwJOWTERMA8GA1UEBxMITmV3IFlvcmsx HTAbBgNVBAoTFFN0YWNrIEV4Y2hhbmdlLCBJbmMuMRwwGgYDVQQDDBMqLnN0YWNr ZXhjaGFuZ2UuY29tMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAr0YD zscT5i6T2FaRsTGNCiLB8OtPXu8N9iAyuaROh/nS0kRRsN8wUMk1TmgZhPuYM6oF S377V8W2LqhLBMrPXi7lnhvKt2DFWCyw38RrDbEsM5dzVGErmhux3F0QqcTI92zj VW61DmE7NSQLiR4yonVpTpdAaO4jSPJxn8d+4p1sIlU2JGSk8LZSWFqaROc7KtXt lWP4HahNRZtdwvL5dIEGGNWx+7B+XVAfY1ygc/UisldkA+a3D2+3WAtXgFZRZZ/1 CWFjKWJNMAI6ZBAtlbgSNgRYxdcdleIhPLCzkzWysfltfiBmsmgz6VCoFR4KgJo8 Gd3MeTWojBthM10SLwIDAQABo4IDuDCCA7QwHwYDVR0jBBgwFoAUUWj/kK8CB3U8 zNllZGKiErhZcjswHQYDVR0OBBYEFFrBQmPCYhOznZSEqjIeF8tto4Z7MIIB6AYD VR0RBIIB3zCCAduCEyouc3RhY2tleGNoYW5nZS5jb22CEXN0YWNrb3ZlcmZsb3cu Y29tghMqLnN0YWNrb3ZlcmZsb3cuY29tgg1zdGFja2F1dGguY29tggtzc3RhdGlj Lm5ldIINKi5zc3RhdGljLm5ldIIPc2VydmVyZmF1bHQuY29tghEqLnNlcnZlcmZh dWx0LmNvbYINc3VwZXJ1c2VyLmNvbYIPKi5zdXBlcnVzZXIuY29tgg1zdGFja2Fw cHMuY29tghRvcGVuaWQuc3RhY2thdXRoLmNvbYIRc3RhY2tleGNoYW5nZS5jb22C GCoubWV0YS5zdGFja2V4Y2hhbmdlLmNvbYIWbWV0YS5zdGFja2V4Y2hhbmdlLmNv bYIQbWF0aG92ZXJmbG93Lm5ldIISKi5tYXRob3ZlcmZsb3cubmV0gg1hc2t1YnVu dHUuY29tgg8qLmFza3VidW50dS5jb22CEXN0YWNrc25pcHBldHMubmV0ghIqLmJs b2dvdmVyZmxvdy5jb22CEGJsb2dvdmVyZmxvdy5jb22CGCoubWV0YS5zdGFja292 ZXJmbG93LmNvbYIVKi5zdGFja292ZXJmbG93LmVtYWlsghNzdGFja292ZXJmbG93 LmVtYWlsMA4GA1UdDwEB/wQEAwIFoDAdBgNVHSUEFjAUBggrBgEFBQcDAQYIKwYB BQUHAwIwdQYDVR0fBG4wbDA0oDKgMIYuaHR0cDovL2NybDMuZGlnaWNlcnQuY29t L3NoYTItaGEtc2VydmVyLWc1LmNybDA0oDKgMIYuaHR0cDovL2NybDQuZGlnaWNl cnQuY29tL3NoYTItaGEtc2VydmVyLWc1LmNybDBMBgNVHSAERTBDMDcGCWCGSAGG /WwBATAqMCgGCCsGAQUFBwIBFhxodHRwczovL3d3dy5kaWdpY2VydC5jb20vQ1BT MAgGBmeBDAECAjCBgwYIKwYBBQUHAQEEdzB1MCQGCCsGAQUFBzABhhhodHRwOi8v b2NzcC5kaWdpY2VydC5jb20wTQYIKwYBBQUHMAKGQWh0dHA6Ly9jYWNlcnRzLmRp Z2ljZXJ0LmNvbS9EaWdpQ2VydFNIQTJIaWdoQXNzdXJhbmNlU2VydmVyQ0EuY3J0 MAwGA1UdEwEB/wQCMAAwDQYJKoZIhvcNAQELBQADggEBAAzJAMGSdKoX1frdqNlN iXu8Gcbsm/DxWMXpcTXlZn8s+/qQQoc+/3o0CK3C8/j9n5DmsYa88P6Ntt5ysDs+ b0ynXFva4CAEyKaoPM4SIpOjwfWBRSUOqAIkQO2/LhKBwT/EnpaIHIKGnI0UdXLQ oDfkMDg6mgJsEBsKdKF5EfEX7iU3NO5xVJPJE8/R0btLAdYwxB9S6fSpCXGe2HqQ D101O/7/4MWNdFSbfdDSFcn5oEm+idimrqiNrF5knmuJy4qPBkL7thNuGK6rvYCF ZJM03ZEZhkQmn2jG/7LgjfwZmvfcITeADCpylf88bL+lf+vxe6cCl9CyqWgBDpsI xpE= -----END CERTIFICATE----- ``` 2. Create **X509.java**: ``` import javax.xml.bind.DatatypeConverter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.cert.CertificateEncodingException; import java.security.cert.CertificateException; import java.security.cert.CertificateFactory; import java.security.cert.X509Certificate; public final class X509 { public static void main(String[] args) throws FileNotFoundException, CertificateException, NoSuchAlgorithmException { FileInputStream is = new FileInputStream(args[0]); CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); X509Certificate cert = (X509Certificate) certificateFactory.generateCertificate(is); String thumbprint = getThumbprint(cert); System.out.println(thumbprint); } private static String getThumbprint(X509Certificate cert) throws NoSuchAlgorithmException, CertificateEncodingException { MessageDigest md = MessageDigest.getInstance("SHA-1"); byte[] der = cert.getEncoded(); md.update(der); byte[] digest = md.digest(); String digestHex = DatatypeConverter.printHexBinary(digest); return digestHex.toLowerCase(); } } ``` 3. Compile the program with Java 8: ``` javac X509.java ``` Or Java 9 - due to modular JDK/JPMS - **DataTypeConverter** is not in **java.base**, but **java.xml.bind**, so you need to explicitly depend on it during your build: ``` javac --add-modules java.xml.bind X509.java ``` Otherwise, on Java 9, you get this when you try to build it: ``` X509.java:3: error: package javax.xml.bind is not visible import javax.xml.bind.DatatypeConverter; ^ (package javax.xml.bind is declared in module java.xml.bind, which is not in the module graph) 1 error ``` 4. Run it with Java 8: ``` java X509 stackoverflow.crt.pem ``` In Java 9 - due to modular JDK/JPMS - **DataTypeConverter** is not in **java.base**, but **java.xml.bind**, so you need to explicitly depend on it when running your program: ``` java --add-modules java.xml.bind X509 stackoverflow.crt.pem ``` Otherwise, on Java 9, you get this when you try to run it: ``` Exception in thread "main" java.lang.NoClassDefFoundError: javax/xml/bind/DatatypeConverter at X509.getThumbPrint(X509.java:29) at X509.main(X509.java:19) Caused by: java.lang.ClassNotFoundException: javax.xml.bind.DatatypeConverter at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:582) at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:185) at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:496) ... 2 more ``` 5. Get the expected output: ``` 47adb03649a2eb18f63ffa29790818349a99cab7 ```
Using Apache Commons Codec you can do: ``` DigestUtils.sha1Hex(cert.getEncoded()) ```
How to retrieve/compute an X509 certificate's thumbprint in Java?
[ "", "java", "certificate", "" ]
I would like to use jQuery.ajax to submit a form using POST without having to specify everything manually in the "data: " part. This is what I don't want: ``` data: "username=" + document.getElementById("username").value + "&email=" + document.getElementById("email").value, ``` Is there a way to just have it include alla elements with their values from an entire FORM field? This form is generated dynamically so it would save me a lot of time!
Use [serialize method](http://docs.jquery.com/Ajax/serialize). ``` data : $("form").serialize() ```
Look at <http://docs.jquery.com/Ajax/serialize>. That would make the following example: ``` $("#submit").click(function() { $.ajax({ data: $("form").serialize(), ...rest }); }); ```
jQuery.ajax - submit all elements in form without manually entering them
[ "", "javascript", "jquery", "ajax", "forms", "" ]
I need to get the MAC ID of a host in my network. For that, if I ping to that IP and query the ARP cache `arp -a`, I am able to get the MAC ID. I just wonder if I can get any API to query the ARP and get the MAC id. Also, if there is a better method to get the MAC ID from IP address, please suggest. P.S: I am working in JAVA. Thanks.
Java provides no direct way to query the MAC address of a host in your network, as this is abstracted away by Java's socket libraries. In a way, this makes sense, because the MAC address of a host actually says very little. There is no such thing as "the" MAC address of a host. * Many hosts will have several NICs, all with a separate MAC address, with which they can connect to the network. The computer I'm on at the moment has a wired ethernet adapter, a WiFi adapter, and a Firewire adapter, and they all have their own MAC address. This means that there is no definitive MAC address for a host. * If the host is on a different subnet, ARP will actually give you the MAC address for the last router your packet passed through, instead of the MAC address of the host you're scanning. Put both of these issues together, and that means that one host may have many different MAC addresses (if it has more than one NIC), and one MAC address may represent many different hosts (if traffic passes through a router). Assuming you know all this and you still need to get the MAC address of a host, the only way to do that in Java is by "going native": * Native to the client that runs your program: + You could launch an ARP command-line tool and parse its output. + You could use some sort of JNI call. I'm not too familiar with JNI, though, so I can't help you with that. + Write a separate, small native app that you can access from Java via Telnet or some such protocol, and which will run the ARP command for you. * Native to the host that you want to scan: + You could use SNMP, as some of the other answers to this thread suggest. I defer to these answers for making that work for you. SNMP is a great protocol, but be aware that SNMP's OIDs can be both platform-dependent and vendor-dependent. OIDs that work for Windows don't always work for Linux and vice versa. + If you know that your host runs Windows, you could use [WMI](http://msdn.microsoft.com/en-us/library/aa394582%28VS.85%29.aspx). The [Win32\_NetworkAdapter](http://msdn.microsoft.com/en-us/library/aa394216%28VS.85%29.aspx) class holds the information you want, but be aware that this returns *all* of the hosts NICs, even the ones Windows makes up. Also, it requires administrator credentials to the host you are scanning. Google will tell you how to connect to WMI from Java. + If you know your host runs OS X, you might be able to SSH into the machine and parse the output of the `system_profile` command. + For Linux, a tool similar to OS X's `system_profile` probably exists.
There is a much simpler way: ``` private static final String ARP_GET_IP_HW = "arp -a"; public String getARPTable(String cmd) throws IOException { Scanner s = new Scanner(Runtime.getRuntime().exec(cmd).getInputStream()).useDelimiter("\\A"); return s.hasNext() ? s.next() : ""; } System.out.println(getARPTable(ARP_GET_IP_HW )); ``` And you get the eintire ARP Table with IP and HW sorted on each row. Then you can split the table into separate String rows and use regular expressions on each row to match both HW and IP Adress. And you're done.
Query ARP cache to get MAC ID
[ "", "java", "networking", "" ]
I'm trying to sort a list of titles, but currently there's a giant block of titles which start with 'The '. I'd like the 'The ' to be ignored, and the sort to work off the second word. Is that possible in SQL, or do I have to do custom work on the front end? For example, current sorting: * Airplane * Children of Men * Full Metal Jacket * Pulp Fiction * The Fountain * The Great Escape * The Queen * Zardoz Would be better sorted: * Airplane * Children of Men * The Fountain * Full Metal Jacket * The Great Escape * Pulp Fiction * The Queen * Zardoz Almost as if the records were stored as 'Fountain, The', and the like. But I don't want to store them that way if I can, which is of course the crux of the problem.
Best is to have a computed column to do this, so that you can index the computed column and order by that. Otherwise, the sort will be a lot of work. So then you can have your computed column as: ``` CASE WHEN title LIKE 'The %' THEN stuff(title,1,4,'') + ', The' ELSE title END ``` Edit: If STUFF isn't available in MySQL, then use RIGHT or SUBSTRING to remove the leading 4 characters. But still try to use a computed column if possible, so that indexing can be better. The same logic should be applicable to rip out "A " and "An ". Rob
Something like: ``` ORDER BY IF(LEFT(title,2) = "A ", SUBSTRING(title FROM 3), IF(LEFT(title,3) = "An ", SUBSTRING(title FROM 4), IF(LEFT(title,4) = "The ", SUBSTRING(title FROM 5), title))) ``` But given the overhead of doing this more than a few times, you're really better off storing the title sort value in another column...
Custom ORDER BY to ignore 'the'
[ "", "sql", "mysql", "sorting", "" ]
This is what I have so far: ``` <?php $text = preg_replace('/((\*) (.*?)\n)+/', 'awesome_code_goes_here', $text); ?> ``` I am successfully matching plain-text lists in the format of: ``` * list item 1 * list item 2 ``` I'd like to replace it with: ``` <ul> <li>list item 1</li> <li>list item 2</li> </ul> ``` I can't get my head around wrapping `<ul>` and looping through `<li>`s! Can anyone please help? **EDIT: Solution as answered below...** My code now reads: ``` $text = preg_replace('/\* (.*?)\n/', '<ul><li>$1</li></ul>', $text); $text = preg_replace('/<\/ul><ul>/', '', $text); ``` That did it!
One option would be to simply replace each list item with `<ul><li>list item X</li></ul>` and then run a second replace which would replace any `</ul><ul>` with nothing.
I know that this is an old post - but it needs a solution. Try this! :) ``` $text = preg_replace("/\[ul\](.*)\[\/ul\]/Usi", "<ul>\\1</ul>", $text); $text = preg_replace("/\[li\](.*)\[\/li\]/Usi", "<li>\\1</li>", $text); ```
PHP preg_replace() on multiple items
[ "", "php", "regex", "preg-replace", "" ]
I am playing around with PortAudio and Python. ``` data = getData() stream.write( data ) ``` I want my stream to play sound data, that is represented in Float32 values. Therefore I use the following function: ``` def getData(): data = [] for i in range( 0, 1024 ): data.append( 0.25 * math.sin( math.radians( i ) ) ) return data ``` Unfortunately that doesn't work because `stream.write` wants a buffer object to be passed in: ``` TypeError: argument 2 must be string or read-only buffer, not list ``` So my question is: How can I convert my list of floats in to a buffer object?
``` import struct def getData(): data = [] for i in range( 0, 1024 ): data.append( 0.25 * math.sin( math.radians( i ) ) ) return struct.pack('f'*len(data), *data) ```
Actually, the easiest way is to use the [struct module](http://docs.python.org/library/struct.html#module-struct). It is designed to convert from python objects to C-like "native" objects.
Convert list of floats into buffer in Python?
[ "", "python", "list", "floating-point", "buffer", "" ]
I am trying to add a column to a `JTable` with the following behaviour (similar to Windows Explorer and similar shells): * The cell can be clicked once to select it, as usual. * The cell can be double-clicked to perform a separate action (launching an external program.) * The cell value (a string) can still be edited, by single-clicking a second time (after a pause) or by pressing `F2` when the cell is highlighted. Double-clicking must **not** trigger editing of the cell, but I would like to leave any other default editing triggers operational if possible. I have tried adding a `MouseListener` to the table, and consuming all `MouseEvent`s, but this does not work - if I return `true` from `isCellEditable()` then my listener never receives any click events but if I return `false` then `F2` no longer works. Can this be achieved using only event listeners? I would prefer not to mess with the PLAF functions if I can avoid it.
You will have to make your own cellEditor and ovveride ``` public boolean isCellEditable( EventObject e ) ``` You can distinguish between single and double click with the clickCount on the eventObject If its a single Click and its on a selected cell you can return true otherwise return false; retrieve row and column with ``` int row = ( (JTable) e.getSource() ).rowAtPoint(e.getPoint()); int column = ( (JTable) e.getSource() ).columnAtPoint(e.getPoint()); ``` to enable F2 you can add custom inputMap en actionMap entries ``` similar too table.getInputMap().put(KeyStroke.getKeyStroke("DOWN"), "doMyArrowDown"); table.getTable().getActionMap().put("doMyArrowDown", new ArrowDownAction()); ``` and from your action you can then fire the cellediting yourself ``` table.editCellAt(row, column ); ```
The DefaultCellEditor has a setClickCountToStart() method to control mouse clicks for editing. The default is 2. Changing this will have no effect on F2 functionality. Therefore you can set editing to be a triple click. Not sure exactly how to handle two single clicks to start editing but I guess you would use a Timer to keep track of the first click and then do the editing if the second single click is within you time interval.
Making a JTable cell editable - but *not* by double clicking
[ "", "java", "swing", "jtable", "tablecelleditor", "" ]
I want to use HTML and PHP for 9 or more images upload. The problem is that I don't want 9 upload fields because it looks bad. Does anybody have any suggestions ? Maybe examples ? Thanks.
<http://the-stickman.com/web-development/javascript/upload-multiple-files-with-a-single-file-element/>
I've been using [noSWFUpload](http://code.google.com/p/noswfupload/) for some time and it works pretty good. It relies on XMLHttpRequest's `sendAsBinary` in supporting clients and falls back to iframe-based submission.
Multiple image upload without flash
[ "", "javascript", "html", "http-upload", "" ]
I plan to write a Desktop Client for Windows and Mac. It will be powered by web techniques (HTML + JS). Therefore it shall run on a WebKit engine on the user's desktop. Recently, I saw an interesting approach for this issue: [Appcelerator](http://www.appcelerator.com/products/titanium-desktop/) I love its basic concept, but I don't want be dependent on their services. Instead I want to have full control on the WebKit program, which loads my app. Are there any decent open source WebKit frameworks for building desktop apps? Desktop integration features, such as Growl-support and stuff are appreciated. Regards, Stefan --- Update: I'm not searching for Adobe Air ;-)
Besides Appcelerator, I'm aware of two desktop gui frameworks that have a browser component that wraps webkit: GTK+ and Qt. You can make the browser component fill your application's window and write most (or all) of the application in HTML+CSS. If you like the Python language or it's very significant standard library, you can use the python bindings pyQt or pyGTK. A more "beefy" alternative to Prism, if you're willing to go with the Gecko engine, is XULRunner (<https://developer.mozilla.org/En/XULRunner>). While Prism is a set of lightweight bindings to the desktop for a web app, XULRunner allows you to build a complete app like Firefox itself or Thunderbird, etc. While many XULRunner applications are written with XUL, it is easy to write the whole app using HTML/CSS inside a single XUL WebBrowser component - and your javascript still has all the power of a native desktop application. I have written a couple desktop applications using XULRunner. Almost all of the applications' code is HTML/CSS/Javascript, but I have included the Python framework (via pyXPCOM and pyXPCOMext) and have written a thin layer that exposes some Python functionality to the Javascript. The Mozilla components that come with XULRunner gives you a decent amount of functionality for free, but if you find yourself in need of more functionality or a full-featured programming library, Python will do the trick. There are also bindings to Java. Or, if you want to use C or C++ libraries, you can build XULRunner from scratch. **Update:** A few things have changed since I originally wrote the above in 2009. For one, the Prism project was dropped from Mozilla Labs and subsequently discontinued altogether in late 2011 (<http://www.salsitasoft.com/2011/09/08/discontinuing-webrunner/>). One alternative worth looking at is <https://github.com/rogerwang/node-webkit>. **Dec 2014 Update:** Another recent option is GitHub's Atom Shell. It uses Chromium's "content" module, just like node-webkit and Chromium Embedded Framework (and publishes it as a standalone lib: <https://github.com/brightray/libchromiumcontent>). One major difference from node-webkit is that instead of merging node's event loop with Chromium's event loop, Atom launches them both in separate processes and uses a mixture of sync and async inter-process messages to communicate between them. If you're interested in embedding Chromium in a C++ or .Net app, there's also [Awesomium](http://www.awesomium.com/).
The Appcelerator platform is [open source](http://github.com/appcelerator/titanium_desktop/tree/master), so you're not dependent on the company - you could always hack the code around yourself if you wanted. If you want more control you could always just [hook directly into WebKit](http://arstechnica.com/open-source/guides/2009/07/how-to-build-a-desktop-wysiwyg-editor-with-webkit-and-html-5.ars). The Gecko equivalent to AIR/Appcelerator Joel refers to is probably [Mozilla Prism](http://prism.mozilla.com/).
Framework for (HTML + JS) Desktop Client
[ "", "javascript", "html", "webkit", "desktop-application", "" ]
I write application in Java using SWT. I would like to create unique file name. But I do not want create it on hard drive. Additional functionality: I want to create unique file name in specify folder. ``` public String getUniqueFileName(String directory, String extension) { //create unique file name } ```
Use a GUID * <http://java.sun.com/j2se/1.5.0/docs/api/java/util/UUID.html> * <http://en.wikipedia.org/wiki/Globally_Unique_Identifier>
From your question I assume you've seen that [`File.createTempFile()`](http://docs.oracle.com/javase/7/docs/api/java/io/File.html#createTempFile%28java.lang.String,%20java.lang.String%29) always creates a file rather than just allowing you to generate the name. But why not just call the method and then delete the temporary file created? `createTempFile()` does all the work in finding a unique file name in the specified directory and since you created the file you can sure you'll be to delete it too. ``` File f = File.createTempFile("prefix",null,myDir); String filename = f.getName(); f.delete(); ```
How to create tmp file name with out creating file
[ "", "java", "file", "file-io", "" ]
Effectively what I need to do in JS is move all absolutely positioned elements down by x pixels. Do I need to loop through every element and try to figure out if it's positioned absolutely? Or is there a better way? Thanks, Mala **Update:** *specific*: I am using a bookmarklet to inject JS onto any page - thus I cannot change the markup or actual css files in any way. This bookmarklet should, among other things, move all absolutely positioned elements 155 pixels down.
Something like this should do it: ``` function getStyle(el, prop) { var doc = el.ownerDocument, view = doc.defaultView; if (view && view.getComputedStyle) { return view.getComputedStyle(el, '')[prop]; } return el.currentStyle[prop]; } var all = document.getElementsByTagName('*'), i = all.length; while (i--) { var topOffset = parseInt(all[i].style.top, 10); if (getStyle(all[i], 'position') === 'absolute') { all[i].style.top = isNaN(topOffset) ? '155px' : (topOffset + 155) + 'px'; } } ```
You could tag all absolutely positioned elements with a specific class name and use the `getElementsByClassName` in [most browsers](http://www.quirksmode.org/dom/w3c_core.html#fivemethods). Other than that, looping is the only option.
Javascript to modify all absolutely positioned elements
[ "", "javascript", "css", "position", "css-position", "" ]
I was trying to find examples about socket programming and came upon this script: <http://stacklessexamples.googlecode.com/svn/trunk/examples/networking/mud.py> When reading through this script i found this line: listenSocket.listen(5) As i understand it - it reads 5 bytes from the buffer and then does stuff with it... but what happens if more than 5 bytes were sent by the other end? in the other place of that script it checks input against 4 commands and sees if there is \r\n in the string. dont commands like "look" plus \r\n make up for more than 5 bytes? Alan
The following is applicable to sockets in general, but it should help answer your specific question about using sockets from Python. socket.listen() is used on a *server* socket to listen for incoming connection requests. The parameter passed to listen is called the *backlog* and it means how many connections should the socket accept and put in a pending buffer until you finish your call to accept(). That applies to connections that are waiting to connect to your server socket between the time you have called listen() and the time you have finished a matching call to accept(). So, in your example you're setting the backlog to 5 connections. **Note**.. if you set your backlog to 5 connections, the following connections (6th, 7th etc.) will be dropped and the connecting socket will receive an *error connecting* message (something like a "host actively refused the connection" message)
This might help you understand the code: <http://www.amk.ca/python/howto/sockets/>
Explain socket buffers please
[ "", "python", "sockets", "stackless", "python-stackless", "" ]
I have an XML document which is confounding me. I'd like to (to start) pull all of the document nodes (/database/document), but it only works if I remove all of the attributes on the database element. Specifically the xmlns tag causes an xpath query for /database/document to return nothing - remove it, and it works. ``` xmlns="http://www.lotus.com/dxl" ``` I take it this has to do with XML namespaces. What is it doing, and more to the point, how do I make it stop? I just want to parse the document for data. ``` <?xml version="1.0" encoding="utf-8"?> <database xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.lotus.com/dxl xmlschemas/domino_7_0_3.xsd" xmlns="http://www.lotus.com/dxl" version="7.0" maintenanceversion="3.0" path="C:\LotusXML\test1.nsf" title="test1"> <databaseinfo numberofdocuments="3"> <datamodified> <datetime dst="true">20090812T142141,48-04</datetime> </datamodified> <designmodified> <datetime dst="true">20090812T154850,91-04</datetime> </designmodified> </databaseinfo> <document form="NameAddress"> <noteinfo noteid="8fa" unid="x" sequence="2"> <created> <datetime dst="true">20090812T130308,71-04</datetime> </created> <modified> <datetime dst="true">20090812T142049,36-04</datetime> </modified> <revised> <datetime dst="true">20090812T142049,35-04</datetime> </revised> <lastaccessed> <datetime dst="true">20090812T142049,35-04</datetime> </lastaccessed> <addedtofile> <datetime dst="true">20090812T130321,57-04</datetime> </addedtofile> </noteinfo> <updatedby> <name>MOOSE</name> </updatedby> <revisions> <datetime dst="true">20090812T130321,57-04</datetime> </revisions> <item name="Name"> <text>joe</text> </item> <item name="OtherName"> <text>dave</text> </item> <item name="Address"> <text>here at home</text> </item> <item name="PictureHere"> <richtext> <pardef id="1" /> <par def="1"> </par> <par def="1" /> </richtext> </item> </document> <document form="NameAddress"> <noteinfo noteid="8fe" unid="x" sequence="2"> <created> <datetime dst="true">20090812T130324,59-04</datetime> </created> <modified> <datetime dst="true">20090812T142116,95-04</datetime> </modified> <revised> <datetime dst="true">20090812T142116,94-04</datetime> </revised> <lastaccessed> <datetime dst="true">20090812T142116,94-04</datetime> </lastaccessed> <addedtofile> <datetime dst="true">20090812T130333,90-04</datetime> </addedtofile> </noteinfo> <updatedby> <name>MOOSE</name> </updatedby> <revisions> <datetime dst="true">20090812T130333,90-04</datetime> </revisions> <item name="Name"> <text>fred</text> </item> <item name="OtherName"> <text>wilma</text> </item> <item name="Address"> <text>bedrock</text> </item> <item name="PictureHere"> <richtext> <pardef id="1" /> <par def="1"> </par> <par def="1" /> </richtext> </item> </document> <document form="NameAddress"> <noteinfo noteid="902" unid="x" sequence="2"> <created> <datetime dst="true">20090812T130337,09-04</datetime> </created> <modified> <datetime dst="true">20090812T142141,48-04</datetime> </modified> <revised> <datetime dst="true">20090812T142141,47-04</datetime> </revised> <lastaccessed> <datetime dst="true">20090812T142141,47-04</datetime> </lastaccessed> <addedtofile> <datetime dst="true">20090812T130350,20-04</datetime> </addedtofile> </noteinfo> <updatedby> <name>MOOSE</name> </updatedby> <revisions> <datetime dst="true">20090812T130350,20-04</datetime> </revisions> <item name="Name"> <text>julie</text> </item> <item name="OtherName"> <text>mccarthy</text> </item> <item name="Address"> <text>the pen</text> </item> <item name="PictureHere"> <richtext> <pardef id="1" /> <par def="1"> </par> <par def="1" /> </richtext> </item> </document> </database> ```
The `xmlns="http://www.lotus.com/dxl"` sets a default namespace for contained nodes. It means that `/database/document` is really `/{http://www.lotus.com/dxl}:database/{http://www.lotus.com/dxl}:document`. Your XPath query will need to include the namespace: ``` XmlDocument doc = new XmlDocument(); doc.Load(fileName); XmlNamespaceManager ns = new XmlNamespaceManager(doc.NameTable); ns.AddNamespace("tns", "http://www.lotus.com/dxl"); var documents = doc.SelectNodes("/tns:database/tns:document", ns); ```
When there is an XML namespace defined, each element needs to preceded by it for it to be correctly recognized. If you were to use LINQ to XML to read in this data it would look something like this: ``` XDocument xdoc = XDocument.Load("file.xml"); XNamespace ns = "http://www.lotus.com/dxl"; var documents = xdoc.Descendants(ns + "document"); ``` XML namespaces are similar in concept to C# namespaces (or any other language that supports it). If you define a class inside a namespace, you wouldn't be able to access it without first specifying the namespace (this is what using statements do for you).
XML Namespaces are confounding me
[ "", "c#", "xml", "" ]
When I use `window.open()` to do a pop up on a new window, I'm unable to hide the url bar. It still shows the url bar even though it's read only. Can I hide it? I do not want user to see the url.
> In Internet Explorer 7 and later, you cannot remove the address bar in Internet Zone windows, for security (anti-spoofing) reasons. — <http://msdn.microsoft.com/en-us/library/ms536651%28VS.85%29.aspx>
You cannot do that in other browsers (Firefox, Chrome) also so even if you **could** do it in IE, it would have been pointless. Won't it?
Hide the url bar on a pop up window
[ "", "javascript", "" ]
I have a big binary file (1 MB < size < 50 MB). I need to search for a string and extract the subsequent four bytes (which is the {size,offset} of actual data in another file). What is the most efficient way to do it so that the search would be fastest? EDIT: The strings in the index files are in sorted order.
Store the {string, size, offset} tuples in sorted order (by string) and use a binary search for the string. You might also store, at the start of the file, offsets for each first letter of strings. For example if strings starting with 'a' began at position 120 and those starting with 'b' began at position 2000 in the file you could start the file with something like `120, 2000, ...`
Look up the [Boyer–Moore string search algorithm](http://en.wikipedia.org/wiki/Boyer-Moore_string_search_algorithm).
Searching for strings in big binary files
[ "", "c#", ".net", "file-io", "" ]