Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
We currently have a system where each client gets their own database when they sign-up. Not surprisingly this is getting out of hand. We are preparing merge all these databases together to a single db. In order to do this we need to note which organization the row belongs. How best is this handled on the database and what pros/cons (Speed, Maintainability, etc) are there to the methods below? **Option 1**: Make the Organization Id to all tables and make it part of the primary key (making all keys composite). **Option 2**: Add Organization Id to all tables as a column with a Foreign Key to the Organization Table. **Option 3**: Something else. We are looking at moving to NHibernate with this move, if that has an effect on what is done.
Option 1 and 2 are not mutually exclusive and you should do both. A foreign key constraint on the organization helps ensure that your organization keys are valid. A composite primary key is the only way to achieve uniqueness, unless you want to re-key all your records, and it is also valuable for lookup performance. Alternatively, you'd have to create a new primary key column on the combined data, an identity column, for instance. Such a change would likely require more changes in other places.
The company I work at uses option 2 and speed and maintainability have not been too much of an issue. As for speed as long as you set up your indexing correctly you queries should be pretty fast.. And for maintainability I would say that option 2 is definitely a step in the right direction compared to what you are dealing with now. It has been really easy to work with and all you have to do is a join in your query and you can add any client info you need. Cdonner made a good point. In those tables that you are going to be querying alot it would be a good idea to have a composite key. They can help with performance of queries if you properly index your tables
Organization Id Field as a Composite Primary Key
[ "", "sql", "sql-server", "performance", "nhibernate", "database-design", "" ]
I recently wrote a program to help me understand the basics of memory pointers in C++, I chose a simple prime number finder. I finally got it to work. (yay for debugging!) And I let it run to see how far it goes, it gets to prime #815389 with my verbose tells me is the 65076th prime, I get an app crash. The one thing I could think of was my ints overflowing so I changed them to longs, it gets stuck at the same place. Would someone be able to help explain what limitation is causing this? comp: WinVista 64-bit Home Premium, 6GB ram AMD 4800+ X2 program crashes at 4,664K memory usage Source: ``` #include <cstdlib> #include <iostream> \\\\(Backslashes added for readability) using namespace std; long number; long numnum; class num; class num { public: long i; void check(); bool nxt; num* nxtnum; }; void num::check() { if (number % i != 0) { if (nxt == true) { (*nxtnum).check(); } else { nxtnum = new num(); (*nxtnum).i = number; numnum++; cout << numnum << ":" << number << ", "; nxt = true; }; }; }; int main(long argc, char *argv[]){ numnum = 1; cout << numnum << ":" << 2 << ", "; num two; two.i = 2; for (number = 3; 1<=1000001; number++) { two.check(); }; cout << endl; system("PAUSE"); return EXIT_SUCCESS; }; ``` (Nevermind the username it's just an alias I use so I can keep track of all my posts with google)
Sean is right, two.nxt is never initialised. In fact, num.nxt is never initialised for any instance of num. The member nxt is unnecessary if the class is made more robust. The nxt pointer can be used instead: ``` class num { private: long i; num *nxtnum; public: num (long value) : i (value), nxtnum (0) { } void check () { if (number % i != 0) { if (nxtnum) { nxtnum->check (); } else { nxtnum = new num (number); cout << ++numnum << ":" << number << ", "; } } }; ``` Of course, the recursive nature is probably the main culprit, the initialisation issue was hidden as you were probably running a debug build. Converting the recursive form to the iterative form is left as an exercise.
Stack overflow? I see that `check` is recursive.
Unknown crash in a C++ Memory Pointers Exercise
[ "", "c++", "pointers", "crash", "" ]
Visual Studio 2008 got two great features for c#, which is called "sort using directives" and "remove unused using directives". I'd like to call the "sort using directives" every time I format the code using ctrl+k,ctrl+d. Or, even better, I would like to be able to reformat all c#-source files in a project, and call "sort using directives" for all source files. How can I do this? Opening every cs-file by hand and typing these functions before every checkin is tedious!
You can do it all for a solution or project using ["PowerCommands for Visual Studio 2008"](http://code.msdn.microsoft.com/PowerCommands). After installation, you just need to right-click on a project or solution and "Remove and Sort Usings" is in the context menu. EDIT: As noted in comments, there are also [PowerCommands for Visual Studio 2010](http://visualstudiogallery.msdn.microsoft.com/e5f41ad9-4edc-4912-bca3-91147db95b99).
Another option is [CodeMaid](http://visualstudiogallery.msdn.microsoft.com/en-us/76293c4d-8c16-4f4a-aee6-21f83a571496), a free and open source Visual Studio extension. It allows you to sort usings, remove usings, format document, remove/insert blank lines, remove whitespace, and quite a few more cleanups. It can run on save, solution wide, etc. Follow the link to the visual studio gallery to see more details. It also lets you conditionally enable/disable individual portions, so with it you can disable remove unused usings and do sort only if you want as you mentioned in the comments. Disclaimer: I wrote it ;)
Automatically call visual studio 2008 "sort using directives" on save?
[ "", "c#", "visual-studio", "visual-studio-2008", "code-formatting", "using-directives", "" ]
how do i go about reading data being sent almost constantly to my server. the protocol is udp. if i try to read in a while(1) loop, i dont get anything. it seems like the read will only echo once all the reading is done. so it waits till the loop is done reading which it will never be. i want the socket\_read to echo immediately when it gets the data. here is the code that doesnt work. thanks in advance. ``` <?php $sock = socket_create(AF_INET, SOCK_DGRAM, SOL_UDP); socket_bind($sock, $local, $port) or die('Could not bind to address'); //this is where the reading loop should go. while(1) { echo socket_read($sock,1024); } socket_close($sock); ?> ```
I needed to call ob\_flush();. Never even heard of it before. turns out my problem wasn't the loop, but the fact that php naturally waits till script is done before actually sending the internal buffer to the web browser. calling flush(); followed by ob\_flush(); will force php to send whatever buffer it has stored to the browser immediately. This is needed for scripts that will not stop (infinite loops) and want to echo data to the browser. Sometimes flush() doesn't work as it didn't in this case. Hope that helps.
Something like this might help: ``` do { echo socket_read($handle,1024); $status = socket_get_status($handle); } while($status['unread_bytes']); ``` OR ``` while ( $buffer = @socket_read($sock,512,PHP_NORMAL_READ) ) echo $buffer; ```
Read constant UDP stream in php
[ "", "php", "sockets", "" ]
What are the alternatives for SOAP development in C++? Which one do you prefer and is most supported/modern?
Check out **Apache Axis**. That is my all times favorite SOAP implementation. It's SOAP done right! Exists for C++ and Java. <http://ws.apache.org/axis/> And in best traditions of **[Apache Foundation](http://ws.apache.org/)**, it is **FREE** and **OPENSOURCE**. So, enjoy!
I had to make SOAP calls for a project a while ago and the only acceptable solution I found was GSOAP. <http://www.cs.fsu.edu/~engelen/soap.html> It supports both C and C++ code, although working with C++ is nicer and easier to understand. It worked ok although there was an incompatibility with our WCF web service which meant we had to manually edit the automagically generated source code.
A Good C++ Library for SOAP
[ "", "c++", "web-services", "soap", "" ]
Background: I'm creating a very simple chatroom-like ASP.NET page with C# Code-Behind. The current users/chat messages are displayed in Controls located within an AJAX Update Panel, and using a Timer - they pull information from a DB every few seconds. I'm trying to find a simple way to handle setting a User's status to "Offline" when they exit their browser as opposed to hitting the "Logoff" button. The "Offline" status is currently just a 1 char (y/n) for IsOnline. So far I have looked into window.onbeforeunload with Javascript, setting a hidden form variable with a function on this event -> Of course the trouble is, I'd still have to test this hidden form variable in my Code-Behind somewhere to do the final Server-Side DB Query, effectively setting the User offline. I may be completely obfusticating this likely simple problem! and of course I'd appreciate any completely different alternative suggestions. Thanks
I suspect you are barking up the wrong tree. Remember, it is possible for the user to suddenly lose their internet connection, their browser could crash, or switch off their computer using the big red switch. There will be cases where the server simply never hears from the browser again. The best way to do this is with a "dead man's switch." Since you said that they are pulling information from the database every few seconds, use that opportunity to store (in the database) a timestamp for the last time you heard from a given client. Every minute or so, on the server, do a query to find clients that have not polled for a couple of minutes, and set the user offline... all on the server.
Javascript cannot be reliable, because I can close my browser by abending it. A more reliable method might be to send periodic "hi I'm still alive" messages from the browser to the server, and have the server change the status when it stops receiving these messages.
Running server-side function as browser closes
[ "", "c#", "asp.net", "onbeforeunload", "" ]
I have a string in a loop and for every loop, it is filled with texts the looks like this: ``` "123 hello everybody 4" "4567 stuff is fun 67" "12368 more stuff" ``` I only want to retrieve the first numbers up to the text in the string and I, of course, do not know the length. Thanks in advance!
If the number is at the start of the string: ``` ("123 hello everybody 4").replace(/(^\d+)(.+$)/i,'$1'); //=> '123' ``` If it's somewhere in the string: ``` (" hello 123 everybody 4").replace( /(^.+)(\w\d+\w)(.+$)/i,'$2'); //=> '123' ``` And for a number between characters: ``` ("hello123everybody 4").replace( /(^.+\D)(\d+)(\D.+$)/i,'$2'); //=> '123' ``` [**addendum**] A regular expression to match all numbers in a string: ``` "4567 stuff is fun4you 67".match(/^\d+|\d+\b|\d+(?=\w)/g); //=> ["4567", "4", "67"] ``` You can map the resulting array to an array of Numbers: ``` "4567 stuff is fun4you 67" .match(/^\d+|\d+\b|\d+(?=\w)/g) .map(function (v) {return +v;}); //=> [4567, 4, 67] ``` Including floats: ``` "4567 stuff is fun4you 2.12 67" .match(/\d+\.\d+|\d+\b|\d+(?=\w)/g) .map(function (v) {return +v;}); //=> [4567, 4, 2.12, 67] ``` If the possibility exists that the string doesn't contain any number, use: ``` ( "stuff is fun" .match(/\d+\.\d+|\d+\b|\d+(?=\w)/g) || [] ) .map(function (v) {return +v;}); //=> [] ``` So, to retrieve the start or end numbers of the string `4567 stuff is fun4you 2.12 67"` ``` // start number var startingNumber = ( "4567 stuff is fun4you 2.12 67" .match(/\d+\.\d+|\d+\b|\d+(?=\w)/g) || [] ) .map(function (v) {return +v;}).shift(); //=> 4567 // end number var endingNumber = ( "4567 stuff is fun4you 2.12 67" .match(/\d+\.\d+|\d+\b|\d+(?=\w)/g) || [] ) .map(function (v) {return +v;}).pop(); //=> 67 ```
``` var str = "some text and 856 numbers 2"; var match = str.match(/\d+/); document.writeln(parseInt(match[0], 10)); ``` If the strings starts with number (maybe preceded by whitespace), simple `parseInt(str, 10)` is enough. `parseInt` will skip leading whitespace. `10` is necessary, because otherwise string like `08` will be converted to `0` (`parseInt` in most implementations consider numbers starting with `0` as octal).
Get the first integers in a string with JavaScript
[ "", "javascript", "string", "string-formatting", "" ]
I would like to determine the network usage of my application. It uses various methods for data transfer (web services, net.tcp WCF contracts, P2P contracts) so I guess I'm interested in the statistics for the running process. Something like uTorrent displays for it's total transfer rates.
Going to use IpHelperApi, I'll post some more info on how it goes. <http://www.codeproject.com/KB/IP/iphlpapi.aspx>
[Wireshark](http://www.wireshark.org/) is a very powerful network analysis tool. Is does more than you are asking for as it allows packet inspection of everything passing your network card. However, it does have some nice analysis tools so you can capture the network traffic from your application and look at its IO profile over time, filter by IP address or protocol, save snapshots, etc.
How do you determine the network transfer speed of a Windows application?
[ "", "c#", "windows", "networking", "" ]
I have a website that has over 400,000 items. Some similar, some vastly different. We want to provide a way to search these items the best way possible. After being delivered the website it was using full text indexing. The solution is basic at best, woefully inadequate at worst. So what is the best way to search these items? They are stored in a SQL Server Database (2005). Our website is designed in C# 2.0. Currently here is the process: 1. User enters value into text box. 2. We 'clean' this entry. Removing 'scary' characters that could be an attempted hack. Remove key words (and, or, etc..) 3. Pass value into a stored procedure to return results. 4. Return results.
Look at [Lucene.NET](http://lucenenet.apache.org/). I think it's a vast improvement over full-text search in SQL Server.
SQL Server Central has a nice article on creating a Google-like Full Text Search using SQL Server. Unfortunately you have to register view the full article, but registration is free and they post a lot of good information. Here is the link: <http://www.sqlservercentral.com/articles/Full-Text+Search+(2008)/64248/> Excerpt: > ... > > Google Style > > The key to a successful application is > to make it easy to use but powerful. > Google has done this with their Web > search engine. The syntax for queries > is simple and intuitive, but > full-featured. Though the basic > building blocks of a Google query are > simple you can combine them in > powerful ways. I'll begin with basic > Google query syntax and add some > additional operators to take advantage > of the power of SQL Server CONTAINS > predicate syntax. The full Google > syntax is defined in the Google > Help:Cheat Sheet at > <http://www.google.com/help/cheatsheet.html>. > > ... The article has full example code and even a link to download it. Its an interesting read even if you don't plan on implementing it.
Best way to build a search function
[ "", "c#", "sql-server", "full-text-search", "" ]
What is the real use of indexer in C#? It looks pretty confusing as I am a new c# programmer. It looks like an array of objects but it's not.
You can think of an indexer as a Property that takes a parameter. What you do with this parameter is up to you. Generally, the indexers are used where providing , well, an *index* to your object makes sense. For instance, if your object deals with collections of items, being able to access them using a simple `'[]'` syntax makes sense because it's simple to think of it as an array to which we give the position of the object we want to return. I wrote a blog entry a while ago on the aspects of [indexers using reflection](http://blog.nkadesign.com/2006/net-the-limits-of-using-reflection/). One of the examples I gave was: ``` using System; using System.Collections; public class DayPlanner { // We store our indexer values in here Hashtable _meetings = new System.Collections.Hashtable(); // First indexer public string this[DateTime date] { get { return _meetings[date] as string; } set { _meetings[date] = value; } } // Second indexer, overloads the first public string this[string datestr] { get { return this[DateTime.Parse(datestr)] as string; } set { this[DateTime.Parse(datestr)] = value; } } } ``` And then you could use it like this: ``` DayPlanner myDay = new DayPlanner(); myDay[DateTime.Parse("2006/02/03")] = "Lunch"; ... string whatNow = myDay["2006/06/26"]; ``` That's just to show you can twist the purpose of an indexer to do what you want. Doesn't mean you should though... :-)
Indexers allow instances of a class or struct to be indexed just like arrays, they are most frequently implemented in types whose primary purpose is to encapsulate an internal collection or array. A get accessor returns a value and a set accessor assigns a value: ``` public T this[int i] { get { return arr[i]; } set { arr[i] = value; } } ``` With the enums, they defined values are limited to a small set of primitive integral types (byte, sbyte, short, ushort, int, uint, long, ulong). The char type is also a integral type, but it differs from the other integral types in two ways: * There are no implicit conversions from other types to the char type. In particular, even though the sbyte, byte, and ushort types have ranges of values that are fully representable using the char type, implicit conversions from sbyte, byte, or ushort to char do not exist. * Constants of the char type must be written as character-literals or as integer-literals in combination with a cast to type char. For example, (char)10 is the same as '\x000A'. ([C# Language Specification 3.0, Section 4.1.5](http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx))
What is the use of Indexers?
[ "", "c#", "" ]
Recently I found a very surprising behavior in c#. I had a method which takes `IEnumerable<Object>` as a parameter and i was passing `IEnumerable<string>` but it's not possible. While in c# everything can be upcast to Object than why this is not possible? It's totally confusing for me. Please someone clear me on this issue.
The technical term for this is that generics are invariant in C# 3.0 and earlier. From C#4.0 onward, the cast works. What invariant means is that there is no relationship between two generic types just because their generic type *parameters* are related (i.e. are sub- or supertypes of each other). In your example, there is no typing relationship between an `IEnumerable<object>` and an `IEnumerable<string>`, just because string is a subtype of object. They're just considered two completely unrelated types, like a string and an int (they still both are subtypes of object, but everything is) There are a few workarounds and exceptions for this issue you've run into. First, you can cast each string individually to object, if you're using .NET 3.0 you can do that using the `Cast<T>()` extension method. Otherwise, you can use a foreach and put the result into a new variable of the static type you want. Second, arrays are an exception for reference type, i.e. passing in a string[] type to a method acccepting object[] types should work.
As others have pointed out, generics types are invariant. `IEnumerable<T>` could be co-variant but C# doesn't currently support specifying variants. C# 4.0 is expected to support variants so this might be supported in the future. To work around this now you can using a the LINQ extension method `Cast<object>()`. Assuming you have a method called `Foo` that takes an `IEnumerable<object>>`. You can call it like this, ``` Foo(stringEnumerable.Cast<object>()); ```
Casting from IEnumerable<Object> to IEnumerable<string>
[ "", "c#", "covariance", "contravariance", "" ]
is this allowed in java: ``` for(int i=0;i<5;i++){ final int myFinalVariable = i; } ``` The keyword of my question is `final`. Is it allowed to do a final variable that changes with every run of the loop? I was wondering this because final says that you can't change the value of the variable (calling only `myFinalVariable = i`), but i'm redefining the whole variable with `final int`. Are they two completely different variables just with the same name - with the variable from the previous run of the loop already heading down the road to the garbage collector?
Yes, it is allowed. The `final` keyword means that you can't change the value of the variable *within its scope*. For your loop example, you can think of the variable going out of scope at the bottom of the loop, then coming back into scope with a new value at the top of the loop. Assigning to the variable within the loop won't work.
You are right, for each iteration in the loop, you are creating a new variable. The variables do share the same name, but that's fine because they are not in the same scope. Next example would *not* work: ``` final int myFinalVariable = 0; for(int i=0;i<5;i++){ myFinalVariable = i; } ```
creating final variables inside a loop
[ "", "java", "final", "" ]
I'm making a simple template system. It's annoying to not to be able to keep the code in the PHP file and output it in html file... Its not nice to have this in the template: ``` <?php while ($row = mysql_fetch_array($query)) { $name = $row['forum_name']; $date = $row['forum_date']; $desc = $row['forum_description']; $lastpost = $row['forum_lastpost']; ?> <h1><?php echo $name ?></h1> <p><?php echo $desc ?></p> <?php } ?> ``` Is there some way I could keep the code in the PHP file? Thanks
I would suggest doing the query and processing in the php file, not in the template. Build an array in the php file, then let the template display it. This is how I typically do it: PHP file: ``` for ($i = 0; $row = mysql_fetch_array($query); $i++) { $forums[$i]['name'] = $row['forum_name']; $forums[$i]['date'] = $row['forum_name']; $forums[$i]['desc'] = $row['forum_description']; $forums[$i]['lastpost'] = $row['forum_lastpost']; } ``` Template file: ``` <?php foreach ($forums as $forum) { ?> <h1><?=$forum['name']?></h1> <p><?=$forum['desc']?></p> <?php } // foreach ($forums as $forum) ?> ``` An alternative syntax is using "endwhile" as glavić showed: ``` <?php foreach ($forums as $forum): ?> <h1><?=$forum['name']?></h1> <p><?=$forum['desc']?></p> <?php endforeach; ?> ```
I like to use PHP as the templating engine and use an MVC pattern. In order to keep the View and Business logic separate only a few types of PHP code are allowed in the View, which is HTML code. The allowed code is: ``` * Single functions * Alternate format If / Else / ElseIf blocks * Alternate format For loops * Alternate format Foreach loops * Alternate format Switch statements ``` PHP offers an alternative syntax for some of its control structures; namely, if, while, for, foreach, and switch. In each case, the basic form of the alternate syntax is to change the opening brace to a colon (:) and the closing brace to endif;, endwhile;, endfor;, endforeach;, or endswitch;, respectively. These alternate formats are the only formats that should be used in the View. I will concede that the alternate PHP syntax is slower (because the interpreter is jumping in and out of PHP tags). But, this generally equates to milliseconds of processing time and makes little difference with today's servers in most environments. Finally, I prefer to use shorthand PHP tags in the View. This is generally acknowledged as a bad idea because there is less server support. But, I believe it improves readability slightly (specifically when using PHP as a templating engine) and I would generally avoid a web host where I couldn't control such things. I describe this in a tiny bit more detail and have a few examples on my web pages about a template I created for web based PHP apps. You'll find that at the URL below. <http://www.joeldare.com/wiki/applate>
template and while loops
[ "", "php", "" ]
I'm trying to write a nice GUI in Swing that uses the proper Model-Delegate pattern as much as possible. I have a JComboBox that when changed, needs to update the model with the new data. To get the currently selected item, I am using: ``` fooCombo.addItemListener(new ItemListener() { public void itemStateChanged(final ItemEvent arg0) { fooChangedHandler((Foo) fooModel.getSelectedItem()); } }); ``` Which returns what the data was changed to as a nice Object. However, I can't find a way to find out the old value, so I don't know which object needs to be changed. Any ideas here?
ended up not going to the model at all but getting my object from the getItem method like so: ```` ``` public void itemStateChanged(final ItemEvent event) { if (event.getStateChange() == event.DESELECTED) { deselectedFoo = (Foo) event.getItem(); } else if (event.getStateChange() == event.SELECTED) { FooChangedHandler(deselectedFoo,(Foo) event.getItem()); } } ``` ````
``` Foo oldFoo; .... fooCombo.addItemListener(new ItemListener() { public void itemStateChanged(final ItemEvent arg0) { Foo newFoo = (Foo) fooModel.getSelectedItem(); fooChangedHandler(oldFoo, newFoo); oldFoo = newFoo; } }); ```
recognise combobox deselect when using Swing + models?
[ "", "java", "swing", "events", "model", "jcombobox", "" ]
I want to display a menu on every page that is run from a database. Using just down and dirty php thats easy but I want to integrate it with cakephp using their MVC system. Now my question is how is the best way to go about this? My thoughts are to make an element with the layout and then a component or controller for all the logic. Any Suggestions on this? Or is a Helper what i want to use? I also need to get all the data from multiple tables in the database. Is it best to do all my data collecting logic through one model? Or do most of it in the menu controller (or component) and use the models for each table? Thank you, Walter
Models should fetch and process data from the table that they are modelising, so fetch menu data for each model in that model. Components are intended to house logic shared by multiple controllers, so a menu component that is used by all your controllers sounds like a good place to put the code to fetch the menu data from the models and mash it together. A menu is typically a nested list, if this is the case with your menu too, the easiest way to output the markup for this is a recursive function (a function that calls itself) which outputs one level at a time, so rather than an element, I'd just create a helper with a menu() method in there, and call that directly from the layout.
I agree with neilcrooks answer, but would like to add a few things for clarity. Helpers and elements are pretty simple, except that helpers can be a little more robust (at least, that's how I think of 'em ;) ). So, if you use a helper, you can bind and unbind model associations on the fly -- which will allow you to grab data from your (temporarily) associated models. Personally, I like fat models and skinny controllers, so I think if I were in this situation, I would use a helper and temporarily bind the models to it. Any data that I need to fetch from the existing models would be accessed through Model1->fetchMenuPart(...) type calls. Then you can call your helper from your layout file(s).
What is the best way to create dynamic database driven menus in CakePHP?
[ "", "php", "cakephp", "" ]
How to build modular web site with Zend framework. I have pages in db, every page is represented as url. Every page has 1toN contents. Every content has controller, action and position (+other now not important columns). So, one request is one page and multiple contents (multiple actions). How can I build all actions before the output? I would like to have layout design like example bellow, where contents are put in there containers (actions are run before layout print-out). ``` <div id="left"> <?= $this->layout()->left_container ?> </div> <div id="center"> <?= $this->layout()->center_container ?> </div> <div id="right"> <?= $this->layout()->right_container ?> </div> ``` Until now I called actions from layout view, but I do not like this approach: ``` foreach ($contents as $item) { echo $this->action($item['action'], $item['controller'], null, array('content' => $item)); } ``` Thanks. **p.s.** adepretis's code is similar to my, views of my actions are run inside layout, which means that when error occurres it is printed in layout where the action is called. Is there no whey that actions are build before layout output? Another bad thing is that in every action I must run ...->setResponseSegment, I would like this to be automated. **p.s. #2** I have found answer, it is listed bellow as answer. If there is a whey I can do this easier please write it down.
I found my answer on other forum. Here is the asnwer: **MyPlugin** ``` class MyPlugin extends Zend_Controller_Plugin_Abstract { public function routeStartup(Zend_Controller_Request_Abstract $request) { $action_stack = new Zend_Controller_Action_Helper_ActionStack(); // here I will read actions from db and run it in loop, but for example few are staticly added bellow $action_stack->actionToStack('index', 'content', 'default', array('position' => 'left')); $action_stack->actionToStack('index', 'content', 'default', array('position' => 'center')); $action_stack->actionToStack('index', 'edo', 'default', array('position' => 'center')); $action_stack->actionToStack('left', 'edo', 'default', array('position' => 'left')); $action_stack->actionToStack('right', 'edo', 'default', array('position' => 'right')); } } ``` **BaseController**, that every controller extends ``` class BaseController extends Zend_Controller_Action { public function preDispatch() { $position = $this->_request->getParam('position', false); if ($position) { $this->_helper->viewRenderer->setResponseSegment($position); } } } ``` **Layout**.phtml ``` <div> <h2><u>LEFT:</u></h2> <?=$this->layout()->left?> </div> <div> <h2><u>CENTER:</u></h2> <?=$this->layout()->center?> </div> <div> <h2><u>RIGHT:</u></h2> <?=$this->layout()->right?> </div> ``` This is what I wanted, if anyone has a better solution please answer the question and I will accept his answer.
You can use the [ActionStack helper](http://framework.zend.com/manual/en/zend.controller.actionhelpers.html#zend.controller.actionhelpers.actionstack). For example: ``` class MyController_Action extends Zend_Controller_Action { function init() { /** you might not want to add to the stack if it's a XmlHttpRequest */ if(!$this->getRequest()->isXmlHttpRequest()) { $this->_helper->actionStack('left', 'somecontroller', 'somemodule'); $this->_helper->actionStack('center', 'somecontroller', 'somemodule'); $this->_helper->actionStack('right', 'somecontroller', 'somemodule'); } } class MyController extends MyController_Action { function indexAction() { // do something } } class SomecontrollerController extends MyController_Action { function leftAction() { // do something $this->_helper->viewRenderer->setResponseSegment('left_container'); } function centerAction() { // do something $this->_helper->viewRenderer->setResponseSegment('center_container'); } function rightAction() { // do something $this->_helper->viewRenderer->setResponseSegment('right_container'); } } ``` A request for */somemodule/my/index* results in executing */somemodule/somecontroller/left*. */somemodule/somecontroller/right*, */somemodule/somecontroller/center* which end up in the correspondig layout segments.
Modular web site with zend framework, stack of actions
[ "", "php", "zend-framework", "" ]
The following codes try to generate random strings over K runs. But we want the newly generated strings to be totally different with its reference string. For that I tried to use "continue" to restart the random string generation process. However it doesn't seem to work. What's wrong with my approach below? ``` #include <iostream> #include <vector> #include <fstream> #include <sstream> #include <time.h> using namespace std; // In this code we want to print new string that is entirely different with // with those in initVector template <typename T> void prn_vec(std::vector < T >&arg, string sep="") { // simple function for printing vector for (int n = 0; n < arg.size(); n++) { cout << arg[n] << sep; } } int main ( int arg_count, char *arg_vec[] ) { // This is reference string vector <string> initVec; initVec.push_back("A"); initVec.push_back("A"); initVec.push_back("A"); initVec.push_back("A"); vector <string> DNA; DNA.push_back("A"); DNA.push_back("C"); DNA.push_back("G"); DNA.push_back("T"); for (unsigned i =0; i< 10000; i++) { vector <string> newString; for(unsigned j=0; j<initVec.size(); j++) { int dnaNo = rand() % 4; string newBase = DNA[dnaNo]; string oldBase = initVec[j]; int sameCount = 0; if (newBase == oldBase) { sameCount++; } if (sameCount == initVec.size()) { continue; } newString.push_back(newBase); } cout << "Run " << i << " : "; prn_vec<string>(newString); cout << endl; } return 0; } ```
Your code looks fine on first glance, unless I am missing a big part of your requirements. Read [this](http://c-faq.com/lib/randrange.html) before you use `rand()`. Except of course, the `continue` part. What you are trying to do is see if this is the same as the `initVector` or not, right? A simple comparison would do before you push it in or print to the console. ``` int sameCount = 0; if (newBase == oldBase) { sameCount++; } // sameCount can be 1 at most, 0 otherwise // this check never return true if (sameCount == initVec.size()) { continue; } ``` The `sameCount` variable is initialized each time you create a new entry to the `newString` and goes out of scope at the closing `}` of the `for` loop. So, it will not be incremented to function as a proper check against duplicate generation. You should ideally, use a `std::set` and keep inserting in it. Duplicates are not allowed and you are saved from a lot of trouble. More on using `rand()` `srand()` and random number generation: From the comp.lang.c FAQ: > [...]the low-order bits of many random number generators are distressingly non-random If you want to keep your randome numbers in the range ``` [0, 1, ... N - 1] ``` a better method compared to the simple `rand() % N` (as advised in the link) is to use the following: ``` (int)((double)rand() / ((double)RAND_MAX + 1) * N) ``` Now, if you were to run your program, every time you will get the same set of 10000 odd random DNA strands. Turns out this is because: > It's a characteristic of most pseudo-random number generators (and a defined property of the C library rand) that they always start with the same number and go through the same sequence. from another [FAQ](http://c-faq.com/lib/srand.html) of comp.lang.c. To get different strands across runs try the following: ``` #include <iostream> #include <vector> #include <fstream> #include <sstream> #include <ctime> #include <cstdlib> using namespace std; int main ( int arg_count, char *arg_vec[] ) { // most pseudo-random number generators // always start with the same number and // go through the same sequence. // coax it to do something different! srand((unsigned int)time((time_t *)NULL)); // This is reference string string initVec("AAAA"); // the family string DNA("ACGT"); for (unsigned i =0; i< 5; i++) { string newString; for(unsigned j=0; j<initVec.size(); j++) { int dnaNo = (int)((double)rand() / ((double)RAND_MAX + 1) * 4); char newBase = DNA[dnaNo]; newString += newBase; } // ideally push in a std::set // for now keep displaying everything if (newString != initVec) { cout << "Run " << i << " : " << newString << endl; } } return 0; } ```
Your algorithm is bogus. Whatever you are trying to do, you aren't doing it, and because there's not a single comment in there, I can't really tell where you went wrong. Your inner loop: ``` for each element of initVec (4) create a random element set sameCount to 0 if random element == current element of initVec, set sameCount to 1 if sameCount == 4, do something (pointless as this never happens) add random element to newString ``` Adding to that, your "newString" isn't a string at all, but a vector of strings. So, your problem isn't even the use of `continue`, it's that your algorithm is FUBAR.
Howto Restart Loop in C++ (Finding Unique Sequence Over Random Runs)
[ "", "c++", "loops", "sequence", "" ]
I need to generate HTML forms in Java. I don't know in advance what fields are needed, those will probably be delivered in XML (i have some say over this). I could use the same input file to handle the form submission. Are there libs, techniques that deal with this problem? I can't imagine that there aren't, but i can't find a suitable solution. I looked at XForms, but it seems that there's not enough adoption from browsers. Any ideas? Much obliged. ( Context: JSR-286 compliant portlet (using Liferay atm) )
Try using XSLT to transform your XML input to your HTML output. Check this [site](http://www.xml.com/pub/a/2000/08/30/xsltandhtml/index.html) for an example for the XSLT part and [this](http://www.ling.helsinki.fi/kit/2004k/ctl257/JavaXSLT/Ch05.html) site for the JAVA-XSLT connection.
as already said, XSLT can be used to transform your input to htmlif you got an XML input. Otherwise, a template engine can be used. i had success with Velocity (from the open source project Jakarta). Regards,
Dynamic HTML Form Generation
[ "", "java", "html", "forms", "" ]
I'm working on a simple web crawler in python and I wan't to make a simple queue class, but I'm not quite sure the best way to start. I want something that holds only unique items to process, so that the crawler will only crawl each page once per script run (simply to avoid infinite looping). Can anyone give me or point me to a simple queue example that I could run off of?
I'd just use a set, it doesn't maintain order but it will help you maintain uniqueness: ``` >>> q = set([9, 8, 7, 7, 8, 5, 4, 1]) >>> q.pop() 1 >>> q.pop() 4 >>> q.pop() 5 >>> q.add(3) >>> q.add(3) >>> q.add(3) >>> q.add(3) >>> q set([3, 7, 8, 9] ```
A very simple example would be to stuff each item's URL into a dict, but as the key, not as the value. Then only process the next item if it's url is not in that dict's keys: ``` visited = {} # grab next url from somewhere if url not in visited.keys(): # process url visited[url] = 1 # or whatever, the value is unimportant # repeat with next url ``` You can get more efficient, of course, but this would be simple.
Simple unique non-priority queue system
[ "", "python", "queue", "" ]
I am running php5 on my mac osx 10.5. If I write a simple php script: ``` <?php file_get_contents('http://www.google.com'); ?> ``` And run it in the command line, I get the following error: "Warning: file\_get\_contents(<http://www.google.com>): failed to open stream: Host is down" I'm not sure if I'm missing some setting in php.ini or something. I know if I run the same script off of my server, it executes w/o warning. Any ideas as to what I'm missing here? Thanks!
Firewall or you aren't connected to the internet (or maybe you are running something like LittleSnitch which is blocking Terminal.app's access).
Check your firewall?
file_get_contents: failed to open stream: Host is down
[ "", "php", "" ]
This may be a silly question but I want the exact idea about inheritance in c#.
inheritance in C# is the same as in any other language, only syntax is different [Here a c# example](http://www.csharp-station.com/Tutorials/Lesson08.aspx)
The concept of inheritance is not unique for any type of language. However the difference lies in how inheritance works in c#. For instance you can inherit from only one base class but yet implement multiple interfaces. In order to override a method or property in a derived class you will have to declare the member as virtual in the base class. For more information you can delve into the documentation for c# inheritance [here.](http://msdn.microsoft.com/en-us/library/ms173149.aspx#)
How Inheritance can be implemented in c#?
[ "", "c#", "" ]
I feel like this is something that Google should be able to solve for me just fine, but I'm finding little to no examples that I really understand. I have this custom control called UserControlTask. I wish to add an OnHide event to it and as the name implies, I want it to be thrown when the user control is being hidden. I seem to find lot's of examples of overriding events like OnClick, but none where a totally new event is being added. All I really know is that I need to declare the EventHandler... ``` public event EventHandler Hide; ``` Then I believe add the OnHide to the attributes in my CreateChildControls method. I think that is accurate anyway. Beyond this I know nothing.
Your problem isn't adding the event (which is easy: ``` public event EventHandler Hide; // this is the function that raises the event private void OnHide() { if (Hide != null) Hide(this, new EventArgs()); } ``` Your problem is knowing when to call `OnHide()` (which raises the event) - since there is no way to know when the user hides the control (I assume you are talking about something that happens in the client side), there is no time in which you should raise this event.
You may be mixing up the methods that raise the events and the events themselves. `Control.OnClick` is a method that raises the `Control.Click` event. In subclasses overriding OnClick (and calling base.OnClick) allows processing without needing to go through a handler. On the other hand a control that composes has to use event directly.
How do I give an ASP.Net custom control a new custom event
[ "", "c#", "asp.net", "events", "" ]
I thought a foreign key meant that a single row must reference a single row, but I'm looking at some tables where this is definitely not the case. Table1 has column1 with a foreign key constraint on column2 in table2, BUT there are many records in table2 with the same value in column2. There's also non-unique index on column2. What does this mean? Does a foreign key constraint simply mean that at least one record must exist with the right values in the right columns? I thought it meant there must be exactly one such record (not sure how nulls fit in to the picture, but I'm less concerned about that at the moment). update: Apparently, this behavior is specific to MySQL, which is what I was using, but I didn't mention it in my original question.
From [MySQL documentation](http://dev.mysql.com/doc/refman/5.6/en/innodb-foreign-key-constraints.html): > InnoDB allows a foreign key constraint to reference a non-unique key. This is an InnoDB extension to standard SQL. However, there is a pratical reason to avoid foreign keys on non-unique columns of referenced table. That is, what should be the semantic of "ON DELETE CASCADE" in that case? [The documentation further advises](http://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html): > The handling of foreign key references to nonunique keys or keys that contain NULL values is not well defined (...) You are advised to use foreign keys that reference only UNIQUE (including PRIMARY) and NOT NULL keys.
Your analysis is correct; the keys don't have to be unique, and constraints will act on the set of matching rows. Not usually a useful behavior, but situations can come up where it's what you want.
Can a foreign key reference a non-unique index?
[ "", "mysql", "sql", "foreign-keys", "" ]
I'm writing some software that automatically connects a Bluetooth device using the Windows [Bluetooth API](http://msdn.microsoft.com/en-us/library/aa362932(VS.85).aspx). When it connects, Windows automatically starts installing the Bluetooth HID device driver, as expected: ![Installing Bluetooth HID drivers](https://i.stack.imgur.com/aZuTq.gif) This takes about 10-15 seconds, after which Windows displays the familar "ready for use" message: ![Hardware installed and ready for use](https://i.stack.imgur.com/Vb5Ex.gif) The problem is that `BluetoothSetServiceState()` returns as soon as the driver install *begins*, not when the device is actually ready for use. This causes some problems for my code, because it invokes a separate library for device communication as soon as it's "connected". The first few calls fail because the drivers haven't finished installing, and making those connection attempts appears to interfere with the driver installation, because if I try to use the communication library before the driver installation has finished Windows wants to restart before the device can be used. What I'm looking for is a way to hook that "ready to use" event, when driver installation has actually finished, so I don't make my communication library calls prematurely. Is there some Windows API call I can use to either register a function callback or directly polling the state of driver installation? I'm writing this in vanilla C/C++, no .NET. Thanks for your help!
You might want to have a look at [this sample code](http://msdn.microsoft.com/en-us/library/aa363432(VS.85).aspx) and [RegisterDeviceNotification](http://msdn.microsoft.com/en-us/library/aa363431(VS.85).aspx) function. I'm not sure for 100%, but it seems to work if you specify correct guid for your device class.
Here is what I would do: 1. Download [Winspector](http://www.windows-spy.com/) (or use Spy++) 2. Start up Winspector, and [begin watching for Window Messages](http://www.windows-spy.com/features/messagefilter.shtml) 3. Install your driver 4. Watch for WM's indicative of a completed driver installation I wish I could be more descriptive on #4, but I'm not familiar with the specific window message you need. [Have a look here for possible Window Messages to expect](http://msdn.microsoft.com/en-us/library/aa363480(VS.85).aspx). However, once you determine the correct window message to look for, then programmatically have your program wait for (and handle) this WM. [CodeProject has an excellent write up on how to do this in C++](http://www.codeproject.com/KB/dialog/messagehandling.aspx). Personally, [I'd prefer to do it in Delphi](http://delphi.about.com/od/windowsshellapi/a/aa020800a.htm).
Windows API: Detecting when a driver install has finished
[ "", "c++", "windows", "bluetooth", "driver", "" ]
I am allowing users to download a file from another server just by giving them the link. However, the files are always named "file.zip" when users try to download it. I was hoping I could use maybe JavaScript to rename the file for them to something more appropriate. How can I do this? Is this possible? Would appreciate any help. Thanks all ## UPDATE How about saving that file to my server and as I do this, let the users download it? Can users start downloading an un-fully downloaded file?
No its not possible, the file.zip will be in the Content-Disposition header sent by the server, there is nothing you can do in Javascript to intercept and modify it.
I'm fairly sure Javascript won't let you do this. A better option might be to send a HTTP Content-Disposition header, like so: ``` Content-Disposition,attachment; filename=foobar.zip ``` where foobar.zip is the name you wish the file to be called.
Renaming File on another server as user downloads it
[ "", "javascript", "url", "file", "save", "" ]
Why do I fail to extract an integer value into the `Num` variable? ``` #include <sstream> #include <vector> #include <iostream> using namespace std; int main() { string Digits("1 2 3"); stringstream ss(Digits); string Temp; vector<string>Tokens; while(ss >> Temp) Tokens.push_back(Temp); ss.str(Tokens[0]); int Num = 0; ss >> Num; cout << Num; //output: 0 } ```
When the stream extracts the last of the 3 digist "1 2 3" the eof state will be set. This is not cleared by the str() member,you need to do it yourself. Change your code to: ``` ss.clear(); ss.str(Tokens[0]); ```
Why are you reading into a temp `string` variable? You can just read from the stringstream into an int... ``` int main() { string Digits("1 2 3"); stringstream ss(Digits); int Temp; vector<int> Tokens; while(ss >> Temp) Tokens.push_back(Temp); } ```
Stringstream extract integer
[ "", "c++", "stringstream", "" ]
I have a problem with the boost::asio::serial\_port class reading from a GPS device (USB-Serial). Connecting the device and reading from it works fine, but when I disconnect and reconnect the device, read\_some doesn't read any bytes from the port. As boost doesn't seam to detect that the serial port is gone ( is\_open() returns true ), I periodically cancel(), close() and open( GPS\_PORT ) the device when I don't get data, resetting the port options on the way. But this doesn't help either, the input buffer stays empty. Am I missing something, or doing something wrong, or is this a bug in asio? Is there a standard way to detect that the port is gone?
It's hard to say what is the exact reason in your case, but practice shows that you often need to disable `RTS` sensitivity on your serial port. `RTS` is a pin on real `RS-232` interface that is on when a device on the other side is on. `serial_port::read_some` invokes underlying `Windows API` function that looks on this signal. As you don't have the real `RS-323` device, you need to rely on the driver emulation of this signal which may be faulty (and unfortunately often is). To disable it, invoke `serial_port::set_option(DCB)` with `RTSControl` set to `RTS_CONTROL_DISABLE`. If `close()`'ing your handle doesn't help, it may be a problem with `boost`. Source code for `close()` looks like this: ``` boost::system::error_code close(implementation_type& impl, boost::system::error_code& ec) { if (is_open(impl)) { if (!::CloseHandle(impl.handle_)) { DWORD last_error = ::GetLastError(); ec = boost::system::error_code(last_error, boost::asio::error::get_system_category()); return ec; } impl.handle_ = INVALID_HANDLE_VALUE; impl.safe_cancellation_thread_id_ = 0; } ec = boost::system::error_code(); return ec; } ``` , i. e. if `CloseHandle()` fails for some reason (or hangs), the internal handle value is not beign assigned to `INVALID_HANDLE_VALUE` and `is_open()` will always return `true`. To work around this, check `is_open()` right after `close()`'ing, and if it returns `true`, destroy whole instance of `boost::asio::serial_port` and create it again.
Normally you should get an exception of type `boost::system::system_error` when `read_some` cannot ready anymore. Try using `read` instead, maybe it returns an error and doesn't just return. You could also try the async methods; in this case the handler should get an error object when the device was disconnected. Alterantively you could get the handle to the port using the `native()` function and call ClearCommError() on that. It might return the error.
boost::asio::serial_port reading after reconnecting Device
[ "", "c++", "boost", "serial-port", "boost-asio", "" ]
I have this html. ``` <a class="link" href="www.website.com?id=233253">test1</a> <a class="link" href="www.website.com?id=456456">test2</a> ``` How can I hide one of these links by using the href attribute, and just the last numbers (233253), to hide the link with this href attribute and the class "link"? This is not a working code, just something i put together to explain it better. getElementsByTagName('a').class('link').href="\*233253" Update: Unfortunately it has to be pure javascript, not using a library, and it has to work on IE6. Update2: I don't have access to the html
``` <html> <head> <script type="text/javascript"> function hideLinks(className, ids) { var links = document.getElementsByTagName("a"); var max = links.length; for (var i=0; i<max; i++) { var link = new RegExp("(\s*)"+ className +"(\s*)"); var isLink = link.test(links[i].className); if (isLink) { for (var j=0; j<ids.length; j++) { var regexp = new RegExp(ids[j] + "$"); var hasId = regexp.test(links[i].href); if (hasId) { links[i].style.display = "none"; } } } } } window.onload = function() { hideLinks("link", [233253]); } </script> </head> <body> <a class="link" href="www.website.com?id=233253">test1</a> <a class="link" href="www.website.com?id=456456">test2</a> </body> </html> ``` **Edit**: I posted a new version after reading your comment about encapsulating the functionality inside a function. This one should work just as well as the previous version.
[**edit**]: code was somewhat sloppy, should work now. Including the split method (see comments). Loop through the a elements, check href and apply the hiding. Like this: ``` var refs = document.getElementsByTagName('a'); for (var i=0;i<refs.length;i++) { if ( refs[i].href && refs[i].href.replace(/(\d+$)/,'$1').match('[your value to match]') ) { refs[i].className = refs[i].className.replace(/link/i,''); refs[i].style.display = 'none'; } } ``` OR ``` for (var i=0;i<refs.length;i++) { var hs = refs[i].href.split(/=/)[1]; if ( hs.match([your value to match]) ) { refs[i].className = refs[i].className.replace(/link/i,''); refs[i].style.display = 'none'; } } ```
Hide a link with a specific class and attribute
[ "", "javascript", "html", "getelementbyid", "" ]
I have a tool which I have written in python and generally should be run as a daemon. What are the best practices for packaging this tool for distribution, particularly how should settings files and the daemon executable/script be handled? Relatedly are there any common tools for setting up the daemon for running on boot as appropriate for the given platform (i.e. *init* scripts on linux, services on windows, *launchd* on os x)?
To answer one part of your question, there are no tools I know of that will do daemon setup portably even across Linux systems let alone Windows or Mac OS X. Most Linux distributions seem to be using `start-stop-daemon` within init scripts now, but you're still going to have minor difference in filesystem layout and big differences in packaging. Using autotools/configure, or distutils/easy\_install if your project is all Python, will go a long way to making it easier to build packages for different Linux/BSD distributions. Windows is a whole different game and will require [Mark Hammond's win32](http://starship.python.net/crew/mhammond/) extensions and maybe [Tim Golden's WMI](http://timgolden.me.uk/python/wmi.html) extensions. I don't know Launchd except that "none of the above" are relevant. For tips on daemonizing Python scripts, I would look to Python apps that are actually doing it in the real world, for example inside Twisted.
The best tool I found for helping with init.d scripts is "start-stop-daemon". It will run any application, monitor run/pid files, create them when necessary, provide ways to stop the daemon, set process user/group ids, and can even background your process. For example, this is a script which can start/stop a wsgi server: ``` #! /bin/bash case "$1" in start) echo "Starting server" # Activate the virtual environment . /home/ali/wer-gcms/g-env/bin/activate # Run start-stop-daemon, the $DAEMON variable contains the path to the # application to run start-stop-daemon --start --pidfile $WSGI_PIDFILE \ --user www-data --group www-data \ --chuid www-data \ --exec "$DAEMON" ;; stop) echo "Stopping WSGI Application" # Start-stop daemon can also stop the application by sending sig 15 # (configurable) to the process id contained in the run/pid file start-stop-daemon --stop --pidfile $WSGI_PIDFILE --verbose ;; *) # Refuse to do other stuff echo "Usage: /etc/init.d/wsgi-application.sh {start|stop}" exit 1 ;; esac exit 0 ``` You can also see there an example of how to use it with a virtualenv, which I would always recommend.
Python Daemon Packaging Best Practices
[ "", "python", "packaging", "setuptools", "distutils", "" ]
In my project we have a base exception. For handling showing error dialogs, log and such. Im looking for a way to handle all derived classes of that exception, I thought this would work: ``` try { main_loop(); } catch (const MyExceptionBase* e) { handle_error(e); } ``` As every child instance thrown could be represented by a pointer to its parent. But no, when exceptions are thrown now, its an unhandled exception. Why is this? Do c++ only throw exceptions as references? Thereby rendering my catch block useless? But then why does this even compile in the first place? The only other way I can think of is this: ``` try { main_loop(); } catch (const ExceptionA& e) { handle_error(e); } catch (const ExceptionB& e) { handle_error(e); } catch (const ExceptionC& e) { handle_error(e); } ``` Which seems kinda ugly. What is the correct way to do this? Dont have a base exception class? Or can it be solved in the way I want? Ps: What `handle_error()` does is simply make use of the base class function `display_message_box()` and cleanly shutdown the program.
Just mix the two approaches: use the base class, and use a reference. ``` try { main_loop(); } catch (const MyExceptionBase& e) { handle_error(e); } ``` BTW C++ can catch pointers, if you throw them. It's not advisable though.
Your best bet is to catch the base reference. But please do so by reference, not by pointer. Example ``` try { main_loop(); } catch (const MyExceptionBase& e) { handle_error(e); } ``` The problem with catching an exception by pointer is that it must be thrown by pointer. This means that it will be created with new. ``` throw new ExceptionA(); ``` This leaves a rather large problem because it must be deleted at some point or you have a memory leak. Who should be responsible for deleting this exception? It's generally difficult to get this right which is why most people catch by reference. In general in C++ you should ... > Catch by reference, throw by value
Catching c++ base exceptions
[ "", "c++", "exception", "try-catch", "" ]
I have a question concerning unit testing. Let's say that I have several classes that inherit behaviour from a parent class. I don't want to test all the child classes for this behaviour. Instead I would test the parent class. However, I should also provide a test proving that the behaviour is available in the child classes. Do you think something like Assert.IsTrue(new ChildClass() is ParentClass) makes sense?
If you're using a state-of-the-art unit-testing framework, I don't understand the statement > I don't want to test all the child classes for this behaviour. Your unit tests (written against an instance of the parent class) should work unchanged if you hand them an instance of a child class, ***provided*** that your child class hasn't overridden some aspect of the parent's behavior in a way that breaks the contract on the inherited methods. And that's exactly what you need to be testing, isn't it? If you're concerned about the time it takes to run the tests, I'd double-check to make sure that your tests are partitioned such that you can selectively run tests based on what you're actively working on (but still run the full portfolio periodically to catch unintended dependencies.)
make your tests inherit from a base class test, something [very]roughly like this. ``` public class MyBaseClass { public virtual void DoStuff() { } public virtual void DoOtherStuff() { } } public class MySubClass : MyBaseClass { public override void DoOtherStuff() { // different to to base } } public abstract class TestOfBaseClass { protected abstract MyBaseClass classUnderTest { get; } [TestMethod] public void TestDoStuff() { classUnderTest.DoStuff(); Assert.StuffWasDone(); } } [TestClass] public class WhenSubclassDoesStuff : TestOfBaseClass { protected override MyBaseClass classUnderTest { get { return new MySubClass(); } } [TestMethod] public void ShoudDoOtherStuff() { classUnderTest.DoOtherStuff(); Assert.OtherStuffDone(); } } ``` most of the popular test frameworks will run the test method in the base test when running the subclass tests. or maybe have a look at something like <https://github.com/gregoryyoung/grensesnitt>
Unit testing inheritance
[ "", "c#", "unit-testing", "tdd", "" ]
Is there a standard function to check that a specified directory is valid? The reason I ask is that I am receiving an absolute directory string and filename from a user and I want to sanity check the location to check that it is valid.
For a file ``` File.Exists(string) ``` For a Directory ``` Directory.Exists(string) ``` *NOTE:* If you are reusing an object you should consider using the FileInfo class vs the static File class. The static methods of the File class does a possible unnecessary security check each time. [FileInfo](http://msdn.microsoft.com/en-us/library/system.io.fileinfo.aspx) - [DirectoryInfo](http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx) - [File](http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx) - [Directory](http://msdn.microsoft.com/en-us/library/system.io.directory.exists.aspx) ``` FileInfo fi = new FileInfo(fName); if (fi.Exists) //Do stuff ``` OR ``` DirectoryInfo di = new DirectoryInfo(fName); if (di.Exists) //Do stuff ```
``` if(System.IO.File.Exists(fileOrDirectoryPath)) { //do stuff } ``` This should do the trick!
C# check that a file destination is valid
[ "", "c#", "validation", "io", "" ]
Can I use String.Format() to pad a certain string with arbitrary characters? ``` Console.WriteLine("->{0,18}<-", "hello"); Console.WriteLine("->{0,-18}<-", "hello"); returns -> hello<- ->hello <- ``` I now want the spaces to be an arbitrary character. The reason I cannot do it with padLeft or padRight is because I want to be able to construct the format string at a different place/time then the formatting is actually executed. **--EDIT--** Seen that there doesn't seem to be an existing solution to my problem I came up with this (after [Think Before Coding's suggestion](https://stackoverflow.com/questions/541098/pad-left-or-right-with-string-format-not-padleft-or-padright-with-arbitrary-str/541210#541210)) **--EDIT2--** I needed some more complex scenarios so I went for [Think Before Coding's second suggestion](https://stackoverflow.com/questions/541098/pad-left-or-right-with-string-format-not-padleft-or-padright-with-arbitrary-str/541323#541323) ``` [TestMethod] public void PaddedStringShouldPadLeft() { string result = string.Format(new PaddedStringFormatInfo(), "->{0:20:x} {1}<-", "Hello", "World"); string expected = "->xxxxxxxxxxxxxxxHello World<-"; Assert.AreEqual(result, expected); } [TestMethod] public void PaddedStringShouldPadRight() { string result = string.Format(new PaddedStringFormatInfo(), "->{0} {1:-20:x}<-", "Hello", "World"); string expected = "->Hello Worldxxxxxxxxxxxxxxx<-"; Assert.AreEqual(result, expected); } [TestMethod] public void ShouldPadLeftThenRight() { string result = string.Format(new PaddedStringFormatInfo(), "->{0:10:L} {1:-10:R}<-", "Hello", "World"); string expected = "->LLLLLHello WorldRRRRR<-"; Assert.AreEqual(result, expected); } [TestMethod] public void ShouldFormatRegular() { string result = string.Format(new PaddedStringFormatInfo(), "->{0} {1:-10}<-", "Hello", "World"); string expected = string.Format("->{0} {1,-10}<-", "Hello", "World"); Assert.AreEqual(expected, result); } ``` Because the code was a bit too much to put in a post, I moved it to github as a gist: <http://gist.github.com/533905#file_padded_string_format_info> There people can easily branch it and whatever :)
There is another solution. Implement `IFormatProvider` to return a `ICustomFormatter` that will be passed to string.Format : ``` public class StringPadder : ICustomFormatter { public string Format(string format, object arg, IFormatProvider formatProvider) { // do padding for string arguments // use default for others } } public class StringPadderFormatProvider : IFormatProvider { public object GetFormat(Type formatType) { if (formatType == typeof(ICustomFormatter)) return new StringPadder(); return null; } public static readonly IFormatProvider Default = new StringPadderFormatProvider(); } ``` Then you can use it like this : ``` string.Format(StringPadderFormatProvider.Default, "->{0:x20}<-", "Hello"); ```
You could encapsulate the string in a struct that implements IFormattable ``` public struct PaddedString : IFormattable { private string value; public PaddedString(string value) { this.value = value; } public string ToString(string format, IFormatProvider formatProvider) { //... use the format to pad value } public static explicit operator PaddedString(string value) { return new PaddedString(value); } } ``` Then use this like that : ``` string.Format("->{0:x20}<-", (PaddedString)"Hello"); ``` result: ``` "->xxxxxxxxxxxxxxxHello<-" ```
Pad left or right with string.format (not padleft or padright) with arbitrary string
[ "", "c#", "formatting", "padding", "string.format", "" ]
I'm trying to jury-rig the [Amazon S3 python library](http://developer.amazonwebservices.com/connect/entry.jspa?externalID=134) to allow chunked handling of large files. Right now it does a "self.body = http\_response.read()", so if you have a 3G file you're going to read the entire thing into memory before getting any control over it. My current approach is to try to keep the interface for the library the same but provide a callback after reading each chunk of data. Something like the following: ``` data = [] while True: chunk = http_response.read(CHUNKSIZE) if not chunk: break if callback: callback(chunk) data.append(chunk) ``` Now I need to do something like: ``` self.body = ''.join(data) ``` Is *join* the right way to do this or is there another (better) way of putting all the chunks together?
hm - what problem are you trying to solve? I suspect the answer depends on what you are trying to do with the data. Since in general you don't want a whole 3Gb file in memory, I'd not store the chunks in an array, but iterate over the http\_response and write it straight to disk, in a temporary or persistent file using the normal write() method on an appropriate file handle. if you do want two copies of the data in memory, your method will require be at least 6Gb for your hypothetical 3Gb file, which presumably is significant for most hardware. I know that array join methods are fast and all that, but since this is a really ram-constrained process maybe you want to find some way of doing it better? StringIO (<http://docs.python.org/library/stringio.html>) creates string objects that can be appended to in memory; the pure python one, since it has to work with immutable strings, just uses your array join trick internally, but the c-based cStringIO might actually append to a memory buffer internall. I don't have its source code to hand, so that would bear checking. if you do wish to do some kind of analysis on the data and really wish to keep in in memory with minimal overhead, you might want to consider some of the byte array objets from Numeric/NumPy as an alternative to StringIO. they are high-performance code optimised for large arrays and might be what you need. as a useful example, for a general-purpose file-handling object which has memory-efficient iterator-friendly approach you might want to check out the django File obeject chunk handling code: <http://code.djangoproject.com/browser/django/trunk/django/core/files/base.py>.
''join() is the best method for joining chunks of data. The alternative boils down to repeated concatenation, which is O(n\*\*2) due to the immutability of strings and the need to create more at every concatenation. Given, this repeated concatenation is optimized by recent versions of CPython if used with += to become O(n), but that optimization only gives it a rough equivalent to ''.join() anyway, which is explicitly O(n) over the number of bytes.
Python: efficiently join chunks of bytes into one big chunk?
[ "", "python", "amazon-s3", "" ]
Given that all the primitive data types and objects have memory allocated, it is intuitively easy to imagine the pointers to these types. But where exactly do function pointers point to? Given that instructions are converted into machine code and reside in memory, should we consider they point to the memory location corresponding to the start of the functions instructions? We face many errors in pointers due to illegal memory access. Is it the case that errors occur when function pointers point to data memory instead of instruction memory?
Function pointer also point into memory, the only difference is that there is executable code at that memory location instead of data. On many platforms if you try to execute data (e.g. regular memory) you'll crash or cause an exception. This is known as Data Execution Prevention - a security measure to prevent applications inadvertently running dodgy code that may be placed there by malware.
A function pointer contains the address of a function -- whatever that means for a given system. You can use it to call the function indirectly, you can assign and compare function pointer values. You can also convert a function pointer to another pointer-to-function type, and so forth. The most straightforward way for a compiler to implement a function pointer is as the memory address of the function, and most compilers do it that way, but the language standard doesn't specify that. Some systems (I think IBM's AS/400 is an example) store additional information in function pointers. A compiler could implement function pointers as integer indices into a table of descriptors, as long as the required semantics are implemented properly. It's not possible to dereference a function pointer. A function call requires a pointer, not a function name, as its prefix expression; if you use a function name, that name is implicitly converted to a pointer (as far as the language is concerned; the generated machine code might be different). So there's no portable way for a program to detect whether function pointers actually contain memory addresses or not. Non-portably, given a function `func`, you can do something like: ``` printf("Address of func is %p\n", (void*)func); ``` and you'll *probably* see something that looks like a human-readable representation of a memory address. But strictly speaking, the behavior of the conversion of the function pointer to `void*` is not defined by the language, and it might not work on some systems. You *might* even be able to convert a function pointer to `unsigned char*` and examine the function's machine code, but goes far beyond anything defined by the C standard. It's best to treat function pointers as opaque values that refer to particular functions in some unspecified manner.
Where exactly do function pointers point?
[ "", "c++", "c", "pointers", "function-pointers", "" ]
How do you bind a DropDownlist DataText or DataValue field from a object. When the object in question is at a second level, e.g. the object to bind is not in the first level of the returned object Users.ContactDetails.Telephone, as the code below doesn't work: ``` ddl.DataSource = dal.dal_Users.GetAllUsers(); ddl.DataTextField = "Telephone"; ``` I have tried a range of ideas but can't seem to find any information on if this can be done or not.
**EDIT:** I got enough feedback about this topic that I felt it was worthy of a [blog post](http://toranbillups.com/blog/archive/2009/06/24/Working-with-a-select-box-using-Model-View-Presenter) One approach that I took when binding domain objects to ddl controls is to inherit from a base class that has an overload in the constr to allow for a text/value only "subset" of the original. The code below is used in a Model View Presenter Or Model View ViewModel implementation that abstracts out the ddl control so you can push any UI on the top of this business code. **below is an example of how I bind a ddl with a collection of user objects, and set the selected based on the related object (unit of work)** ``` public void PopulateUserDDL(UnitOfWork UnitOfWorkObject) { List<User> UserCollection = mUserService.GetUserCollection(); //get a collection of objects to bind this ddl List<ILookupDTO> UserLookupDTO = new List<ILookupDTO>(); UserLookupDTO.Add(new User(" ", "0")); //insert a blank row ... if you are into that type of thing foreach (var User in UserCollection) { UserLookupDTO.Add(new User(User.FullName, User.ID.ToString())); } LookupCollection LookupCollectionObject = new LookupCollection(UserLookupDTO); LookupCollectionObject.BindTo(mView.UserList); if (UnitOfWorkObject == null) { return; } if (UserCollection == null) { return; } for (i = 0; i <= UserCollection.Count - 1; i++) { if (UserCollection(i).ID == UnitOfWorkObject.User.ID) { LookupCollectionObject.SelectedIndex = (i + 1); //because we start at 0 instead of 1 (we inserted the blank row above) break; } } } ``` **below is what the overload will look like in your user object** ``` /// <summary> /// This constr is used when you want to create a new Lookup Collection of ILookupDTO /// </summary> /// <param name="txt">The text that will show up for the user in the lookup collection</param> /// <param name="val">The value that will be attached to the item in the lookup collection</param> /// <remarks></remarks> public New(string txt, string val) : base(txt, val) { } ``` **below will be needed in the base class for any Entity/Domain Objects/DTO/etc** ``` public New(string txt, string val) { mText = txt; mValue = val; } ``` **this base class should also implement ILookupDTO - because this will force you to make public a Text and Value property that are used by the user object in this example** ``` public interface ILookupDTO { string Text { get; set; } string Value { get; set; } } ``` **the below is the def for LookupCollection used in the bind method at the top of this answer** ``` public class LookupCollection { private readonly IEnumerable<ILookupDTO> dtos; private ILookupList mList; public LookupCollection(IEnumerable<ILookupDTO> dtos) { this.dtos = dtos; } public void BindTo(ILookupList list) { mList = list; mList.Clear(); foreach (ILookupDTO dto in dtos) { mList.Add(dto); } } public int SelectedIndex { get { return mList.SelectedIndex; } set { mList.SelectedIndex = value; } } public string SelectedValue { get { return mList.SelectedValue; } set { mList.SelectedValue = value; } } } ``` **below is the interface for ILookupList - used in the implementation of each UI specific control (see the web and wpf examples below)** ``` public interface ILookupList { void Add(ILookupDTO dto); void Clear(); int Count(); int SelectedIndex { get; set; } string SelectedValue { get; set; } } ``` **now in your code-behind you will need to do something like this in your read only property for the view** Return New WebLookupList(ddlUsers) **here is an implementation for a web specific ddl** ``` public class WebLookupList : ILookupList { private readonly ListControl listControl; public WebLookupList(ListControl listControl) { this.listControl = listControl; } public void Clear() { listControl.Items.Clear(); } public void Add(Interfaces.ILookupDTO dto) { listControl.Items.Add(new ListItem(dto.Text, dto.Value)); } public int Count() { return listControl.Items.Count; } public int SelectedIndex { get { return listControl.SelectedIndex; } set { listControl.SelectedIndex = value; } } public string SelectedValue { get { return listControl.SelectedValue; } set { listControl.SelectedValue = value; } } } ``` **here is the implementation for a WPF specific ddl** **if using wpf your read only property for the view would look like - Return New WPFLookupList(ddlUsers)** ``` public class WPFLookupList : ILookupList { private readonly ComboBox combobox; public WPFLookupList(ComboBox combobox) { this.combobox = combobox; } public void Add(Interfaces.ILookupDTO dto) { ComboBoxItem item = new ComboBoxItem(); item.Content = dto.Text; item.Tag = dto.Value; combobox.Items.Add(item); } public void Clear() { combobox.Items.Clear(); } public int Count() { return combobox.Items.Count; } public int SelectedIndex { get { return combobox.SelectedIndex; } set { combobox.SelectedIndex = value; } } public string SelectedValue { get { return combobox.SelectedValue.Tag; } set { combobox.SelectedValue.Tag = value; } } } ``` **You only need 1 of these at a time, but I thought showing both would help make clear what we are abstracting away** Because this was such a huge answer, I could post a sample project for download showing this in action if requested - let me know
If you are using C# 3 then you can use the `ConvertAll<>` etension method to create a new anonymous type that moves the inner property up to the top level. Try something like this: ``` IEnumerable<User> users = dal.dal_Users.GetAllUsers(); ddl.DataSource = users.ConvertAll(u => new { Value = u.Name, Telephone = u.ContactDetails.Telephone }); ddl.DataTextField = "Telephone"; ```
DropDownList from object
[ "", "c#", ".net", "drop-down-menu", "" ]
I am trying to organize some modules for my own use. I have something like this: ``` lib/ __init__.py settings.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py ``` In `lib/__init__.py`, I want to define some classes to be used if I import lib. However, I can't seem to figure it out without separating the classes into files, and import them in`__init__.py`. Rather than say: ``` lib/ __init__.py settings.py helperclass.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py from lib.settings import Values from lib.helperclass import Helper ``` I want something like this: ``` lib/ __init__.py #Helper defined in this file settings.py foo/ __init__.py someobject.py bar/ __init__.py somethingelse.py from lib.settings import Values from lib import Helper ``` Is it possible, or do I have to separate the class into another file? ## EDIT OK, if I import lib from another script, I can access the Helper class. How can I access the Helper class from settings.py? The example [here](http://docs.python.org/tutorial/modules.html) describes Intra-Package References. I quote "submodules often need to refer to each other". In my case, the lib.settings.py needs the Helper and lib.foo.someobject need access to Helper, so where should I define the Helper class?
1. '`lib/`'s parent directory must be in `sys.path`. 2. Your '`lib/__init__.py`' might look like this: ``` from . import settings # or just 'import settings' on old Python versions class Helper(object): pass ``` Then the following example should work: ``` from lib.settings import Values from lib import Helper ``` ### Answer to the edited version of the question: `__init__.py` defines how your package looks from outside. If you need to use `Helper` in `settings.py` then define `Helper` in a different file e.g., '`lib/helper.py`'. ``` . | `-- import_submodule.py `-- lib |-- __init__.py |-- foo | |-- __init__.py | `-- someobject.py |-- helper.py `-- settings.py 2 directories, 6 files ``` The command: ``` $ python import_submodule.py ``` Output: ``` settings helper Helper in lib.settings someobject Helper in lib.foo.someobject # ./import_submodule.py import fnmatch, os from lib.settings import Values from lib import Helper print for root, dirs, files in os.walk('.'): for f in fnmatch.filter(files, '*.py'): print "# %s/%s" % (os.path.basename(root), f) print open(os.path.join(root, f)).read() print # lib/helper.py print 'helper' class Helper(object): def __init__(self, module_name): print "Helper in", module_name # lib/settings.py print "settings" import helper class Values(object): pass helper.Helper(__name__) # lib/__init__.py #from __future__ import absolute_import import settings, foo.someobject, helper Helper = helper.Helper # foo/someobject.py print "someobject" from .. import helper helper.Helper(__name__) # foo/__init__.py import someobject ```
If `lib/__init__.py` defines the Helper class then in settings.py you can use: ``` from . import Helper ``` This works because . is the current directory, and acts as a synonym for the lib package from the point of view of the settings module. Note that it is not necessary to export Helper via `__all__`. (Confirmed with python 2.7.10, running on Windows.)
How to import classes defined in __init__.py
[ "", "python", "package", "" ]
When hovering over a span I would like to get the offsetLeft and offsetTop values so I can make something hover near it. When I do this I get 0 for both values. What is a better way to tackle this? I am using jQuery. Assume I am starting with (looped by server-side scripting): ``` <span onmouseover="hoverNearMe(this.offsetLeft,this.offsetTop);">some username</span><br /> ``` **FINAL THOUGHTS:** I'm giving the the answer rep out based on "code leverage"/DRY. The longer function you could use over and over in your own js library. The second short answer however is 100% correct too.
I think you should be able to do this: **HTML** ``` <span class="get-close-to">some username</span><br /> ``` **jQuery** ``` jQuery('.get-close-to').hover(function() { var offset = jQuery(this).css('offset'); alert( 'Left: ' + offset.left + '\nTop: ' + offset.top ); }); ```
`$(this).offset().left` and `$(this).offset().top`
JavaScript/jQuery - offsetLeft and offsetTop
[ "", "javascript", "jquery", "" ]
I am asking this from a language design point of view. So I am trying to find out 1. What is the rationale for the behavior of `this`? 2. To what degree the behavior of `this` was a mistake, or could be improved upon? --- To clarify why I'm uneasy about `this`, consider this example: ``` var a = {}; a.f = function(){ return this; } var f = a.f; // f() != a.f() ``` Note how easily the object to which `f()` belong is lost: separated from `a`, `this` becomes the global object (`window` for browsers). Now consider: ``` var newA = function(){ var self = {}; self.f = function(){ return self; } return self; } var a = newA(); var f = a.f; // f() == a.f() ! ``` Without using `this` at all, we are able to establish and maintain the object context regardless of where or how the method is used. I can't help but think that, with the power that closures provide, `this` becomes superfluous, and perhaps even a little dangerous... I'm not on some vendetta against `this`, or looking to start an argument; I'm merely trying to better understand it. I do appreciate that 'this' can be useful, but recognize that [it can be confusing](http://groups.google.com/group/comp.lang.javascript/browse_thread/thread/c95c2d8eb232e466#dad2785d7263e699) as well... Certainly confusing to beginners, and perhaps to experts as well in sufficiently obscure cases. And yet, it remains a heavily-used and seemingly well-respected part of the language, in a time when other core aspects of the language seem fair game for shunning (i.e., Crockford and `with` or `new`). What am I missing then, that makes `this` indispensable?
You seem to be expecting this to behave as it does in certain OO languages, where it always refers to the object a method belongs to. But in JavaScript, a *function* can be attached to multiple objects, or no object at all. In your example, you've written a function intended to be used in the context of *one specific object*... But nothing prevents me from taking that function and attaching it to any other object. That's just the nature of the language - functions are first-class, object membership is optional. Therefore, *this* refers to the context in which a function is called. Right now, that's either an arbitrary object (specified via `.`, `.apply`, or `.call()`) or the global object. In future versions of the language, it will refer to the context in which the function was defined: the global object for global functions, the outer `this` for inner functions; you can view this as a correction of a design flaw, as in practice being able to refer to the global object using this was not particularly useful.
I don't think making "this" unbound was a mistake. It can sometimes be confusing at first, but there are good reasons for the way it is. The first one that comes to mind is that, since JavaScript is not a class based language, functions are not associated with any specific class, so there's not a consistent way to automatically bind "this" to the correct object instance. For example, ``` function Person(first, last, age) { this.firstName = first; this.lastName = last; this.age = age; } Person.prototype.getFullName = function() { return this.firstName + " " + this.lastName; }; ``` "this" needs to refer to a Person object, but the function assigned to Person.prototype.getName doesn't have any way of knowing how it's going to be used, so "this" needs to be bound to whatever object it is called on. Where this causes a problem, is when you have nested functions. ``` // This is a really contrived example, but I can't think of anything better Person.prototype.getInfo = function() { // get name as "Last, First" function getNameLastFirst() { // oops. "this" is the global object, *not* the Person return this.lastName + ", " + this.firstName; } // expect something like "Crumley, Matthew: Age 25", // but you get "undefined, undefined: Age 25" return getNameLastFirst() + ": Age " + this.age; }; ``` The syntax [artificialidiot](https://stackoverflow.com/questions/541167/what-are-the-good-and-bad-points-of-the-this-keyword-in-javascript/541304#541304) suggested would be convenient, but it's pretty easy to bind "this" to a specific object using apply: ``` function bind(func, obj) { return function() { return func.apply(obj, arguments); }; } Person.prototype.getInfo = function() { // get name as "Last, First" var getNameLastFirst = bind(function () { return this.lastName + ", " + this.firstName; }, this); return getNameLastFirst() + ": Age " + this.age; }; ``` or the more "traditional" method using closures: ``` Person.prototype.getInfo = function() { var self = this; // get name as "Last, First" function getNameLastFirst() { return self.lastName + ", " + self.firstName; } return getNameLastFirst() + ": Age " + this.age; }; ```
What is the rationale for the behavior of the 'this' keyword in JavaScript?
[ "", "javascript", "language-design", "" ]
Could anyone explain to my why this is not working? In the database we have Employees with an IdEmployee column. We also have some tables with foreign keys to that one. Say we have something like this: ``` var employee = dataContext.Employees.First(<some predicate>); var someEntity = dataContext.SomeEntities.First(<some predicate>); ``` Why does this not work: ``` var something = someEntity.SomeThings.First(t => t.Employee == employee); ``` while this does: ``` var something = someEntity.SomeThings.First(t => t.IdEmployee == employee.IdEmployee); ``` I don't get it... Isn't the first version supposed to work? The Employee entity is from the same datacontext...
It is a little bit tricky to know for sure when you have used names like `SomeThings` and `someEntity`, but what I believe is happening is that when you're looking at `someEntity.SomeThings`, `SomeThings` is a collection of `Employee` entities. Thus, the `t` in your lambda expression will refer to an `Employee` object, giving you the ability to compare their properties. Try the following ``` var something = someEntity.SomeThings.First(t => t.Equals(employee)); ``` and see if that works better. EDIT: Actually, the `.Equals()` syntax is better than the `==` I first proposed... --- EDIT2: As Sessiz Saas proposes, it is probably because of lazy loading. An alternate way of loading the employee objects is provided below: ``` var myThings = dataContext.Things.Include("employee"); ``` However, remember that this could cause extra (and unnecessary, as you are able to do the job anyway) data calls.
Edit : the preceding explanation is wrong since 'it works on my machine' : ``` var contract = dataContext.Contracts.First(); var room = dataContext.Rooms.First(r => r.Contract == contract); ``` something must be broken in your association between your classes. You can get the executed command by using ``` var command = dataContext.GetCommand( dataContext.Rooms.Where(r => r.Contract == contract)) .CommandText; ``` The resulting command text is : ``` SELECT ... FROM [Rooms] AS [t0] WHERE [t0].[ContractId] = @p0 ``` So we can see that the primary key is found from the entity type... --- > Isn't the first version supposed to > work? The Employee entity is from the > same datacontext... Yes but the lambda expression is converted to SQL script and it seems that the linq Sql script builder doesn't try to find the entity key to generate the request. The linq to Sql command builder use the lambda content as an Expression<> tree to build the query text. To perform this operation it expect the lambda to contain expressions referencing entities properties. The problem here seems to be that it references the entities themselve and not there properties. The following query ``` var something = someEntity.SomeThings .First(t => t.IdEmployee == employee.IdEmployee); ``` produces Sql that will be something like ``` SELECT ... FROM SomThings WHERE IdEmployee = @idEmployee ``` The table columns are found using the properties names in the lambda. In the other case, there is no property name...
C#: Comparing two Linq2Sql entities not working?
[ "", "c#", "linq-to-sql", "" ]
This [earlier SO question](https://stackoverflow.com/questions/163162/can-you-call-directory-getfiles-with-multiple-filters) talks about how to retrieve all files in a directory tree that match one of multiple extensions. eg. Retrieve all files within C:\ and all subdirectories, matching \*.log, \*.txt, \*.dat. The accepted answer was this: ``` var files = Directory.GetFiles("C:\\path", "*.*", SearchOption.AllDirectories) .Where(s => s.EndsWith(".mp3") || s.EndsWith(".jpg")); ``` This strikes me as being quite inefficient. If you were searching on a directory tree that contains thousands of files (it uses SearchOption.AllDirectories), every single file in the specified directory tree is loaded into memory, and only then are mismatches removed. (Reminds me of the "paging" offered by ASP.NET datagrids.) Unfortunately the standard System.IO.DirectoryInfo.GetFiles method only accepts one filter at a time. It could be just my lack of Linq knowledge, is it actually inefficient in the way I mention? Secondly, is there a more efficient way to do it both with and without Linq (without resorting to multiple calls to GetFiles)?
I shared your problem and I found the solution in Matthew Podwysocki's [excellent post](http://codebetter.com/blogs/matthew.podwysocki/archive/2008/10/16/functional-net-fighting-friction-in-the-bcl-with-directory-getfiles.aspx) at [codebetter.com](http://codebetter.com). He implemented a solution using native methods that allows you to provide a predicate into his GetFiles implementation. Additionally he implemented his solution using yield statements effectively reducing the memory utilization per file to an absolute minimum. With his code you can write something like the following: ``` var allowedExtensions = new HashSet<string> { ".jpg", ".mp3" }; var files = GetFiles( "C:\\path", SearchOption.AllDirectories, fn => allowedExtensions.Contains(Path.GetExtension(fn)) ); ``` And the files variable will point to an enumerator that returns the files matched (delayed execution style).
You are right about the memory consumption. However, I think that's a fairly premature optimization. Loading an array of a few thousand strings is no problem at all, neither for performance nor for memory consumption. Reading a directoy containing that many files, however, *is* – no matter how you store/filter the file names: it will always be relatively slow.
Efficiently retrieving and filtering files
[ "", "c#", "linq", "performance", "file", "" ]
jQuery currently has `.next(filter)` and `.nextAll(filter)` but I need something that fits in the middle of these - effectively, a `.nextWhile(filter)` that repeatedly does next until the filter is no longer true, then stops (rather than continuing to the end). To demonstrate this, the following is some simplified HTML - (in reality, it is dynamically generated, random order/data, more columns, proper class names, and so on). ``` <table> <thead> <tr> <th>...</th> </tr> </thead> <tbody> <tr class="x"><td>a <button>Show/Hide</button></td></tr> <tr class="x y"><td>a1</td></tr> <tr class="x y"><td>a2</td></tr> <tr class="z"><td>b</td></tr> <tr class="z"><td>c</td></tr> <tr class="x"><td>d <button>Show/Hide</button></td></tr> <tr class="x y"><td>d1</td></tr> <tr class="x y"><td>d2</td></tr> <tr class="x y"><td>d3</td></tr> <tr class="z"><td>e</td></tr> <tr class="x"><td>f</td></tr> <tr class="x"><td>g <button>Show/Hide</button></td></tr> <tr class="x y"><td>g1</td></tr> <tr class="x y"><td>g2</td></tr> </tbody> </table> ``` And against this some JavaScript is run: ``` <script type="text/javascript"> var $j = jQuery.noConflict(); $j().ready(init); function init() { $j('tr.y').hide(); $j('tr.x button').click( toggleRelated ); } function toggleRelated() { // Only toggles one row // $j(this).parents('tr').next('.y').toggle(); // Toggles unrelated ones also $j(this).parents('tr').nextAll('.y').toggle(); // Not currently a jQuery construct // $j(this).parents('tr').nextWhile('.y').toggle(); } </script> ``` Is there an easy way to implement this `nextWhile` construct? Ideally this needs to be achieved without modifying the current HTML.
In jQuery you can create `nextWhile()` equivalent using [`nextUntil()`](http://api.jquery.com/nextUntil/) method and [`:not`](http://api.jquery.com/not-selector/) selector. Simply put, *`while (condition is true) { do something }`* is same as saying *`until (condition is false) { do something }`*. Consider this trick example where you are required to select all `.child` elements that follow the first `.parent`: ``` <ul id="test"> <li class="parent"></li> <li class="child"></li> <li class="child"></li> <li class="child"></li> <li class="divider"></li> <li class="parent"></li> <li class="child"></li> <li class="child"></li> <li class="child"></li> </ul> ``` The following code is roughly equivalent to *`.nextWhile(".child")`* and selects the three `.child` elements: ``` $("#test .parent:first").nextUntil(":not(.child)"); ```
***UPDATE:*** Gave up on the recursion idea and decided to count and slice (see last example). **Initial Attempt:** *This code is buggy - it only returns the last two items, so doesn't work for 3+ items.* ``` jQuery.fn.nextWhile = function(f) { if( this.next(f).html() ) { return this.next(f).nextWhile(f).andSelf(); } else { return this; } }; ``` **Current Version:** ``` jQuery.fn.nextWhile = function(f) { var Next = this.next(f); var Pos = 0; while( Next.length > 0 ) { Pos++; Next = Next.next(f); } return this.nextAll(f).slice(0,Pos); } ``` This appears to work fine, but I'm not sure if there are any performance penalties to selecting everything and then slicing only a handful from it?
jQuery - suggestions for a "nextWhile" traversion?
[ "", "javascript", "jquery", "jquery-selectors", "traversal", "" ]
In C# some collections such as `ArrayList` and `HashTable` have generic alternatives which are `List<T>` and `Dictionary<TKey, TValue>`. **Does Array also have a generic alternative?**
If you're looking for the generic collection type that most closely resembles an array, then you probably want a `List<T>`. But it's not really the same thing. To expand on what others have said: the point of having generic types is so that a programmer can then use *type-specific* instances of those generic types, based on the needs of the current program. Arrays are *already* type-specific. You can always just take a `T[]`. For example, look at this simple function definition: ``` void SomeFunction(int[] x) ``` You could also think of it like this: ``` void SomeFunction<T>(T[] x) ``` where the programmer just chose to call it with an `int` for the type parameter: ``` SomeFunction<int>(myIntArray) ```
No - just use a strongly typed array, e.g. `int[]`. It's relatively rare to use a "weakly typed" `Array` in the first place - in fact, I don't believe you can really create one. Every `Array` is really a strongly-typed one, even if you don't refer to it that way.
What is the generic alternative of Array?
[ "", "c#", ".net", "arrays", "generics", "" ]
You system allows new users to register and enter their wedding date. Being a purist, I wanted to store this as a date. After user interviews, it was clear that the reality differs from this approach. Users are often not sure of the day or the month, and wish to store partial dates, so "June 2009" or "sometime in 2012". Does anyone know a good design pattern that allows the storing partial dates, and then trying to create a timeline for the big day - even though there are partial dates entered?
Maybe a "fuzzy" date. If they say "June 2009", that could be stored as 15 June 2009, with a variance of +/- 15 days. "sometime in 2010" would be 01 July 2010 with a variance of 180 days. So store a date and a # days. If/how that would work in practice I don't know. Just an idea. A date range might be easier to implement.
You could store it as a range with an after-date and before-date column.
SQL Date pattern for dates that user may not know all the information
[ "", "sql", "design-patterns", "date", "null", "" ]
I’ve got the following code: ``` #include <iostream> using namespace std; int main() { char* a = "foo"; char* b = "bar"; a = b; cout << a << ", " << b << endl; return 0; } ``` This compiles and works, ie. prints `bar,` `bar`. Now I would like to demonstrate that what goes on here is not copying a string. I would like to change `b` and show that `a` also changes. I came up with this simple code: ``` #include <iostream> using namespace std; int main() { char* a = "foo"; char* b = "bar"; a = b; b[1] = 'u'; // ← just this line added cout << a << ", " << b << endl; return 0; } ``` …but it segfaults. Why? The interesting thing is that the following modification runs just fine: ``` #include <iostream> using namespace std; int main() { char* a = "foo"; char b[] = "bar"; // ← declaration changed here a = b; b[1] = 'u'; cout << a << ", " << b << endl; return 0; } ``` Why doesn’t it segfault like the previous one? I guess I am missing some important difference between the pointer-style and the array-style string initialization.
You cannot change string constants, which is what you get when you use the pointer-to-literal syntax as in the first code samples. See also this question: [Is a string literal in c++ created in static memory?](https://stackoverflow.com/questions/349025/is-a-string-literal-in-c-created-in-static-memory).
When you write this: ``` char *b = "bar"; ``` the compiler allocates an anonymous (nameless) memory area to store the string literal "bar". String literals may not be modified, so the compiler (with the help of the linker and operating system) puts the string literal in a part of the running program's memory space that is write-protected. When you try to modify it, the operating system catches it and causes your program to segmentation fault. (Your code is C++, not C, but that's irrelevant to this question.)
Why does this simple string assignment segfault?
[ "", "c++", "string", "initialization", "" ]
I've: ``` function Obj1(param) { this.test1 = param || 1; } function Obj2(param, par) { this.test2 = param; } ``` now when I do: ``` Obj2.prototype = new Obj1(44); var obj = new Obj2(55); alert(obj.constructor) ``` I have: ``` function Obj1(param) { this.test1 = param || 1; } ``` but the constructor function has been Obj2... why that? Obj1 has become the Obj2 prototype... Can someone explain me, in detail, the prototype chain and the constructor property Thanks
`constructor` is a regular property of the prototype object (with the `DontEnum` flag set so it doesn't show up in `for..in` loops). If you replace the prototype object, the `constructor` property will be replaced as well - see [this explanation](http://joost.zeekat.nl/constructors-considered-mildly-confusing.html) for further details. You can work around the issue by manually setting `Obj2.prototype.constructor = Obj2`, but this way, the `DontEnum` flag won't be set. Because of these issues, it isn't a good idea to rely on `constructor` for type checking: use `instanceof` or `isPrototypeOf()` instead. --- Andrey Fedorov raised the question why `new` doesn't assign the `constructor` property to the instance object instead. I guess the reason for this is along the following lines: All objects created from the same constructor function share the constructor property, and shared properties reside in the prototype. The real problem is that JavaScript has no built-in support for inheritance hierarchies. There are several ways around the issue (yours is one of these), another one more 'in the spirit' of JavaScript would be the following: ``` function addOwnProperties(obj /*, ...*/) { for(var i = 1; i < arguments.length; ++i) { var current = arguments[i]; for(var prop in current) { if(current.hasOwnProperty(prop)) obj[prop] = current[prop]; } } } function Obj1(arg1) { this.prop1 = arg1 || 1; } Obj1.prototype.method1 = function() {}; function Obj2(arg1, arg2) { Obj1.call(this, arg1); this.test2 = arg2 || 2; } addOwnProperties(Obj2.prototype, Obj1.prototype); Obj2.prototype.method2 = function() {}; ``` This makes multiple-inheritance trivial as well.
Check out [Tom Trenka's OOP woth ECMAscript](http://people.apache.org/~martinc/OOP_with_ECMAScript/), the "Inheritance" page. *Everything* from the prototype is inherited, including the `constructor` property. Thus, we have to unbreak it ourselves: ``` Obj2.prototype = new Obj1(42); Obj2.prototype.constructor = Obj2; ```
prototype and constructor object properties
[ "", "javascript", "prototype", "constructor", "" ]
I want to start a job in a new thread or using backgroundworker to do it but havent done that before and asking you wich way I should do it. My program has a datagridview with a list of files, one file per row. I want the user to be able to select a row and then press "Start download" to start a background job of the download. I want to get events back of the progress of the download. I have a class clsDownload that handles everything and raises events back but how do I implement the backgroundworking? Should I use the System.ComponentModel.BackgroundWorker inside of the class or create some wrapper that handles this or use some other threading stuff? Thanks. **Edit:** I dont understand how to implement my download in the backgroundworker, any small example would be very nice. The example on msdn didnt get me far. I have a download class that has a StartDownload-function. Should I use the backgroundworker IN the class or in the caller? "feeling stupid"
I've created several different classes that incorporate BackgroundWorker. What I generally do is have a BackgroundWorker component on the form that will be open when the job is being performed, then I pass that instance to the constructor of my job class. Here is what your job class might look like: ``` Private m_bwMain As BackgroundWorker Public Sub New(ByVal bwMain As BackgroundWorker) m_bwMain = bwMain 'additional setup code here End Sub ``` To start a job, you would do something like this in the Click event handler of your Start Download button: ``` lblStatus.Text = "Initializing ..." bgwMain.RunWorkerAsync(someFileName) ``` I declare my job class as a private member of the current form, then instantiate it in the BackgroundWorker.DoWork event. From there you can call your method to download a file: ``` Private Sub bgwMain_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles bgwMain.DoWork m_oJobEngine = New JobEngine(CType(sender, BackgroundWorker)) m_oJobEngine.DownloadFile(CStr(e.Argument)) End Sub ``` To report progress to the user, you can handle the events raised by your class in your main form. You just need to make sure the job class object declaration has the WithEvents keyword. From those handlers you can call the ReportProgress method of BackgroundWorker. From within ReportProgress you can make whatever changes you need to the UI to indicate progress. Here's an example: ``` Private Sub m_oJobEngine.DownloadProgress(ByVal bgw as Backgroundworker, ByVal bytesTransferred as Long) Handles m_oJobEngine.DownloadProgress bgw.ReportProgress(0, bytesTransferred) End Sub Private Sub bgwMain_ProgressChanged(ByVal sender As Object, ByVal e As System.ComponentModel.ProgressChangedEventArgs) Handles bgwMain.ProgressChanged lblStatus.Text = CLng(e.UserState).ToString & " bytes transferred." End Sub ``` Hope this helps.
I'd strongly advise `BackgroundWorker` if you need to provide feedback to the user on the UI. The `ProgressChanged` and `RunWorkerCompleted` events are run on the UI thread, so there's no need to do marshalling, which can make your code more complex.
Running class as new thread
[ "", "c#", "vb.net", "backgroundworker", "" ]
I want my application to save the password encrypted in a database or in a text file. How can I do that assuming that the database or text file can be open by anyone? **Duplicate** > [Encrypting/Hashing plain text passwords in database](https://stackoverflow.com/questions/287517/encrypting-hashing-plain-text-passwords-in-database) **Not duplicate** I'm asking for code specific for .NET EDIT: I'm saving the password for later use. I need to decode it and use it to login. It doesn't have to be super secure, it just needs to be unreadable to the human eye, and difficult to decode with a trivial script.
StackOverflow readers don't know how to write secure password schemes and neither do you. If you're going to do that, save time by sticking with plain text. From [Enough With The Rainbow Tables: What You Need To Know About Secure Password Schemes](http://www.matasano.com/log/958/enough-with-the-rainbow-tables-what-you-need-to-know-about-secure-password-schemes/): > Rainbow tables are easy to beat. For > each password, generate a random > number (a nonce). Hash the password > with the nonce, and store both the > hash and the nonce. The server has > enough information to verify passwords > (the nonce is stored in the clear). > But even with a small random value, > say, 16 bits, rainbow tables are > infeasible: there are now 65,536 > “variants” of each hash, and instead > of 300 billion rainbow table entries, > you need quadrillions. The nonce in > this scheme is called a “salt”. > > Cool, huh? Yeah, and Unix crypt —- > almost the lowest common denominator > in security systems —- has had this > feature since 1976. If this is news to > you, you shouldn’t be designing > password systems. Use someone else’s > good one. Use [BCrypt](http://derekslager.com/blog/posts/2007/10/bcrypt-dotnet-strong-password-hashing-for-dotnet-and-mono.ashx) - Strong Password Hashing for .NET and Mono. It's a single cleanly written .cs file that will continue to meet your needs as password cracking computers get faster.
[BCrypt](http://derekslager.com/blog/posts/2007/10/bcrypt-dotnet-strong-password-hashing-for-dotnet-and-mono.ashx) - Strong Password Hashing for .NET and Mono
How to encrypt a password for saving it later in a database or text file?
[ "", "c#", ".net", "security", "" ]
How can I set a DateTimePicker control to a specific date (yesterday's date) in C# .NET 2.0?
Just need to set the value property in a convenient place (such as `InitializeComponent()`): ``` dateTimePicker1.Value = DateTime.Today.AddDays(-1); ```
If you want to set a date, DateTimePicker.Value is a DateTime object. ``` DateTimePicker.Value = new DateTime(2012,05,28); ``` This is the constructor of DateTime: ``` new DateTime(int year,int month,int date); ``` My Visual is 2012
How can I set a DateTimePicker control to a specific date?
[ "", "c#", "winforms", "datepicker", "" ]
Assume all the variables have been declared previously... because they have been. The child process does not print anything which makes me think it's not being executed. The parent process runs fine, albeit it doesn't get the shared memory. I apologize for the length of this code... ``` // create 5 child process for(int k=0;k<5;k++){ // fork a child process pid = fork(); // error occured on fork if (pid < 0) { fprintf(stderr, "Fork Failed"); return 1; } // this is what the child process will run else if (pid == 0) { //create a shared mem segment segment_id = shmget(IPC_PRIVATE, size, S_IRUSR | S_IWUSR); //attach the shared memory segment shared_memory = (char *) shmat(segment_id, NULL, 0); printf("this is child"); double x = 0; double sum = 0; // Run process that sums the function for(int i=0; i<n; i++){ // get random number in range of x1-x2 x = rand()%(x2 - x1 + 1) + x1; sum = sum + f(x); } //write output to the shared memory segment sprintf(shared_memory, "%f", sum); execlp("/bin/ls", "ls", NULL); } // this is what the parent process will run else { //print output from shared memory printf("\n*%s", shared_memory); //detach shared memory shmdt(shared_memory); //Here we add the shared memory to the array // To add together at the end // but since I cant get the memory to share // the array can't be implemented //remove the shared memory segment shmctl(segment_id, IPC_RMID, NULL); wait(NULL); } } // End of for statement ```
The C stdout stream internally buffers data. It's likely that your "this is child" message is being buffered, and the buffer isn't being flushed by execlp, so it just disappears. Try a `fflush(stdout);` after the printf. Incidentally, you should do this before the `fork()` as well, so that child and parent don't both try to write output buffered from before the fork.
Print to stderr it is not buffered. ``` fprintf(stderr,"Plop\n"); ``` Also the shared memory stuff (segment\_id, shared\_memory) is not initialized in the parent (or if it is then it is not the same as the child). Furthermore the parent is potentially destroying the shared memory stuff while the child is still processing. The parent should wait first then process the data produced by the child.
Why does the child process here not print anything?
[ "", "c++", "fork", "parent-child", "" ]
I have to implements a function that takes a string as an input and finds the non-duplicate character from this string. So an an example is if I pass string str = "DHCD" it will return "DHC" or str2 = "KLKLHHMO" it will return "KLHMO"
A Linq approach: ``` public static string RemoveDuplicates(string input) { return new string(input.ToCharArray().Distinct().ToArray()); } ```
It will do the job ``` string removedupes(string s) { string newString = string.Empty; List<char> found = new List<char>(); foreach(char c in s) { if(found.Contains(c)) continue; newString+=c.ToString(); found.Add(c); } return newString; } ``` I should note this is criminally inefficient. I think I was delirious on first revision.
How can you remove duplicate characters in a string?
[ "", "c#", "" ]
I'm working on a simple copy tool to copy files off digital cameras. I've written the file copy code, I've got everything hooked up nicely. The issue I have seems to be with the FolderBrowserDialog. In Vista (I haven't checked XP yet), I can browse to the directories on the camera. However the FolderBrowserDialog will not let me select a directory on the camera. The OK button is greyed out. Looking at the path for the files on the camera it looks like this: ``` Computer\[Camera Name]\Removable storage\AnotherDirectory\ ``` As this is not a valid path (intead of C:\whatever), I'm guessing the FolderBrowserDialog doesn't like this. It works fine from a valid path name, but not off the camera... Does anyone have any suggestions to get around this? **Update** To confirm oefe's question the path is actually displayed as: ``` Computer\[Camera Name]\Removable storage\AnotherDirectory\ ``` ChulioMartinez's suggestion of using SHBrowseForFolder does work, and I will mark as the correct answer. Thanks for your help Chulio.
My guess would be that the location doesn't have a file system representation (path) such as c:...\my camera. You should be able to get the PIDL of the folder, (it should be one the the flags for the function), and implement the copy using the COM shell interfaces. [SHBrowseForFolder](http://msdn.microsoft.com/en-us/library/bb762115%28VS.85%29.aspx) [Using PIDL to enumerate a folder](http://www.gtro.com/delphi/shell_e.php)
Is there a way to map the camera path to a drive letter? (I'm thinking something like "subst" or "net use" from a command prompt.) Maybe that would fool the FolderBrowserDialog into behaving as desired?
Using FolderBrowserDialog on a Removable Device / Removable storage
[ "", "c#", ".net", "path", "folderbrowserdialog", "" ]
I'm having a table (an existing table with data in it) and that table has a column UserName. I want this UserName to be unique. So I add a constraint like this: ``` ALTER TABLE Users ADD CONSTRAINT [IX_UniqueUserUserName] UNIQUE NONCLUSTERED ([UserName]) ``` Now I keep getting the Error that duplicate users exist in this table. But I have checked the database using the following query: ``` SELECT COUNT(UserId) as NumberOfUsers, UserName FROM Users GROUP BY UserName, UserId ORDER BY UserName ``` This results in a list of users all having 1 as a NumberOfUsers. So no duplicates there. But when I'm checking the username he fails I see the following result: ``` beluga béluga ``` So apperently he fails to compare an "e" and "é" or "è" ... It's like he ignores these, is there any way that sql doesn't ignore these accents when adding the unique key contraint. SOLUTION: THX to you guys I've found the solution. This fixed the problem: ``` ALTER TABLE Users ALTER COLUMN UserName nvarchar(250) COLLATE SQL_Latin1_General_CP1_CI_AS ```
The collation you are using most likely ignores case and accents when comparing. You'll need to change the collation. * `Latin1_General_CI_AI` Ignores case and accents * `Latin1_General_CI_AS` will not ignore accents List of SQL server collation names [here](http://msdn.microsoft.com/en-us/library/ms180175.aspx).
Your query groups by UserID too - you don't want to be doing that. Use: ``` SELECT COUNT(*) as NumberOfUsers, UserName FROM Users GROUP BY UserName ORDER BY UserName ``` Your query would only show up users with the same name and same user ID. Or, maybe, order the data by `COUNT(*)` so the last row that shows up is most likely the troublemaker? You could also have problems with collation as others have suggested, but normally, GROUP BY would be self-consistent.
Unique constraint on table column
[ "", "sql", "sql-server", "constraints", "diacritics", "unique-key", "" ]
I have asked this question today already but this time I want to know if I can achieve this via PHP since Javascript wasn't up to it. I have a link to a file on another server. If i provide this link to my users the headers are pushed out to download that file from that server. Is there a way for me to capture those headers and file and redirect the download to the user? I would like to do this so that I can change the filename of the download since it is always 'file.zip'. Is this possible with PHP? Thank you for any help.
You could do this, and you can do it in several ways. 1) (simple) copy the file to your server, and rename it. Point your download links to this copy. 2) (harder) Create a stub php file, called , read the file from the remote server within php, and stream the content to the script output. This will need you to set appropriate headers, etc. as well as setting up your webserver to parse through PHP. Seriously, I'd go with option 1. (assumes you have a legal right to serve the content, etc.)
You can download the file to your server using [curl](http://php.net/curl) and serve it correctly(with a [Content-Disposition](http://www.ietf.org/rfc/rfc2183.txt) header). As long as you are using HTTP, there's no way to send just the header and let another server stream the content directly to the client.
Renaming File on another server as user downloads it [2] - using PHP
[ "", "php", "http", "file", "redirect", "http-headers", "" ]
As a side result of testing some code I wrote a small function to compare the speed of using the `array.push(value)` method vs direct addressing `array[n] = value`. To my surprise the push method often showed to be faster especially in Firefox and sometimes in Chrome. Just out of curiosity: anyone has an explanation for it? Here's the test (**note**: rewritten 2023/02/10) ``` const arrLen = 10_000; const x = [...Array(10)].map( (_, i) => testArr(arrLen, i)); console.log(`Array length: ${arrLen}\n--------\n${x.join(`\n`)}`); function testArr(n, action) { let arr = []; const perfStart = performance.now(); const methods = ` for (; n; n--) arr.push(n) for (; i < n; i += 1) { arr[i] = i; } for (; i < n; i += 1) arr.push(i) while (--n) arr.push(n) while (i++ < n) arr.push(n) while (--n) arr.splice(0, 0, n) while (--n) arr.unshift(n) while (++i < n) arr.unshift(i) while (--n) arr.splice(n - 1, 0, n) while (n--) arr[n] = n`.split(`\n`).map(v => v.trim()); const report = i => `${methods[i]}: ${ (performance.now() - perfStart).toFixed(2)} milliseconds`; let i = 0; switch (action) { case 0: for (; n; n--) arr.push(n) case 1: for (; i < n; i += 1) { arr[i] = i; } break; case 2: for (let i = 0; i < n; i += 1) arr.push(i); break; case 3: while (--n) arr.push(n); break; case 4: while (i++ < n) arr.push(n); break; case 5: while (--n) arr.splice(0, 0, n); break; case 6: while (--n) arr.unshift(n) case 7: while (++i < n) arr.unshift(i); break; case 8: while (--n) arr.splice(n - 1, 0, n); break; default: while (n--) arr[n] = n; } return report(action); } ``` ``` .as-console-wrapper { max-height: 100% !important; } ```
All sorts of factors come into play, most JS implementations use a flat array that converts to sparse storage if it becomes necessary later on. Basically the decision to become sparse is a heuristic based on what elements are being set, and how much space would be wasted in order to remain flat. In your case you are setting the last element first, which means the JS engine will see an array that needs to have a length of `n` but only a single element. If `n` is large enough this will immediately make the array a sparse array -- in most engines this means that all subsequent insertions will take the slow sparse array case. You should add an additional test in which you fill the array from index 0 to index n-1 -- it should be much, much faster. In response to @Christoph and out of a desire to procrastinate, here's a description of how arrays are (generally) implemented in JS -- specifics vary from JS engine to JS engine but the general principle is the same. All JS `Object`s (so not strings, numbers, true, false, `undefined`, or `null`) inherit from a base object type -- the exact implementation varies, it could be C++ inheritance, or manually in C (there are benefits to doing it in either way) -- the base Object type defines the default property access methods, eg. ``` interface Object { put(propertyName, value) get(propertyName) private: map properties; // a map (tree, hash table, whatever) from propertyName to value } ``` This Object type handles all the standard property access logic, the prototype chain, etc. Then the Array implementation becomes ``` interface Array : Object { override put(propertyName, value) override get(propertyName) private: map sparseStorage; // a map between integer indices and values value[] flatStorage; // basically a native array of values with a 1:1 // correspondance between JS index and storage index value length; // The `length` of the js array } ``` Now when you create an Array in JS the engine creates something akin to the above data structure. When you insert an object into the Array instance the Array's put method checks to see if the property name is an integer (or can be converted into an integer, e.g. "121", "2341", etc.) between 0 and 2^32-1 (or possibly 2^31-1, i forget exactly). If it is not, then the put method is forwarded to the base Object implementation, and the standard [[Put]] logic is done. Otherwise the value is placed into the Array's own storage, if the data is sufficiently compact then the engine will use the flat array storage, in which case insertion (and retrieval) is just a standard array indexing operation, otherwise the engine will convert the array to sparse storage, and put/get use a map to get from propertyName to value location. I'm honestly not sure if any JS engine currently converts from sparse to flat storage after that conversion occurs. Anyhoo, that's a fairly high level overview of what happens and leaves out a number of the more icky details, but that's the general implementation pattern. The specifics of how the additional storage, and how put/get are dispatched differs from engine to engine -- but this is the clearest i can really describe the design/implementation. A minor addition point, while the ES spec refers to `propertyName` as a string JS engines tend to specialise on integer lookups as well, so `someObject[someInteger]` will not convert the integer to a string if you're looking at an object that has integer properties eg. Array, String, and DOM types (`NodeList`s, etc).
These are the result I get with **your test** on Safari: * Array.push(n) 1,000,000 values: 0.124 sec * Array[n .. 0] = value (descending) 1,000,000 values: 3.697 sec * Array[0 .. n] = value (ascending) 1,000,000 values: 0.073 sec on FireFox: * Array.push(n) 1,000,000 values: 0.075 sec * Array[n .. 0] = value (descending) 1,000,000 values: 1.193 sec * Array[0 .. n] = value (ascending) 1,000,000 values: 0.055 sec on IE7: * Array.push(n) 1,000,000 values: 2.828 sec * Array[n .. 0] = value (descending) 1,000,000 values: 1.141 sec * Array[0 .. n] = value (ascending) 1,000,000 values: 7.984 sec According to **your test** the *push* method seems to be better on IE7 (huge difference), and since on the other browsers the difference is small, it seems to be the *push* method really the best way to add element to an array. But I created another [simple test script](http://vanylla.it/test-array-push-vs-length.html) to check what method is fast to append values to an array, the results really surprised me, **using Array.length seems to be much faster compared to using Array.push**, so I really don't know what to say or think anymore, I'm clueless. *BTW: on my IE7 your script stops and browsers asks me if I want to let it go on (you know the typical IE message that says: "Stop runnign this script? ...") I would recoomend to reduce a little the loops.*
Why is array.push sometimes faster than array[n] = value?
[ "", "javascript", "arrays", "performance", "firefox", "browser", "" ]
I am working with another colleague in C# in VS2005 in a not very complex project. However, we have no version control system, we send each other our last version and copy the changes into our own files. We now have to merge both files (most of the project is a single form file) into a last version of the project. Any suggestions? Maybe trying diff tools? It must be done quickly and probably learning how to use complex revision control programs is not doable.
I'll spare you the lecture on not using version control, but your best bet is to try and use a differencing tool like [WinMerge](http://winmerge.org/) to compare the differences of the 2 files and manually merge the changes that each of you has made into a single file. If you have the common file that you both started with before you each made any changes, then you can use a 3-way merge feature to generate a file that has both of your changes in it. It was pointed out to me that WinMerge does not offer a 3-way merge, so refer to [this other question](https://stackoverflow.com/questions/460198/best-free-3-way-merge-tool-for-windows) for finding a tool that supports it.
We use [BeyondCompare](http://www.scootersoftware.com/) - we have found that to be an excellent compare and merge tool. I understand the need for speed to produce your final version of the code now. However, if you are planning to start another project it really is worth investing the time to set up a source control system. You'll save that time in spades over the course of the project!
How to merge two source files easily?
[ "", "c#", "version-control", "merge", "diff", "" ]
Is it possible to cancel a linq2sql query? Like if I have built a query that takes a while to run, I would like it to be possible for the user to cancel it. Does anyone have any good ideas on this?
So, according to [Richard Szalay](https://stackoverflow.com/users/3603/richard-szalay)'s comment: > Your best bet is to run the query in a background thread and simply unsubscribe from the container object's events when the user hits Cancel. And I think I agree that this is a an ok work-around for now. What I would love to see is some Async query functionality already in the framework, but until that happens this will have to do. Haven't started to implement this yet (have to finish some other things first), but one way it could work: * In the working thread, do the queries in a separate query thread and then Join that thread until it is finished. * When user hits cancel, call the `Interrupt` method of the working thread, which would then get an `ThreadInterruptedException` and stop waiting for the query thread to finish. --- May add some code later when I make it. But we'll see how pretty it turns out :p
If you set the [CommandTimeout](http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.commandtimeout.aspx) (seconds) property of [DataContext](http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.aspx), it will automatically throw an exception after the timeout elapses.
C#: Is it possible to cancel a linq2sql query?
[ "", "c#", "linq-to-sql", "" ]
I want to get all the values associated with a key in Map. For e.g, ``` Map tempMap = new HashMap(); tempMap.put("1","X"); tempMap.put("2","Y"); tempMap.put("3","Z"); tempMap.put("1","ABC"); tempMap.put("2","RR"); tempMap.put("1","RT"); ``` How to retrieve all the values associated with key 1 ?
What you can do is this: ``` Map<String, List<String>> tempMap = new HashMap<String, List<String>>(); tempMap.put("1", new LinkedList<String>()); tempMap.get("1").add("X"); tempMap.get("1").add("Y"); tempMap.get("1").add("Z"); for(String value : tempMap.get("1")) { //do something } ``` This compartmentalizes values that correspond to the key "1" into their own list, which you can easily access. Just don't forget to initialize the list... else `NullPointerException`s will come to get you. Yuval =8-)
the thing you must understand is that in a Map, the key is unique. that means that after ``` tempMap.put("1","X"); ``` "1" is mapped to "X" and after ``` tempMap.put("1","ABC"); ``` "1" is mapped to "ABC" and the previous value ("X") is lost
How to retrieve all the values associated with a key?
[ "", "java", "dictionary", "" ]
I am running a Web Service in C# .NET 3.5. I want to log various calls. However since many users are hitting the same functions at once it is difficult to tell which log call belongs to which. In a C++ life we used a thread Id. What is the equivalent in C#? I have tried ``` System.Diagnostics.Process proc = System.Diagnostics.Process.GetCurrentProcess(); proc.Id; ``` However this gets me the same Id each time.
If you use MS Ent Lib and their logger you can use the Tracer class to get some nice logging: Example ``` public Output MyServiceMethod(Input input, string transactionId) { using(new Tracer("MyServiceMethod: " + transactionId)) { ... stuff ... return output; } } ``` You can even nest Tracers. All logging within the using will have the string you give Tracer constructor as an extended property.
Mayhaps Thread.CurrentThread.ManagedThreadId
On a C# Web Service can I find a unique thread ID or some ID for logging purposes?
[ "", "c#", ".net", "web-services", "multithreading", "" ]
What is Environment.FailFast? How is it useful?
It is used to kill an application. It's a static method that will instantly kill an application without being caught by any exception blocks. > Environment.FastFail(String) can > actually be a great debugging tool. > For example, say you have an > application that is just downright > giving you some weird output. You have > no idea why. You know it's wrong, but > there are just no exceptions bubbling > to the surface to help you out. Well, > if you have access to Visual Studio > 2005's Debug->Exceptions... menu item, > you can actually tell Visual Studio to > allow you to see those first chance > exceptions. If you don't have that, > however you can put > Environment.FastFail(String) in an > exception, and use deductive reasoning > and process of elimination to find out > where your problem in. [Reference](https://netfxharmonics.com/2006/10/uncatchable-exception)
It also creates a dump and event viewer entry, which might be useful.
What is Environment.FailFast?
[ "", "c#", ".net", "vb.net", "" ]
What is the efficiency of this? ... ``` CommentText.ToCharArray().Where(c => c >= 'A' && c <= 'Z').Count() ```
Ok, just knocked up some code to time your method against this: ``` int count = 0; for (int i = 0; i < s.Length; i++) { if (char.IsUpper(s[i])) count++; } ``` The result: > Yours: 19737 ticks > > Mine: 118 ticks Pretty big difference! Sometimes the most straight-forward way is the most efficient. **Edit** Just out of interest, this: ``` int count = s.Count(c => char.IsUpper(c)); ``` Comes in at at around 2500 ticks. So for a "Linqy" one-liner it's pretty quick.
First there is no reason you need to call `ToCharArray()` since, assuming `CommentText` is a string it is already an `IEnumerable<char>`. Second, you should probably be calling `char.IsUpper` instead of assuming you are only dealing with ASCII values. The code should really look like, ``` CommentText.Count(char.IsUpper) ``` Third, if you are worried about speed there isn't much that can beat the old for loop, ``` int count = 0; for (int i = 0; i < CommentText.Length; i++) if (char.IsUpper(CommentText[i]) count++; ``` In general, calling any method is going to be slower than inlining the code but this kind of optimization should only be done if you are absolutely sure this is the bottle-neck in your code.
Fastest way to count number of uppercase characters in C#
[ "", "c#", "linq", "" ]
Is it possible to programmatically construct a stack (one or more stack frames) in CPython and start execution at an arbitrary code point? Imagine the following scenario: 1. You have a workflow engine where workflows can be scripted in Python with some constructs (e.g. branching, waiting/joining) that are calls to the workflow engine. 2. A blocking call, such as a wait or join sets up a listener condition in an event-dispatching engine with a persistent backing store of some sort. 3. You have a workflow script, which calls the Wait condition in the engine, waiting for some condition that will be signalled later. This sets up the listener in the event dispatching engine. 4. The workflow script's state, relevant stack frames including the program counter (or equivalent state) are persisted - as the wait condition could occur days or months later. 5. In the interim, the workflow engine might be stopped and re-started, meaning that it must be possible to programmatically store and reconstruct the context of the workflow script. 6. The event dispatching engine fires the event that the wait condition picks up. 7. The workflow engine reads the serialised state and stack and reconstructs a thread with the stack. It then continues execution at the point where the wait service was called. **The Question** Can this be done with an unmodified Python interpreter? Even better, can anyone point me to some documentation that might cover this sort of thing or an example of code that programmatically constructs a stack frame and starts execution somewhere in the middle of a block of code? **Edit:** To clarify 'unmodified python interpreter', I don't mind using the C API (is there enough information in a PyThreadState to do this?) but I don't want to go poking around the internals of the Python interpreter and having to build a modified one. **Update:** From some initial investigation, one can get the execution context with `PyThreadState_Get()`. This returns the thread state in a `PyThreadState` (defined in `pystate.h`), which has a reference to the stack frame in `frame`. A stack frame is held in a struct typedef'd to `PyFrameObject`, which is defined in `frameobject.h`. `PyFrameObject` has a field `f_lasti` (props to [bobince](https://stackoverflow.com/questions/541329/is-it-possible-to-programatically-construct-a-python-stack-frame-and-start-execut/541529#541529)) which has a program counter expressed as an offset from the beginning of the code block. This last is sort of good news, because it means that as long as you preserve the actual compiled code block, you should be able to reconstruct locals for as many stack frames as necessary and re-start the code. I'd say this means that it is theoretically possible without having to make a modified python interpereter, although it means that the code is still probably going to be fiddly and tightly coupled to specific versions of the interpreter. The three remaining problems are: * Transaction state and 'saga' rollback, which can probably be accomplished by the sort of metaclass hacking one would use to build an O/R mapper. I did build a prototype once, so I have a fair idea of how this might be accomplished. * Robustly serialising transaction state and arbitrary locals. This might be accomplished by reading `__locals__` (which is available from the stack frame) and programatically constructing a call to pickle. However, I don't know what, if any, gotchas there might be here. * Versioning and upgrade of workflows. This is somewhat trickier, as the system is not providing any symbolic anchors for workflow nodes. All we have is the anchor In order to do this, one would have to identify the offsets of all of the entry points and map them to the new version. Probably feasible to do manually, but I suspect it would be hard to automate. This is probably the biggest obstacle if you want to support this capability. **Update 2:** `PyCodeObject` (`code.h`) has a list of addr (`f_lasti`)-> line number mappings in `PyCodeObject.co_lnotab` (correct me if wrong here). This might be used to facilitate a migration process to update workflows to a new version, as frozen instruction pointers could be mapped to the appropriate place in the new script, done in terms of the line numbers. Still quite messy but a little more promising. **Update 3:** I think the answer to this might be [Stackless Python.](http://www.stackless.com) You can suspend tasks and serialise them. I haven't worked out whether this will also work with the stack as well.
With standard CPython this is complicated by the mixture of C and Python data in the stack. Rebuilding the call stack would require the C stack to be reconstructed at the same time. This really puts it in the too hard basket as it could potentially tightly couple the implementation to specific versions of CPython. Stackless Python allows tasklets to be pickled, which gives most of the capability required out of the box.
The expat python bindings included in the normal Python distribution is constructing stack frames programtically. Be warned though, it relies on undocumented and private APIs. <http://svn.python.org/view/python/trunk/Modules/pyexpat.c?rev=64048&view=auto>
Is it possible to programmatically construct a Python stack frame and start execution at an arbitrary point in the code?
[ "", "python", "serialization", "stack", "continuations", "python-stackless", "" ]
I've got some jsp files that are supposed to output xhtml. They seem to have the correct doctype etc but Eclipse is not parsing the xhtml attributes. For instance for the root element: ``` <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> ``` I get the warning: "Undefined attribute name (xmlns)." What's the best way to solve this in Eclipse? edit: The doctype for this particular file was wrong apparently, it was set to: ``` <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ``` Which does not exist obviously. Eclipse is now complaining about taglib tags though, i.e.: ``` <%@taglib prefix="s" uri="/struts-tags" %> ``` generates the warning: "Tag (jsp:directive.taglib) should be an empty-element tag."
That seems odd, I use the same in Eclipse but with PHP and it works fine. What is the DOCTYPE that you use? I've used `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">`
If you're going to ouput xml (in my understanding xhtml **is** xml) then you should be using the jsp *document* syntax, for instance your ``` <%@taglib prefix="s" uri="/struts-tags" %> ``` should instead be a namespace in some top-level tag. For the project I'm working on all the jsp are like this ``` <?xml version="1.0" encoding="UTF-8" ?> <jsp:root version="2.0" xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:fmt="http://java.sun.com/jsp/jstl/fmt" xmlns:fn="http://java.sun.com/jsp/jstl/functions"> <jsp:directive.page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"/> <jsp:text><![CDATA[<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">]]> </jsp:text> <html xmlns="http://www.w3.org/1999/xhtml"> ... </html> </jsp:root> ```
Editing xhtml jsp files in Eclipse
[ "", "java", "eclipse", "jsp", "xhtml", "" ]
I'm trying to make a quick jquery plugin (as a learning exercise) for making a simple pager from a list of items (LIs in this case) and have run into a problem when passing the current selector (this) to a sub-function. The code is below. The problem is when creating the dynamic nav (the plugin requires jquery 1.3) and I need to pass the selector, as it is the sub-function that does the actual showing/hiding that make up the pager. I'm trying the following ``` var selector = $(this); ``` To get the selector, then passing it to the sub-function at the bottom of the script as follows ``` $(".pageNav a").live("click", function(selector) { ``` and hoping to use the selector within the subfunction as follows ``` $(selector).hide(); ``` But i'm getting nothing. Any advice would be appreciated, no need to finish the plugin for me! Thanks ``` (function($) { $.fn.quickPager = function() { //edit this var pageSize = 10; //leave this var selector = $(this); var totalRecords = $(this).length; var currentPage = 1; var pageCounter = 1; $(this).each(function(i){ if(i < pageCounter*pageSize && i >= (pageCounter-1)*pageSize) { $(this).addClass("page"+pageCounter); } else { $(this).addClass("page"+(pageCounter+1)); pageCounter ++; } }); //show/hide the appropriate regions $(this).hide(); $(".page"+currentPage).show(); //first check if there is more than one page. If so, build nav if(pageCounter > 1) { //Build pager navigation var pageNav = "<ul class='pageNav'>"; for (i=1;i<=pageCounter;i++){ if (i==1) { pageNav += "<li class=currentPage pageNav"+i+"'><a rel='"+i+"' href='#'>Page "+i+"</a></li>"; } else { pageNav += "<li class='pageNav"+i+"'><a rel='"+i+"' href='#'>Page "+i+"</a></li>"; } } pageNav += "</ul>"; $("#pagerContainer").append(pageNav); //pager navigation behaviour $(".pageNav a").live("click", function(selector) { //grab the REL attribute var clickedLink = $(this).attr("rel"); currentPage = clickedLink; //remove current current (!) page $("li.currentPage").removeClass("currentPage"); //Add current page highlighting $(this).parent("li").addClass("currentPage"); //hide and show relevant links //$("ul.paging li").text("TEST"); $(selector).hide(); $(selector+".page"+clickedLink).show(); return false; }); } } })(jQuery); ```
``` var selector = $(this); $(".pageNav a").live("click", function() { // do something selector.hide(); }); ```
and change ``` $(selector+".page"+clickedLink).show(); ``` to ``` selector.find(".page"+clickedLink).show(); ``` *selector* is not a string it is a jQuery object which contains all elements that plugin understands as **this**
Passing jquery selector to sub-function within a plugin
[ "", "javascript", "jquery", "function", "jquery-plugins", "" ]
I've been evaluating profilers and memory checking tools for native C++ programs on Windows and all of them want to be installed *and* run with administrator privileges. I rarely log in as admin on my machine. If I need to install something or do something that requires administrative privileges, I use runas and it works pretty well. Is it legitimate for a profiler to require admin privileges, or are the profiler developers just being lazy? Am I being unreasonable by rejecting all of these tools on this basis? I'm developing with VS 2005 on an XP Pro machine.
I've been reading about this and I'm slowly coming to the conclusion that profiler-like tools in general do not require administrative access, but stating that you require it is an easy way for the tool makers to avoid all problems related to insufficient privileges. So, I guess they *are* being lazy but also somewhat pragmatic. Correct me if I'm wrong (I'm no expert on the Windows security model), but I believe one way to handle this situation would be to require admin privileges only at install time. Then create a ProfilerUsers user group and grant any necessary privileges to that group, then ask which computer users should be added to that group. The most shocking thing I've discovered is that a lot of developers run all the time with administrative privileges.
Because they have to look at other process' memory, which is normally taboo.
Why do profilers need administrative privs (on Windows)
[ "", "c++", "visual-studio", "profiling", "privileges", "" ]
Is there a function to extract the extension from a filename?
Use [`os.path.splitext`](https://docs.python.org/3/library/os.path.html#os.path.splitext): ``` >>> import os >>> filename, file_extension = os.path.splitext('/path/to/somefile.ext') >>> filename '/path/to/somefile' >>> file_extension '.ext' ``` Unlike most manual string-splitting attempts, `os.path.splitext` will correctly treat `/a/b.c/d` as having no extension instead of having extension `.c/d`, and it will treat `.bashrc` as having no extension instead of having extension `.bashrc`: ``` >>> os.path.splitext('/a/b.c/d') ('/a/b.c/d', '') >>> os.path.splitext('.bashrc') ('.bashrc', '') ```
*New in version 3.4.* ``` import pathlib print(pathlib.Path('yourPath.example').suffix) # '.example' print(pathlib.Path("hello/foo.bar.tar.gz").suffixes) # ['.bar', '.tar', '.gz'] print(pathlib.Path('/foo/bar.txt').stem) # 'bar' ``` I'm surprised no one has mentioned [`pathlib`](https://docs.python.org/3/library/pathlib.html) yet, `pathlib` IS awesome!
Extracting extension from filename in Python
[ "", "python", "filenames", "file-extension", "" ]
I am looking to do the following with a single database query if possible. ``` public class Location { public string URL {get;set;} public IList<Page> Pages {get;set;} } Page firstPage = Session.Linq<Location>() .Where(location => location.URL == "some-location-url") .Select(location => location.Pages).FirstOrDefault(); ``` My aim is based on the current location url, return the first Page object from its pages collection. I have tried a number of different ways now and they all seem to execute many queries to get the desired Page object out. Any help is appreciated! Dave the Ninja
This might be what your looking for: ``` Page firstPage = Session.Linq<Page>() .OrderBy(page => page.Index) .FirstOrDefault(page=> page.Location.URL == "some-location-url"); ``` I'm making the assumption that the page has a Location property that relates back to the Location it belongs to and the .Index would be the property you want to order with.
Run the query against `Page` instead of against `Location`: you don't need to return the `Location` record at all. ``` (from p in AllPages where p.Location.URL == "some-location-url" select p).FirstOrDefault(); ``` [Almost always when I get stuck with writing a LINQ query, I find it helps to start building the query from the bottom-most object in the parent-child relationships involved.]
How to return first object of a collection from its parent
[ "", "c#", "linq", "nhibernate", "linq-to-nhibernate", "" ]
I have a rectangle in my XAML and want to change its `Canvas.Left` property in code behind: ``` <UserControl x:Class="Second90.Page" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="400" Height="300" KeyDown="txt_KeyDown"> <Canvas> <Rectangle Name="theObject" Canvas.Top="20" Canvas.Left="20" Width="10" Height="10" Fill="Gray"/> </Canvas> </UserControl> ``` But this doesn't work: ``` private void txt_KeyDown(object sender, KeyEventArgs e) { theObject.Canvas.Left = 50; } ``` Does anyone know what the syntax is to do this?
``` Canvas.SetLeft(theObject, 50) ```
Try this ``` theObject.SetValue(Canvas.LeftProperty, 50d); ``` There is a group of methods on DependencyObject (base of most WPF classes) which allow the common access to all dependency properties. They are * SetValue * GetValue * ClearValue **Edit** Updated the set to use a double literal since the target type is a double.
Change Canvas.Left property in code behind?
[ "", "c#", "wpf", "code-behind", "attached-properties", "" ]
I love [Prototype](http://www.prototypejs.org/api) but it doesn't come with any widgets. In particular, it provides nothing for window/dialog creation. I've tried the [Prototype Window](http://prototype-window.xilinus.com/) add-on library but found it unreliable and it hasn't been maintained for a long time. Anyone have any recommended solutions? Or any recipes/patterns for creating a dialog from first principles (i.e. with no library other than Prototype)? I need modal behavior (with faded background effect) and I have to support IE6 as well as modern browsers. Just to be clear, I'm not looking to switch away from Prototype and I don't really want to include an additional base library such as JQuery.
For a really simple dialog, checkout this code: <http://snippets.dzone.com/posts/show/3411> Very minimal and simple - just what I wanted. The code went through a few modifications. Here's the final version that worked for me: ``` /* * Adapted from http://snippets.dzone.com/posts/show/3411 */ var Dialog = {}; Dialog.Box = Class.create(); Object.extend(Dialog.Box.prototype, { initialize: function(id) { this.createOverlay(); this.dialog_box = $(id); this.dialog_box.show = this.show.bind(this); this.dialog_box.persistent_show = this.persistent_show.bind(this); this.dialog_box.hide = this.hide.bind(this); this.parent_element = this.dialog_box.parentNode; this.dialog_box.style.position = "absolute"; var e_dims = Element.getDimensions(this.dialog_box); var b_dims = Element.getDimensions(this.overlay); this.dialog_box.style.left = ((b_dims.width/2) - (e_dims.width/2)) + 'px'; this.dialog_box.style.top = this.getScrollTop() + ((this.winHeight() - (e_dims.width/2))/2) + 'px'; this.dialog_box.style.zIndex = this.overlay.style.zIndex + 1; }, createOverlay: function() { if ($('dialog_overlay')) { this.overlay = $('dialog_overlay'); } else { this.overlay = document.createElement('div'); this.overlay.id = 'dialog_overlay'; Object.extend(this.overlay.style, { position: 'absolute', top: 0, left: 0, zIndex: 90, width: '100%', backgroundColor: '#000', display: 'none' }); document.body.insertBefore(this.overlay, document.body.childNodes[0]); } }, moveDialogBox: function(where) { Element.remove(this.dialog_box); if (where == 'back') this.dialog_box = this.parent_element.appendChild(this.dialog_box); else this.dialog_box = this.overlay.parentNode.insertBefore(this.dialog_box, this.overlay); }, show: function(optHeight/* optionally override the derived height, which often seems to be short. */) { this.overlay.style.height = this.winHeight()+'px'; this.moveDialogBox('out'); this.overlay.onclick = this.hide.bind(this); this.selectBoxes('hide'); new Effect.Appear(this.overlay, {duration: 0.1, from: 0.0, to: 0.3}); this.dialog_box.style.display = ''; this.dialog_box.style.left = '0px'; var e_dims = Element.getDimensions(this.dialog_box); this.dialog_box.style.left = (this.winWidth() - e_dims.width)/2 + 'px'; var h = optHeight || (e_dims.height + 200); this.dialog_box.style.top = this.getScrollTop() + (this.winHeight() - h/2)/2 + 'px'; }, getScrollTop: function() { return (window.pageYOffset)?window.pageYOffset:(document.documentElement && document.documentElement.scrollTop)?document.documentElement.scrollTop:document.body.scrollTop; }, persistent_show: function() { this.overlay.style.height = this.winHeight()+'px'; this.moveDialogBox('out'); this.selectBoxes('hide'); new Effect.Appear(this.overlay, {duration: 0.1, from: 0.0, to: 0.3}); this.dialog_box.style.display = ''; this.dialog_box.style.left = '0px'; var e_dims = Element.getDimensions(this.dialog_box); this.dialog_box.style.left = (this.winWidth()/2 - e_dims.width/2) + 'px'; }, hide: function() { this.selectBoxes('show'); new Effect.Fade(this.overlay, {duration: 0.1}); this.dialog_box.style.display = 'none'; this.moveDialogBox('back'); $A(this.dialog_box.getElementsByTagName('input')).each( function(e) { if (e.type != 'submit' && e.type != 'button') e.value = ''; }); }, selectBoxes: function(what) { $A(document.getElementsByTagName('select')).each(function(select) { Element[what](select); }); if (what == 'hide') $A(this.dialog_box.getElementsByTagName('select')).each(function(select){Element.show(select)}) }, winWidth: function() { if (typeof window.innerWidth != 'undefined') return window.innerWidth; if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientWidth != 'undefined' && document.documentElement.clientWidth != 0) return document.documentElement.clientWidth; return document.getElementsByTagName('body')[0].clientWidth }, winHeight: function() { if (typeof window.innerHeight != 'undefined') return window.innerHeight if (typeof document.documentElement != 'undefined' && typeof document.documentElement.clientHeight != 'undefined' && document.documentElement.clientHeight != 0) return document.documentElement.clientHeight; return document.getElementsByTagName('body')[0].clientHeight; } }); ```
There are a few good sites to look at: [Prototype UI](http://prototype-ui.com/) - which has a modal dialog. [Scripteka](http://scripteka.com/) - The mother lode of Prototype add-ons. Lots of great stuff here.
Best technique for DHTML windows/dialogs in Prototype?
[ "", "javascript", "prototypejs", "dhtml", "" ]
How should I read any header in PHP? For example the custom header: `X-Requested-With`.
**IF**: you only need a single header, instead of *all* headers, the quickest method is: ``` <?php // Replace XXXXXX_XXXX with the name of the header you need in UPPERCASE (and with '-' replaced by '_') $headerStringValue = $_SERVER['HTTP_XXXXXX_XXXX']; ``` **ELSE IF**: you run PHP as an Apache module or, as of PHP 5.4, using FastCGI (simple method): [apache\_request\_headers()](http://www.php.net/apache_request_headers) ``` <?php $headers = apache_request_headers(); foreach ($headers as $header => $value) { echo "$header: $value <br />\n"; } ``` **ELSE:** In any other case, you can use (userland implementation): ``` <?php function getRequestHeaders() { $headers = array(); foreach($_SERVER as $key => $value) { if (substr($key, 0, 5) <> 'HTTP_') { continue; } $header = str_replace(' ', '-', ucwords(str_replace('_', ' ', strtolower(substr($key, 5))))); $headers[$header] = $value; } return $headers; } $headers = getRequestHeaders(); foreach ($headers as $header => $value) { echo "$header: $value <br />\n"; } ``` **See Also**: [getallheaders()](http://php.net/manual/en/function.getallheaders.php) - (PHP >= 5.4) ~~cross platform edition~~ Alias of `apache_request_headers()` [apache\_response\_headers()](http://www.php.net/manual/en/function.apache-response-headers.php) - Fetch all HTTP response headers. [headers\_list()](http://www.php.net/manual/en/function.headers-list.php) - Fetch a list of headers to be sent.
``` $_SERVER['HTTP_X_REQUESTED_WITH'] ``` [RFC3875](http://www.faqs.org/rfcs/rfc3875.html), 4.1.18: > Meta-variables with names beginning with `HTTP_` contain values read from the client request header fields, if the protocol used is HTTP. The HTTP header field name is converted to upper case, has all occurrences of `-` replaced with `_` and has `HTTP_` prepended to give the meta-variable name.
How do I read any request header in PHP?
[ "", "php", "http-headers", "" ]
I've only dealt with one-to-one relationships in php so far, but I'm stuck on a problem which involves a one-to-many relationship. I've been sitting on this for a few days with no luck, so I'm desperate for someone to step in and show me a solution before I lose my mind. In my database have a series of urls, which are received by a SELECT query along with various other fields, from different tables. Every url has at least one category associated with it, but can have multiple categories. So in my results I might see something that looks a bit like this: ``` link_id = 3 url= 'http://www.somesite1.com' category = 'uncategorised' link_id = 4 url= 'http://www.somesite2.com' category = 'travel' link_id = 4 url= 'http://www.somesite2.com' category = 'fun' link_id = 4 url= 'http://www.somesite2.com' category = 'misc' link_id = 3 url= 'http://www.somesite3.com' category = 'uncategorised' ``` I have got this to work, kind of. When I loop through and print them off, using a while loop and mysql fetch array, the result looks exactly like it does above. Thats great, except what I need is for it to read something like: ``` link_id = 4 url = 'http://www.somesite2.com' category = 'travel fun misc' ``` So that basically all of the categories for each url get combined somehow, as they are printed out. My first attempt led me to try a nested while loop, but it didn't work and i'm not sure if this is feasible. Apart from that I'm wondering if I might need a multidimensional array (complete guess, i've never had to use one before). I'm ordering these results by link id as above, so I know if the link id in the current loop iteration, matches the one in the last iteration - then I have something which has more than one category.. I think I'm really close, but I just can't figure it out. Any ideas?
There is also the "GROUP\_CONCAT" function in mysql. That should do exactly what you want to achieve. Something like : ``` SELECT url, GROUP_CONCAT(category) AS categories FROM yourtable GROUP BY url ```
You should be using a connection table. 1st you have a table of links ``` id = 1 url = something id = 2 url = something else ``` Then you have a table of categories ``` id = 1 category = something id = 2 category = something else ``` Then you have a connection table ``` url_id = 1 category_id = 1 url_id = 1 category_id = 2 url_id = 2 category_id = 1 ``` This should atleast get you started.
PHP and outputting one-to-many results
[ "", "php", "mysql", "database", "one-to-many", "" ]
I've been reading a lot about asynchronous programming recently, as I need to create a multi-threaded application. Unfortunately I can't seem to bring my newly acquired knowledge together into one cohesive and useful unit! I'm hoping someone can give me some pointers on how to construct the following: * I have a class that does a lot of different (and time-consuming) tasks in a specified sequence. * I'd like to instantiate this class in my Winforms UI thread. eg: ``` TaskRunner tr = new TaskRunner(); ``` * I'd like to be able to call a BeginAsync() method (as you can do with lots of the .NET built-in objects). eg: ``` tr.BeginAsync(); ``` * I'd like my class to callback to my UI thread when certain events arise (for logging, completion etc). * I'd like to be able to cancel the execution of my class. eg: ``` tr.CancelAsync(); ``` How do I go about building the internals of that class? I can't seem to find anything that talks about how the internals of SqlCommand or WebRequest might work.
For this operation, you want to use the event-based asynchronous pattern (as opposed to the IAsyncResult design pattern). For more information, see the section of the MSDN documentation titled "Event-based Asynchronous Pattern Overview", located at: <http://msdn.microsoft.com/en-us/library/wewwczdw.aspx>
Hope, this example will help you. ``` public class MessagingServices { public static IAsyncResult BeginReverseEcho (TcpClient client, AsyncCallback callback, object userState) { var re = new ReverseEcho( ); re.Begin (client, callback, userState); return re; } public static byte[] EndReverseEcho (IAsyncResult r) { return ((ReverseEcho)r).End( ); } } class ReverseEcho : IAsyncResult { volatile TcpClient _client; volatile NetworkStream _stream; volatile object _userState; volatile AsyncCallback _callback; ManualResetEvent _waitHandle = new ManualResetEvent (false); volatile int _bytesRead = 0; byte[] _data = new byte [5000]; volatile Exception _exception; internal ReverseEcho( ) { } // IAsyncResult members: public object AsyncState { get { return _userState; } } public WaitHandle AsyncWaitHandle { get { return _waitHandle; } } public bool CompletedSynchronously { get { return false; } } public bool IsCompleted { get { return _waitHandle.WaitOne (0, false); } } internal void Begin (TcpClient c, AsyncCallback callback, object state) { _client = c; _callback = callback; _userState = state; try { _stream = _client.GetStream( ); Read( ); } catch (Exception ex) { ProcessException (ex); } } internal byte[] End( ) // Wait for completion + rethrow any error. { AsyncWaitHandle.WaitOne( ); AsyncWaitHandle.Close( ); if (_exception != null) throw _exception; return _data; } void Read( ) // This is always called from an exception-handled method { _stream.BeginRead (_data, _bytesRead, _data.Length - _bytesRead, ReadCallback, null); } void ReadCallback (IAsyncResult r) { try { int chunkSize = _stream.EndRead (r); _bytesRead += chunkSize; if (chunkSize > 0 && _bytesRead < _data.Length) { Read( ); // More data to read! return; } Array.Reverse (_data); _stream.BeginWrite (_data, 0, _data.Length, WriteCallback, null); } catch (Exception ex) { ProcessException (ex); } } void WriteCallback (IAsyncResult r) { try { _stream.EndWrite (r); } catch (Exception ex) { ProcessException (ex); return; } Cleanup( ); } void ProcessException (Exception ex) { _exception = ex; // This exception will get rethrown when Cleanup(); // the consumer calls the End( ) method. } void Cleanup( ) { try { if (_stream != null) _stream.Close( ); } catch (Exception ex) { if (_exception != null) _exception = ex; } // Signal that we're done and fire the callback. _waitHandle.Set( ); if (_callback != null) _callback (this); } } ``` Example is taken from C# 3.0 in a Nutshell, 3rd Edition by Joseph Albahari; Ben Albahari
How do I create a class with asynchronous capabilities (similiar to SqlCommand or WebRequest)?
[ "", "c#", "winforms", "asynchronous", "callback", "" ]
From what time I've spent with threads in `Java`, I've found these two ways to write threads: With **implements `Runnable`:** ``` public class MyRunnable implements Runnable { public void run() { //Code } } //Started with a "new Thread(new MyRunnable()).start()" call ``` Or, with **extends `Thread`:** ``` public class MyThread extends Thread { public MyThread() { super("MyThread"); } public void run() { //Code } } //Started with a "new MyThread().start()" call ``` Is there any significant difference in these two blocks of code?
Yes: implements `Runnable` is the preferred way to do it, IMO. You're not really specialising the thread's behaviour. You're just giving it something to run. That means [composition](http://en.wikipedia.org/wiki/Object_composition) is the *philosophically* "purer" way to go. In *practical* terms, it means you can implement `Runnable` and extend from another class as well... and you can also implement `Runnable` via a lambda expression as of Java 8.
**tl;dr: implements Runnable is better. However, the caveat is important**. In general, I would recommend using something like `Runnable` rather than `Thread` because it allows you to keep your work only loosely coupled with your choice of concurrency. For example, if you use a `Runnable` and decide later on that this doesn't in fact require its own `Thread`, you can just call threadA.run(). **Caveat:** Around here, I strongly discourage the use of raw Threads. I much prefer the use of [Callables](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Callable.html) and [FutureTasks](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/FutureTask.html) (From the javadoc: "A cancellable asynchronous computation"). The integration of timeouts, proper cancelling and the thread pooling of the modern concurrency support are all much more useful to me than piles of raw Threads. **Follow-up:** There is a [`FutureTask` constructor](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/FutureTask.html#FutureTask-java.lang.Runnable-V-) that allows you to use Runnables (if that's what you are most comfortable with) and still get the benefit of the modern concurrency tools. [To quote the javadoc](https://docs.oracle.com/javase/8/docs/api/java/util/concurrent/FutureTask.html#FutureTask-java.lang.Runnable-V-): If you don't need a particular result, consider using constructions of the form: ``` Future<?> f = new FutureTask<Object>(runnable, null) ``` So, if we replace their `runnable` with your `threadA`, we get the following: ``` new FutureTask<Object>(threadA, null) ``` Another option that allows you to stay closer to Runnables is a [ThreadPoolExecutor](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html). You can use the [execute](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/ThreadPoolExecutor.html#execute%28java.lang.Runnable%29) method to pass in a Runnable to execute "the given task sometime in the future". If you'd like to try using a thread pool, the code fragment above would become something like the following (using the [Executors.newCachedThreadPool()](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newCachedThreadPool%28%29) factory method): ``` ExecutorService es = Executors.newCachedThreadPool(); es.execute(new ThreadA()); ```
"implements Runnable" vs "extends Thread" in Java
[ "", "java", "multithreading", "runnable", "implements", "java-threads", "" ]
I am reading through a directory with some pictures and such using a pretty simple implementation of readdir() like the following: ``` if ($handle = opendir($path)) { while (false !== ($szFilename = readdir($handle))) { if ($szFilename[0] !== '.') { if (is_file($path.$szFilename)) { // do stuff } } } } ``` The problem that I am having is that the files are not being read in alphabetical order as the docs for readdir() state: > Returns the filename of the next file > from the directory. The filenames are > returned in the order in which they > are stored by the filesystem. Another weird thing is that, on the local testing server, the same code works great. This is running on a server using the LAMP stack in both cases. I know that I can build an array and just sort it, but I was wondering if I was missing something in what I was doing.
Alphabetical order :: I think you misread the snippet you quoted... > Returns the filename of the next file from the directory. The filenames are returned in the order in which they are stored by the filesystem. The fact that 'ls' would display the files in (usually) alphabetical order does not mean that's how they are stored on the filesystem. PHP is behaving as spec, I'm afraid. You may want to consider using [scandir](https://www.php.net/manual/en/function.scandir.php) as the basis for your efforts, if alphabetical sorting is a must. :)
You could copy all the filenames into an array and then use ``` <?php sort($filesArray); ?> ```
PHP readdir() not returning files in alphabetical order
[ "", "php", "" ]
I am using a pre-build task in Visual Studio 2008 that invokes msbuild: ``` C:\WINDOWS\Microsoft.NET\Framework\v3.5\MSBuild.exe $(MSBuildProjectDirectory)\version.targets /p:Configuration=$(ConfigurationName) ``` Inside version.targets, I am updating the AssemblyInfo.cs file to replace version information: ``` <FileUpdate Encoding="ASCII" Files="$(MSBuildProjectDirectory)\Properties\AssemblyInfo.cs" Regex="AssemblyInformationalVersion\(&quot;.*&quot;\)\]" ReplacementText="AssemblyInformationalVersion(&quot;Product $(ConfigurationString) ($(buildDate))&quot;)]" /> ``` When I build the project through Visual Studio 2008, it builds without any problems. But when I look at the resulting exe's version information, it contains the previous time stamp even though the AssemblyInfo.cs has been changed with the "correct" one. It seems that the pre-build's changes aren't seen by the main compilation task and it's always one behind. Any ideas of what I'm doing wrong?
I don't think you are doing anything wrong - it's a bug. I have reported it [here](https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=423670) - check if you can reproduce it and add a validation, maybe we can get it fixed by MS. EDIT: I tried the suggestion by "Si" to update the file in the "BeforeBuild" event - however I still get the same wrong result with Visual Studio 2008/SP1. **UPDATE/WORKAROUND**: MS has responded to the bug report. As a workaround you can add ``` <UseHostCompilerIfAvailable>FALSE</UseHostCompilerIfAvailable> ``` to your csproj file.
+1 for the `<UseHostCompilerIfAvailable>FALSE</UseHostCompilerIfAvailable>` trick, although neither the accepted solution nor the linked article specified that **the line should be added to the *first* `<PropertyGroup>` element in the `.csproj` file**. It is also a problem with Visual Studio only, as invoking **msbuild** from the command-line on the same `.csproj` file (without the trick) will see the generated code files compiled right away (and not the previous versions). Also, I would like to recommend that this topic be tagged with the following, as I had to dig a lot to find it: 1. VisualStudio 2. compiler 3. BeforeBuild 4. generated 5. .NET 6. c#
Pre-build MSBuild task to update AssemblyInfo not in sync with built exe
[ "", "c#", "visual-studio", "msbuild", "prebuild", "generated", "" ]
I have a search screen in a Visual Basic .Net App that has text boxes for: 1. First Name Varchar(50) 2. Last Name Varchar(50) 3. Middle Name Varchar(50) 4. DOB DateTime 5. Home Phone Varchar(10) 6. Work Phone Varchar(10) How would I create a stored procedure in SQL Server 2000 that would allow me to be able to search on all/some/one of the fields. If user only enters data on say first name and home phone number what would I need to do for the rest of the parameters where data was not entered. I tried the select statement below but it doesn't work properly. ``` Select Last_Name, First_Name, Mid_Name, DOB, Home_Phone, Work_Phone from dbo.tblClient Where Last_Name Like '%@LastName' and First_Name Like '%@FirstName' and Mid_Name Like '%@MiddleName' and DOB Like '%DOB' and Home_Phone Like '%@HomePhone' and Work_Phone Like '%@WorkPhone' ```
I use this pattern a lot: ``` Select Last_Name, First_Name, Mid_Name, DOB, Home_Phone, Work_Phone from dbo.tblClient Where (@LastName is null or Last_Name Like '%'+ @LastName) and (@FirstName is null or First_Name Like '%'+ @FirstName) and (@HomePhone is null or Home_Phone Like '%'+ @HomePhone) -- etc... ``` It will ignore anything that's not supplied, while still giving good performance. Better still, it doesn't resort to dynamic SQL to pull it off.
How about using ISNULL() function to determine if a value has been passed into the stored procedure and if not, setting the WHERE clause field value to search for equal to itself in each case (*if someone can think of a better choice of words for describing this, I will update the answer*). ``` SELECT Last_Name, First_Name, Mid_Name, DOB, Home_Phone, Work_Phone FROM dbo.tblClient WHERE Last_Name LIKE '%' + ISNULL(@LastName, Last_Name) AND First_Name LIKE '%' + ISNULL(@FirstName, First_Name) AND Mid_Name LIKE '%' ISNULL(@MiddleName, Mid_Name) AND DOB LIKE '%' + ISNULL(@DOB, DOB) AND Home_Phone LIKE '%' + ISNULL(@HomePhone, Home_Phone) AND Work_Phone LIKE '%' + ISNULL(@WorkPhone, Work_Phone) ``` You could also set a NULL default value for each of your stored procedure parameters.
Multiple Parameter Search in SQL Server 2000
[ "", "sql", "sql-server", "vb.net", "" ]
Hello i been trying to get a tokenizer to work using the boost library tokenizer class. I found this tutorial on the boost documentation: [http://www.boost.org/doc/libs/1 \_36 \_0/libs/tokenizer/escaped \_list \_separator.htm](http://www.boost.org/doc/libs/1_36_0/libs/tokenizer/escaped_list_separator.htm) problem is i cant get the argument's to escaped \_list \_separator("","",""); but if i modify the boost/tokenizer.hpp file it work's. but that's not and ideal solution was wondering if there's anything i am missing to get diferent arguments into the escaped \_list \_separator. i want to make it split on spaces with " and ' for escaping and with no escape character inside the quoted string. this is used for a argument parsing system in a ingame console system. ``` #include <iostream> #include <boost/tokenizer.hpp> #include <string> int main() { using namespace std; using namespace boost; string s = "exec script1 \"script argument number one\""; string separator1("");//dont let quoted arguments escape themselves string separator2(" ");//split on spaces string separator3("\"\'");//let it have quoted arguments tokenizer<escaped_list_separator<char>(separator1,separator2,separator3)> tok(s); for(tokenizer<escaped_list_separator<char>(separator1,separator2,separator3)>::iterator beg=tok.begin(); beg!=tok.end();++beg) { cout << *beg << "\n"; } } ``` the error from visual studio 2005 is error C2974: 'boost::tokenizer' : invalid template argument for 'TokenizerFunc', type expected EDIT: This question was awnsered by ferrucio and explained by peter thank's everybody.
try this: ``` #include <iostream> #include <boost/tokenizer.hpp> #include <string> int main() { using namespace std; using namespace boost; string s = "exec script1 \"script argument number one\""; string separator1("");//dont let quoted arguments escape themselves string separator2(" ");//split on spaces string separator3("\"\'");//let it have quoted arguments escaped_list_separator<char> els(separator1,separator2,separator3); tokenizer<escaped_list_separator<char>> tok(s, els); for(tokenizer<escaped_list_separator<char>>::iterator beg=tok.begin(); beg!=tok.end();++beg) { cout << *beg << "\n"; } } ```
It seems like you're declaring your tokenizer type incorrectly. ``` typedef boost::tokenizer< boost::escaped_list_separator<char> > Tokenizer; boost::escaped_list_separator<char> Separator( '\\', ' ', '\"' ); Tokenizer tok( s, Separator ); for( Tokenizer::iterator iter = tok.begin(); iter != tok.end(); ++iter ) { cout << *iter << "\n"; } ``` You want to make a `boost::tokenizer< boost::escaped_list_separator< char > >` typed object with a `boost::escaped_list_separator< char >` separator object as its TokenizerFunc.
Using Boost Tokenizer escaped_list_separator with different parameters
[ "", "c++", "string", "boost", "tokenize", "" ]
I have a website in which I send a confirmation mail as part of the registration process. Some time ago, I had some troubles with the mails I sent since I used no headers (PHP mail function). Once I put some headers, I've gotten more responses from users, but I suspect that not every message reaches its destination. How can I be sure that the messages reach their destination? Which are the headers that can be considered a 'must'? This is the code of my SendMail function ``` mail($to, $subject, $message, "MIME-Version: 1.0\n". "Content-type: text/plain; charset=ISO-8859-1; format=flowder\n". "Content-Transfer-Encoding: 8bit\n". "Message-Id: <" . md5(uniqid(microtime())) . "@mysite.com>\n". "Return-Path: <admin@mysite.com>\n". "X-Mailer: PHP v".phpversion()."\n". "From: admin@ mysite.com"); ```
The headers need a white space at the bottom to separate the header from main body. Tools like Spam Assassin will give you a big mark down for that. Also you should use `\r\n` as a line terminator instead of just `\n` [From PHP.net](http://is.php.net/manual/en/function.mail.php) > Multiple extra headers should be separated with a CRLF (\r\n).
You should use external library for working with e-mails in php like [PhpMailer](http://phpmailer.codeworxtech.com) , [SwiftMailer](http://www.swiftmailer.org/) or [Zend\_Mail](http://framework.zend.com/manual/en/zend.mail.html). All your problems will go away.
Required Mail Headers
[ "", "php", "email", "" ]
C#: I want to pass messages like a file path to my forms application like a console application, how would I do that? I was told I needed to find my main method to add string[] args, but I wouldn't know which one that would be in Windows Forms. Which would my main method be in C# windows forms application?
Ok, string[] args = Environment.GetCommandLineArgs() is a better option. But I will keep the following answer as an alternative to it. Look for a file called Program.cs containing the following code fragment... ``` static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } ``` and change that to ``` static class Program { public static string[] CommandLineArgs { get; private set;} /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main(string[] args) { CommandLineArgs = args; Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } } ``` Then access the command line args from your form ... ``` Program.CommandLineArgs ```
Your `Main()` method is located in `Program.cs` file, typically like this: ``` [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } ``` You should modify the `Main()` to the following: ``` static void Main(string[] args) ``` You'll have access to the arguments passed. Also, you could access the arguments using `Environment.GetCommandLineArgs()`
C#: I want to pass messages like a file path to my forms application like a console application, how would I do that?
[ "", "c#", "winforms", "command-line", "arguments", "" ]
## **Questions:** 1. What is the best practice for keeping track of a thread's progress without locking the GUI ("Not Responding")? 2. Generally, what are the best practices for threading as it applies to GUI development? ## **Question Background:** * I have a PyQt GUI for Windows. * It is used to process sets of HTML documents. * It takes anywhere from three seconds to three hours to process a set of documents. * I want to be able to process multiple sets at the same time. * I don't want the GUI to lock. * I'm looking at the threading module to achieve this. * I am relatively new to threading. * The GUI has one progress bar. * I want it to display the progress of the selected thread. * Display results of the selected thread if it's finished. * I'm using Python 2.5. **My Idea:** Have the threads emit a QtSignal when the progress is updated that triggers some function that updates the progress bar. Also signal when finished processing so results can be displayed. ``` #NOTE: this is example code for my idea, you do not have # to read this to answer the question(s). import threading from PyQt4 import QtCore, QtGui import re import copy class ProcessingThread(threading.Thread, QtCore.QObject): __pyqtSignals__ = ( "progressUpdated(str)", "resultsReady(str)") def __init__(self, docs): self.docs = docs self.progress = 0 #int between 0 and 100 self.results = [] threading.Thread.__init__(self) def getResults(self): return copy.deepcopy(self.results) def run(self): num_docs = len(self.docs) - 1 for i, doc in enumerate(self.docs): processed_doc = self.processDoc(doc) self.results.append(processed_doc) new_progress = int((float(i)/num_docs)*100) #emit signal only if progress has changed if self.progress != new_progress: self.emit(QtCore.SIGNAL("progressUpdated(str)"), self.getName()) self.progress = new_progress if self.progress == 100: self.emit(QtCore.SIGNAL("resultsReady(str)"), self.getName()) def processDoc(self, doc): ''' this is tivial for shortness sake ''' return re.findall('<a [^>]*>.*?</a>', doc) class GuiApp(QtGui.QMainWindow): def __init__(self): self.processing_threads = {} #{'thread_name': Thread(processing_thread)} self.progress_object = {} #{'thread_name': int(thread_progress)} self.results_object = {} #{'thread_name': []} self.selected_thread = '' #'thread_name' def processDocs(self, docs): #create new thread p_thread = ProcessingThread(docs) thread_name = "example_thread_name" p_thread.setName(thread_name) p_thread.start() #add thread to dict of threads self.processing_threads[thread_name] = p_thread #init progress_object for this thread self.progress_object[thread_name] = p_thread.progress #connect thread signals to GuiApp functions QtCore.QObject.connect(p_thread, QtCore.SIGNAL('progressUpdated(str)'), self.updateProgressObject(thread_name)) QtCore.QObject.connect(p_thread, QtCore.SIGNAL('resultsReady(str)'), self.updateResultsObject(thread_name)) def updateProgressObject(self, thread_name): #update progress_object for all threads self.progress_object[thread_name] = self.processing_threads[thread_name].progress #update progress bar for selected thread if self.selected_thread == thread_name: self.setProgressBar(self.progress_object[self.selected_thread]) def updateResultsObject(self, thread_name): #update results_object for thread with results self.results_object[thread_name] = self.processing_threads[thread_name].getResults() #update results widget for selected thread try: self.setResultsWidget(self.results_object[thread_name]) except KeyError: self.setResultsWidget(None) ``` Any commentary on this approach (e.g. drawbacks, pitfalls, praises, etc.) will be appreciated. ## **Resolution:** I ended up using the QThread class and associated signals and slots to communicate between threads. This is primarily because my program already uses Qt/PyQt4 for the GUI objects/widgets. This solution also required fewer changes to my existing code to implement. Here is a link to an applicable Qt article that explains how Qt handles threads and signals, <http://www.linuxjournal.com/article/9602>. Excerpt below: > Fortunately, Qt permits > signals and slots to be connected > across threads—as long as the threads > are running their own event loops. > This is a much cleaner method of > communication compared to sending and > receiving events, because it avoids > all the bookkeeping and intermediate > QEvent-derived classes that become > necessary in any nontrivial > application. Communicating between > threads now becomes a matter of > connecting signals from one thread to > the slots in another, and the mutexing > and thread-safety issues of exchanging > data between threads are handled by > Qt. > > Why is it necessary to run an event > loop within each thread to which you > want to connect signals? The reason > has to do with the inter-thread > communication mechanism used by Qt > when connecting signals from one > thread to the slot of another thread. > When such a connection is made, it is > referred to as a queued connection. > When signals are emitted through a > queued connection, the slot is invoked > the next time the destination object's > event loop is executed. If the slot > had instead been invoked directly by a > signal from another thread, that slot > would execute in the same context as > the calling thread. Normally, this is > not what you want (and especially not > what you want if you are using a > database connection, as the database > connection can be used only by the > thread that created it). The queued > connection properly dispatches the > signal to the thread object and > invokes its slot in its own context by > piggy-backing on the event system. > This is precisely what we want for > inter-thread communication in which > some of the threads are handling > database connections. The Qt > signal/slot mechanism is at root an > implementation of the inter-thread > event-passing scheme outlined above, > but with a much cleaner and > easier-to-use interface. **NOTE:** *eliben* also has a good answer, and if I weren't using PyQt4, which handles thread-safety and mutexing, his solution would have been my choice.
If you want to use signals to indicate progress to the main thread then you should really be using PyQt's QThread class instead of the Thread class from Python's threading module. A simple example which uses QThread, signals and slots can be found on the PyQt Wiki: <https://wiki.python.org/moin/PyQt/Threading,_Signals_and_Slots>
Native python queues won't work because you have to block on queue get(), which bungs up your UI. Qt essentially implements a queuing system on the inside for cross thread communication. Try this call from any thread to post a call to a slot. QtCore.QMetaObject.invokeMethod() It's clunky and is poorly documented, but it should do what you want even from from a non-Qt thread. You can also use event machinery for this. See QApplication (or QCoreApplication) for a method named something like "post". Edit: Here's a more complete example... I created my own class based on QWidget. It has a slot that accepts a string; I define it like this: ``` @QtCore.pyqtSlot(str) def add_text(self, text): ... ``` Later, I create an instance of this widget in the main GUI thread. From the main GUI thread or any other thread (knock on wood) I can call: ``` QtCore.QMetaObject.invokeMethod(mywidget, "add_text", QtCore.Q_ARG(str,"hello world")) ``` Clunky, but it gets you there. Dan.
PyQt: How to update progress without freezing the GUI?
[ "", "python", "multithreading", "user-interface", "pyqt", "qthread", "" ]
I have the following: ``` var o = {f: function(fn) { fn.call(o); }}; var ob = {f: function() { o.f(function() { this.x = 2; //HERE: how can this reference ob? //ob.x = 2; }); }}; ob.f(); ob.x; // undefined ``` `o.f(fn)` calls `fn` where `this` is bound to o. At HERE, I want to use `this` to access ob. However, when `ob.f` is called, `this` is bound to `o`. JQuery works like this, I think. For example: ``` $(...).blah(function() { this // this is bound to $(...) jquery object. ... }; ``` What I'm doing now is: ``` var Ob = function() { var self = this; self.f = function() { o.f(function() { self.x = 2; }; }; }; var ob = new Ob(); ob.f(); ob.x; // 2 ``` But I don't like above for stylistic reasons: 1. Using the `new` operator sounds like too classical OOP. 2. Defining `class Ob` using `function` isn't intuitive (at least in the beginning). That's why I am trying to define `ob` with an object literal. But I can't find a way to reference the object `ob` in a function that uses method call that sets `this` to other object than `ob`. I can do something like the following: ``` var ob = {f: function() { o.f(function() { self.x = 2; }); }}; var self = ob; ob.f(); ob.x; ``` But I don't know how to factor above. I tried: ``` function obj(o) { return function() { var self = o; return o; }(); } var ob = obj({f: function() { o.f(function() { self.x = 2; }); }}); ob.f(); ob.x;// ReferenceError: self is not defined ``` So, is there a way to reference the object in a function inside the object reliably (`this` can bound to anything depending on the context)?
Following Douglas Crockfords simple constructor pattern, I would make a constructor-function that uses the object literal instead of new. Like this: ``` var o = {f: function(fn) { fn.call(o); }}; function obj() { var me = {}; me.f = function () { o.f(function() { me.x = 2; }); }; return me; } var ob = obj(); ob.f(); ob.x; // 2 ```
In JavaScript, functions are objects, having two methods to invoke the function: ``` call(scope, arg1, arg2, ...); apply(scope, args); // args is an array of arguments to call the function with ``` The first argument, 'scope', is the object that is bound to 'this' within the function. So, the following examples are equivalent: ``` obj.method(1, 2, 3); obj.method.call(obj, 1, 2, 3); obj.method.apply(obj, [1, 2, 3]); ``` In your first example, you are calling the function passed to o.f() using 'o' as scope: ``` var o = {f: function(fn) { fn.call(o); }}; ``` Therefore your function passed in 'ob' references 'o' as this: ``` var ob = {f: function() { o.f(function() { this.x = 2; //HERE: how can this reference ob? //ob.x = 2; }); }}; ``` In the line 'HERE', 'this' is actually 'o'. You could try the following: ``` var ob = {f: function() { var self = this; o.f(function() { self.x = 2; // self is ob now }); }}; ``` Or you could modify the function 'o.f' to take a scope parameter: ``` var o = {f: function(fn, scope) { fn.call(scope || this); // Uses the given scope or this (= 'o') if no scope is provided }}; ``` Then you can pass 'this' in 'ob': ``` var ob = {f: function() { o.f(function() { this.x = 2; // 'this' will be the 'outer' this }, this); // Here: this as scope }}; ```
How can I reference an object inside one of its member functions?
[ "", "javascript", "oop", "this", "" ]
I'm writing a JavaScript widget, which is intended for use on other website and loads additional script files from my own web site (which basically means no XHR due to cross-domain limitations). Now I want to handle failures gracefully - if one script fails to load, I want to load the script from an alternate server. I managed to handle server failures where the 1st server returns an error, but I also want to handle a timeout - if the 1st server takes too long to respond I want to abort the load and switch to the alternate. The problem I have is that I can setup a timeout to trigger a method that switches to the alternate server, but the script from the alternate server doesn't load successfully until the browser itself times-out on the original request - which is way too long for my needs. I want to be able to - while the 1st <script> tag is loading - abort the load, and add a second <script> tag that points to the alternate server. I've tried setting the original script's src attribute to null, and even removing the tag from the HEAD element using removeNode(), but to no effect. This all was tried on Firefox - I haven't tried IE yet, but the solution has to work on both. I'd love to hear any suggestions.
Unfortunately it's not possible to cancel the request for tags. Historically browsers only allow 2 requests at the same time to one hostname, so it should be possible to load the second script from another server. Do you initiate the script loading before body.onload? For a normal page load the browser waits for each script to load before continuing since the scripts can alter the document. If the script is not modifying the document, you can use the defer attribute so the browser continues to render the document while your script loads. jQuery has a few open requests on a similar feature: <http://dev.jquery.com/ticket/1863> <http://dev.jquery.com/ticket/3442>
If you can modify the script that's being loaded you can add a callback there. Just set a timer at the top of the your page and clear it at the bottom of your script file. This way if your script doesn't load properly, the backup request will be executed when the timer runs out. At the top of your page run the following in an inline script block: ``` doneLoading = function() { clearTimeout(timeout); } timeout = setTimeout(function() { ... change the .src on the old inline script element here ... }, 15000); ``` At the bottom of your external JavaScript file just call `doneLoading()`. If your initial request takes longer than 15 seconds, a new request to a backup server will run. I don't think you can abort the initial request, but the backup request will execute as expected.
How to abort the loading of an external HTML resource, from JavaScript?
[ "", "javascript", "browser", "dynamic-loading", "" ]
I've written a asp.net app and one of my postback routines simply saves user submitted form data to a sql 2005 db. All runs great on my development machine but when I deploy to the live site I'm getting invalid dates from my parse date checker. Basically it is expecting an american date format on the live machine but this is not what I want. The user needs to be able to enter in dd/MM/yyyy format. So a valid date like 21/10/2009 returns errors on live server but not on my dev machine. Below is the code that throws the exception. ``` DateTime dt; dt = DateTime.Parse(sdate); //sdate in GB dd/MM/yyyy format ``` Is it possible to force the parse routine to expect the date in dd/MM/yyyy format?
Do like this: ``` System.Globalization.CultureInfo cultureinfo = new System.Globalization.CultureInfo("en-gb"); DateTime dt = DateTime.Parse("13/12/2009", cultureinfo); ```
You can use [DateTime.ParseExact](http://msdn.microsoft.com/en-us/library/system.datetime.parseexact.aspx) to specify an expected format.
c# and Date Culture Problems
[ "", "c#", ".net", "asp.net", "datetime", "cultureinfo", "" ]
I have a question regarding the development of liferay portlets using the liferay plugin SDK. My question goes mainly in the setup of the development IDE. The suggested one would be to use Netbeans IDE which I also tried out, but it appears to run very slowly on my machine while Eclipse is quite performant. The setup for Netbeans IDE is the following 1. Go to the directory \portlets 2. Run the create.bat (or sh file depending on the OS) to create a new sample portlet 3. Run Netbeans IDE, create a new "Java free form project" and point it to the directory of the created sample portlet That's it, pretty simple. For the mentioned reasons above (and because I'm a lot more familiar with Eclipse) I'd like to import the project into Eclipse the same way. Is there a way for doing it without having to change too much in the original structure of the created sample portlet and the according build.xml (ant file)?? I tried already to create a new project out of the build.xml ant file of the created sample portlet, however in this way it doesn't include me the source code. I didn't also find great tutorials on the web... Could someone help me with this, pointing out online tutorials or give me some hints. Thanks
I know your pain. Starting to work with Liferay needs much time. I you do not want to edit the existing source, but only crate your own portlets, you can download the plugins SDK from the 'Additional Files' section on the Liferay website. This provides ant scripts, to create a simple JSR compliant portlet, and to create all necessary things, to create a sound Eclipse project, for example: ``` ant -Dportlet.name=<project name> -Dportlet.display.name="<portlet title>" create ``` Than cd into the directory of your created portlet an do: ``` ant setup-eclipse ``` After that you should be able to create a new project from the sources in that directory in Eclipse, which can then be deployed via another ant script to the running tomcat instance. If you already know somthing about portlet programming, you shoud be pretty much settled now. If not, try to find documentation about JSR portlet programming first, before looking into Liferay specifig portlet development.
Liferay has now released an official set of Eclipse plugins that support portlet development. Here is the installation guide for installing the eclipse plugins: [Liferay IDE Installation Guide](http://www.liferay.com/community/wiki/-/wiki/Main/Liferay+IDE+Installation+Guide) Also there is a getting started guide that shows what to do after installation to actually setting up your first portlet project. [Getting Started Tutorial](http://www.liferay.com/community/wiki/-/wiki/Main/Liferay+IDE+Getting+Started+Tutorial) Liferay IDE uses the Plugins SDK from Liferay under the covers to do all the work. If you already have existing projects that you created with the Plugins SDK those can be imported into Liferay IDE as well. [Importing existing Projects](http://www.liferay.com/community/wiki/-/wiki/Main/Liferay+IDE+Importing+Existing+Projects)
Importing Liferay portlet into Eclipse IDE
[ "", "java", "eclipse", "liferay", "liferay-ide", "" ]
What is LINQ? I know it's for databases, but what does it do?
[LINQ](https://learn.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/) stands for *Language Integrated Query*. Instead of writing YAQL (Yet Another Query Language), Microsoft language developers provided a way to express queries directly in their languages (such as C# and Visual Basic). The techniques for forming these queries do not rely on the implementation details of the thing being queried, so that you can write valid queries against many targets (databases, in-memory objects, XML) with practically no consideration of the underlying way in which the query will be executed. Let's start this exploration with the parts belonging to the .NET Framework (3.5). * LINQ To Objects - examine [System.Linq.Enumerable](http://msdn.microsoft.com/en-us/library/system.linq.enumerable_members.aspx) for query methods. These target `IEnumerable<T>`, allowing any typed loopable collection to be queried in a type-safe manner. These queries rely on compiled .NET methods, not Expressions. * LINQ To Anything - examine [System.Linq.Queryable](http://msdn.microsoft.com/en-us/library/system.linq.queryable_members.aspx) for some query methods. These target `IQueryable<T>`, allowing the construction of Expression Trees that can be translated by the underlying implementation. * Expression Trees - examine [System.Linq.Expressions](http://msdn.microsoft.com/en-us/library/system.linq.expressions.aspx) namespace. This is code as data. In practice, you should be aware of this stuff, but don't really need to write code against these types. Language features (such as lambda expressions) can allow you to use various short-hands to avoid dealing with these types directly. * LINQ To SQL - examine the [System.Data.Linq](http://msdn.microsoft.com/en-us/library/system.data.linq.aspx) namespace. Especially note the `DataContext`. This is a DataAccess technology built by the C# team. It just works. * LINQ To Entities - examine the [System.Data.Objects](http://msdn.microsoft.com/en-us/library/system.data.objects.aspx) namespace. Especially note the `ObjectContext`. This is a DataAccess technology built by the ADO.NET team. It is complex, powerful, and harder to use than LINQ To SQL. * LINQ To XML - examine the [System.Xml.Linq](http://msdn.microsoft.com/en-us/library/system.xml.linq.aspx) namespace. Essentially, people weren't satisfied with the stuff in `System.Xml`. So Microsoft re-wrote it and took advantage of the re-write to introduce some methods that make it easier to use LINQ To Objects against XML. * Some nice helper types, such as [Func](http://msdn.microsoft.com/en-us/library/bb534960.aspx) and [Action](http://msdn.microsoft.com/en-us/library/system.action.aspx). These types are delegates with Generic Support. Gone are the days of declaring your own custom (and un-interchangable) delegate types. All of the above is part of the .NET Framework, and available from any .NET language (VB.NET, C#, IronPython, COBOL .NET etc). --- Ok, on to language features. I'm going to stick to C#, since that's what I know best. VB.NET also had several similar improvements (and a couple that C# didn't get - XML literals). This is a short and incomplete list. * Extension Methods - this allows you to "add" a method to type. The method is really a static method that is passed an instance of the type, and is restricted to the public contract of the type, but it very useful for adding methods to types you don't control (string), or adding (fully implemented) helper methods to interfaces. * Query Comprehension Syntax - this allows you to write in a SQL Like structure. All of this stuff gets translated to the methods on System.Linq.Queryable or System.Linq.Enumerable (depending on the Type of myCustomers). It is completely optional and you can use LINQ well without it. One advantage to this style of query declaration is that the range variables are scoped: they do not need to be re-declared for each clause. ``` IEnumerable<string> result = from c in myCustomers where c.Name.StartsWith("B") select c.Name; ``` * Lambda Expressions - This is a shorthand for specifying a method. The C# compiler will translate each into either an anonymous method or a true `System.Linq.Expressions.Expression`. You really need to understand these to use Linq well. There are three parts: a parameter list, an arrow, and a method body. ``` IEnumerable<string> result = myCustomers .Where(c => c.Name.StartsWith("B")) .Select(c => c.Name);` ``` * Anonymous Types - Sometimes the compiler has enough information to create a type for you. These types aren't truly anonymous: the compiler names them when it makes them. But those names are made at compile time, which is too late for a developer to use that name at design time. ``` myCustomers.Select(c => new { Name = c.Name; Age = c.Age; }) ``` * Implicit Types - Sometimes the compiler has enough information from an initialization that it can figure out the type for you. You can instruct the compiler to do so by using the var keyword. Implicit typing is required to declare variables for Anonymous Types, since programmers may not use the name of an *anonymous* type. ``` // The compiler will determine that names is an IEnumerable<string> var names = myCustomers.Select(c => c.Name); ```
LINQ (Language INtegrated Query) may refer to: * a library for collection and iterator manipulation that makes extensive use of higher-order functions as arguments (System.Linq) * a library for passing and manipulation of simple functions as abstract syntax trees (System.Linq.Expressions) * a syntax extension to various languages to provide a more SQL-like syntax for processing collections, a more compact notation for anonymous functions, and a mechanism to introduce static helper functions syntactically indistinguishable from final member functions * an interface definition to which data providers may conform in order to receive query structure and potentially perform optimization thereon, or occasionally the compatible data providers themselves The components may be used in isolation or combined.
What is LINQ and what does it do?
[ "", "c#", "linq", "" ]
I've seen numerous methods of POSTing data with PHP over the years, but I'm curious what the suggested method is, assuming there is one. Or perhaps there is a somewhat unspoken yet semi-universally-accepted method of doing so. This would include handling the response as well.
You could try the [Snoopy script](http://sourceforge.net/projects/snoopy/) It is useful on hosting providers that don't allow [fopen wrappers](https://www.php.net/manual/en/filesystem.configuration.php#ini.allow-url-fopen) I have used it for several years to grab RSS feeds.
While the Snoopy script maybe cool, if you're looking to *just post xml data with PHP*, why not use cURL? It's easy, has error handling, and is a useful tool already in your bag. Below is an example of how to post XML to a URL with cURL in PHP. ``` // url you're posting to $url = "http://mycoolapi.com/service/"; // your data (post string) $post_data = "first_var=1&second_var=2&third_var=3"; // create your curl handler $ch = curl_init($url); // set your options curl_setopt($ch, CURLOPT_MUTE, 1); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0); //ssl stuff curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded')); curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); // your return response $output = curl_exec($ch); // close the curl handler curl_close($ch); ```
POST XML to URL with PHP and Handle Response
[ "", "php", "xml", "api", "post", "" ]
This is a really, really stupid question but I am so accustomed to using linq / other methods for connecting and querying a database that I never stopped to learn how to do it from the ground up. Question: How do I establish a manual connection to a database and pass it a string param in C#? (yes, I know.. pure ignorance). Thanks
``` using (SqlConnection conn = new SqlConnection(databaseConnectionString)) { using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = "StoredProcedureName"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@ID", fileID); conn.Open(); using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection)) { if (rdr.Read()) { // process row from resultset; } } } } ```
One uses the [`SqlCommand`](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.aspx) class to execute commands (either stored procedures or sql) on SQL Server using ado.net. Tutorials abound.
Passing sql statements as strings to mssql with C#?
[ "", "c#", "ado.net", "" ]
Is there a better way to select empty datetime fields than this? ``` SELECT * FROM `table` WHERE `datetime_field` = '0000-00-00 00:00:00' ```
Better in what way? That query does everything you ask of it and, provided there's an index on `datetime_field`, it's as fast as it's going to get. If you're worried about the query looking "ugly", don't be. Its intent is quite clear. The only possible improvement you could consider is to use NULLs for these zero-date/time rows, in which case your query becomes: ``` SELECT * FROM `table` WHERE `datetime_field` IS NULL ``` That's what I'd do with a standards-compliant DBMS. My understanding is that MySQL **may** represent true NULL datetime fields in this horrific manner, in which case I guess the `IS NULL` may not work.
`SELECT * FROM db.table WHERE UNIX_TIMESTAMP(datetime_field) = 0` I like this code because it not only catches "zero dates" (e.g. '0000-00-00 00:00:00') is also catches "zeroes in dates" (e.g. '2010-01-00 00:00:00')
Selecting empty mysql datetime fields
[ "", "php", "mysql", "datetime", "" ]
When using iostream in C++ on Linux, it displays the program output in the terminal, but in Windows, it just saves the output to a stdout.txt file. How can I, in Windows, make the output appear in the console?
Since you mentioned stdout.txt I google'd it to see what exactly would create a stdout.txt; normally, even with a Windows app, console output goes to the allocated console, or nowhere if one is not allocated. So, assuming you are using SDL (which is the only thing that brought up stdout.txt), you should follow the advice [here](http://wiki.libsdl.org/FAQWindows#How_do_I_avoid_creating_stdout.txt_and_stderr.txt.3F). Either freopen stdout and stderr with "CON", or do the other linker/compile workarounds there. In case the link gets broken again, here is exactly what was referenced from libSDL: > How do I avoid creating stdout.txt and stderr.txt? > > "I believe inside the Visual C++ project that comes with SDL there is a SDL\_nostdio target > you can build which does what you want(TM)." > > "If you define "NO\_STDIO\_REDIRECT" and recompile SDL, I think it will fix the problem." > > (Answer courtesy of Bill Kendrick)
For debugging in Visual Studio you can print to the debug console: ``` OutputDebugStringW(L"My output string."); ```
How to output to the console in C++/Windows
[ "", "c++", "windows", "console", "sdl", "iostream", "" ]
I would like to force subclasses to implement the singleton pattern. I originally thought of having an abstract static property in the parent class, but upon closer though, that didn't make sense (abstract requires and instance). Next, I thought of having an interface with a static property, but that also doesn't make sense (interfaces also require an instance). Is this something which is possible, or should I give up this train of thought and implement an abstract factory?
Please reconsider. You do NOT want to use singletons here. You are making some functionality available to users who derive from your class. That's fine. But you're also dictating one specific way in which it must always be used, and for absolutely no reason. That is not good. It may make sense to only instantiate one object of this class the majority of the time, but in that case, *simply just instantiate the object once*. It's not like you're very likely to accidentally instantiate a dozen objects without noticing. Moreover, how can you tell that having two instances will *NEVER* be useful? I can think of several cases even now. Unit testing: You might want each test to instantiate this object, and tear it down again afterwards. And since most people have more than one unit test, you'll need to instantiate it more than once. Or you might at some point decide to have multiple identical/similar levels in your game, which means creating multiple instances. A singleton gives you two things: * A guarantee that no more than one instance of the object will ever be instantiated, and * Global access to that instance If you don't need both these things, there are better alternatives. You certainly don't need global access. (globals are bad, and usually a symptom of bad design, especially in mutable data such as your game state) But you don't need a guarantee that no more than one instances will ever be instantiated either. Is it the end of the world if I instantiate the object twice? Will the application crash? If so, you need that guarantee. But in your case, nothing bad will happen. The person instantiating the object simply uses more memory than necessary. But he might have a reason. Simply put in the class documentation that this is a very big and expensive class, and you shouldn't instantiate it more often than necessary. Problem solved. You don't remove flexibility that might turn out to be useful later on, you don't grant global access to data for no reason. Because you can control who can see the object, you don't need to drown it in locks that will become a bottleneck in multithreaded applications. You don't have hidden dependencies scattered throughout your code, making it harder to test and harder to reuse.
Try using an IOC container. Most good IOC containers enable the use of the singleton pattern without having to implement it yourself (ie: spring framework) - I like this better than forcing a static GetInstance() method. Besides, it's not really possible in java, it would work in C++ with templates though.
Force singleton pattern in subclasses
[ "", "c#", "design-patterns", "" ]
I'm trying to bind the following enum ``` public enum CertificateTypes : byte { None = 0, Original = 1, AuthenticatedCopy = 2, Numbered = 3 } ``` to a `tinyint` column on the database. However, when creating the SelectListItems and calling, for instance, `Person.CertificateTypes.Original.ToString() I get this:` ``` <option value="Original">Original</option> ``` which is not bindable to a byte? column. How should I do this? Should I explicitly set the value to "1" on the `Value` property of the SelectListItem? Or is there a way to make this work "automagically"?
If you want automagically you can use ``` var enumValues = Enum.GetValues(typeof(CertificateTypes)).Cast<CertificateTypes>().Select(e => (byte)e); var selectList = new SelectList(enumValues); ``` Problem here is you're only going to get the bytes, so you would probably need to select a new type something like... ``` var enumValues = Enum.GetValues(typeof(CertificateTypes)).Cast<CertificateTypes>() .Select(e => new KeyValuePair<byte, string>((byte)e, e.ToString())); var selectList = new SelectList(enumValues, "Key", "Value"); ``` That would just take possible values from the enum and translate it into an IEnumerable of CertificateTypes then taking each value and translating it into a new KeyValuePair. One thing to note, it's usually a good idea to only make your enums pluralized if you have a [Flags] attribute on them. Otherwise I would name it singular. Gotta love LINQ!
Not sure how the following translates to a `SelectListItems` in ASP.NET/MVC, though, as I have no experience, but maybe this can be of use. --- Of course you have to specifically cast the enum to it's underlying type like `(byte)Person.CertificateTypes.Original` to get it to talk to the database nicely. In WinForms, I use an `IList` of `KeyValuePair<byte,string>` to bind to a `ComboBox`, using something like the following: ``` foreach (Enum value in Enum.GetValues(typeof(CertificateTypes)) MyBindingIList.Add(new KeyValuePair<byte,string>((byte)value, value.ToString())); ``` I then bind the `ComboBox` and set it's `DisplayMember` to `"Value"` and `ValueMember` to `"Key"`. (You can switch the `Key` and `Value` in the `KeyValuePair` to whatever makes sense for you. For me, the key comes out of the database, so it makes sense to be the numeric type.)
Binding an Enum to LINQ and SelectListItem
[ "", "c#", "asp.net-mvc", "linq", "forms", "" ]
On Stack Overflow, I've seen a few people referring to the [MVC Futures library](http://aspnet.codeplex.com/releases/view/24471) What is this project? How do I use it? Where is the documentation?
Check [Eilon Lipton's Blog](http://weblogs.asp.net/leftslipper/archive/2009/03/03/asp-net-mvc-release-candidate-2-i-declare-myself-to-be-declarative.aspx) : > In this blog post I'll introduce you > to a feature that's not even part of > the main ASP.NET MVC download. It's > part of the separate MVC Futures > download, **which includes prototypes of > features that we're thinking of > including in a future version of > ASP.NET MVC**.
There is no documentation because it is very early prototype work. We do post the source code so if you're really interested, you can figure it out. Over time, we'll start to blog about it and provide samples. Right now, our focus is on the main product. We post the futures to provide a way for those who really want to dig into the source to provide feedback on what we're thinking about for the future.
What is the MVC Futures Library?
[ "", "c#", ".net", "asp.net-mvc", "asp.net-mvc-futures", "" ]
How to detect that a PC has been idle for 30 seconds using Java? EDITED With idle I mean that there are no user activity. The user does nothing in 30 seconds. I wold like to do an apllication like Windows, that detects that the user does nothing and enter in stad-by.
Directly from java it is not possible. You'll have to find some native library and create a JNI wrapper for that.
I've come across this excellent example of detecting system wide idle time using [JNA](https://github.com/twall/jna/). [Java Native Access (JNA)](https://github.com/twall/jna/) is a library that provides access to [Java Native Interface (JNI)](http://java.sun.com/j2se/1.5.0/docs/guide/jni/index.html) without the need for you to actually write native code. [Here's the example](http://ochafik.free.fr/blog/?p=98) that is very close to what you're asking for.
How to detect that a PC has been idle for 30 seconds using Java?
[ "", "java", "" ]
How much is read from `ThreadLocal` variable slower than from regular field? More concretely is simple object creation faster or slower than access to `ThreadLocal` variable? I assume that it is fast enough so that having `ThreadLocal<MessageDigest>` instance is much faster then creating instance of `MessageDigest` every time. But does that also apply for byte[10] or byte[1000] for example? Edit: Question is what is really going on when calling `ThreadLocal`'s get? If that is just a field, like any other, then answer would be "it's always fastest", right?
Running unpublished benchmarks, `ThreadLocal.get` takes around 35 cycle per iteration on my machine. Not a great deal. In Sun's implementation a custom linear probing hash map in `Thread` maps `ThreadLocal`s to values. Because it is only ever accessed by a single thread, it can be very fast. Allocation of small objects take a similar number of cycles, although because of cache exhaustion you may get somewhat lower figures in a tight loop. Construction of `MessageDigest` is likely to be relatively expensive. It has a fair amount of state and construction goes through the `Provider` SPI mechanism. You may be able to optimise by, for instance, cloning or providing the `Provider`. Just because it may be faster to cache in a `ThreadLocal` rather than create does not necessarily mean that the system performance will increase. You will have additional overheads related to GC which slows everything down. Unless your application very heavily uses `MessageDigest` you might want to consider using a conventional thread-safe cache instead.
In 2009, some JVMs implemented `ThreadLocal` using an unsynchronised `HashMap` in the `Thread.currentThread()` object. This made it extremely fast (though not nearly as fast as using a regular field access, of course), as well as ensuring that the `ThreadLocal` object got tidied up when the `Thread` died. Updating this answer in 2016, it seems most (all?) newer JVMs use a `ThreadLocalMap` with linear probing. I am uncertain about the performance of those – but I cannot imagine it is significantly worse than the earlier implementation. Of course, `new Object()` is also very fast these days, and the garbage collectors are also very good at reclaiming short-lived objects. Unless you are certain that object creation is going to be expensive, or you need to persist some state on a thread by thread basis, you are better off going for the simpler allocate when needed solution, and only switching over to a `ThreadLocal` implementation when a profiler tells you that you need to.
Performance of ThreadLocal variable
[ "", "java", "multithreading", "performance", "thread-local", "" ]
I am surprised that I can't initialize my fields in structs, why is it like that? Like: ``` struct MyStruct { private int a = 90; } ``` but it's a complie time error. I don't know why it's a problem? Please explain this to me.
The reason is mainly performance. Consider the following, ``` var a = new MyStruct[1000]; ``` If C# allowed initialization of fields in a struct then the initialization would have to be performed 1000 times, once for each element in the array. C# wanted to avoid such kinds of implicit behavior as might be found in other languages.
In C#, a `struct` cannot declare a default constructor. The compiler moves the initialization statements to the constructor, which can't happen with a `struct` in C#.
Why can't I initialize my fields in my structs?
[ "", "c#", "" ]
I have a text field which is bound with Integer variable, so when user enters number into this field, binding mechanism automatically converts text into Integer and sets this value into var. Problem is, since user types text into text field, that binding mechanism is converting only values, and if user types some letters into it, binding would not activate because there is no legal value inside text field. What I would need in such situation, binding has to trigger change with null value, so I have null in my Integer var. So, if user would left this field empty or something that is not number, binding will have to trigger null value propagation; not to ignore event... How could I do this without propgramming events on text field? Is java binding capable for changing its default behaviour?
Besides altering the behaviour of the binding mechanism, you could put a Formatter into the TextField that only accepts numbers. You need to extend javax.swing.text.DefaultFormatter for this. And you would then use a JFormattedTextField instead of a normal JTextField. The result would be that you only get valid input in your textfield and you don't have to make anything out of incorrect values.
What you need is [JFormattedTextField](http://java.sun.com/j2se/1.4.2/docs/api/javax/swing/JFormattedTextField.html) and [NumberFormat](http://java.sun.com/j2se/1.4.2/docs/api/java/text/NumberFormat.html).
Java binding JTextField -> java.lang.Integer problem
[ "", "java", "binding", "" ]
I have two tables: **TableA** (`ID [int, pk], Name [string])` and **TableB** `(ID [int, pk], TableA_ID [int, fk], Name [string], DateStamp [datetime (dd/mm/yyyy hh:MM:ss)])`. There is a one-to-many relationship between TableA and TableB. An inner join on the two tables will give me the following results: ``` TableA.ID, TableA.Name, TableB.Name, TableB.DateStamp 1, 'File A', 'Version 1', 01/01/2009 15:00:00 1, 'File A', 'Version 2', 05/01/2009 08:15:00 1, 'File A', 'Version 3', 06/01/2009 19:33:00 2, 'File B', 'Version 1', 03/01/2009 09:10:00 2, 'File B', 'Version 2', 20/01/2009 20:00:00 3, 'File C', 'Version 1', 01/01/2009 17:00:00 ``` What I actually want is the following (each row from TableA and the last matching row from TableB): ``` TableA.ID, TableA.Name, TableB.Name, TableB.DateStamp 1, 'File A', 'Version 3', 06/01/2009 19:33:00 2, 'File B', 'Version 2', 20/01/2009 20:00:00 3, 'File C', 'Version 1', 01/01/2009 17:00:00 ``` This is the query that I'm using to achieve this: ``` SELECT ta.ID, ta.Name, tb.Name, tb.DateStamp FROM TableA ta INNER JOIN TableB tb ON ta.ID = tb.TableA_ID WHERE tb.ID IN ( SELECT TOP 1 tb2.ID FROM TableB tb2 WHERE tb2.TableA_ID = ta.ID ORDER BY tb2.DateStamp DESC) ``` That works but my gut feeling is that I'm not doing this in the "best way". It looks like it is a candidate for an aggregation query (i.e. groupby) but I didn't have any luck with that. In the end I always had to use a subquery to get the row I'm after in TableB. Any help much appreciated.
No, there is no requirement to do GROUP BY here, this should be solved through a correlated sub-query: ``` SELECT TableA.ID, TableA.Name, TableB.Name, TableB.DateStamp FROM TableA INNER JOIN TableB ON TableA.ID = TableB.TableA_ID AND TableB.DateStamp = ( SELECT MAX(DateStamp) FROM TableB WHERE TableA_ID = TableA.ID ) ``` An additional GROUP BY is only necessary if you have more than one record in `TableB` with equal `TableA_ID` *and* equal `DateStamp`. --- For the specific example you've shown, a GROUP BY query *happens to produce* the correct result. It's still wrong, because the correct result is more a side-effect in this situation. ``` SELECT TableA.ID, TableA.Name, MAX(TableB.Name) Max_TableBName, MAX(TableB.DateStamp) Max_TableBDateStamp FROM TableA INNER JOIN TableB ON TableA.ID = TableB.TableA_ID GROUP BY TableA.ID, TableA.Name ``` This relies on the coincidence that `MAX(TableB.Name)` is in fact the value you want to get out, and it is aligned with `MAX(TableB.DateStamp)`. But since this correlation is a mere accident, the GROUP BY query is wrong.
You can also try RANK() OVER function: ``` -- Test data DECLARE @TableA TABLE (ID INT, Name VARCHAR(20)) INSERT INTO @TableA SELECT 1, 'File A' UNION SELECT 2, 'File B' UNION SELECT 3, 'File C' DECLARE @TableB TABLE (ID INT, TableAID INT, Name VARCHAR(20), DateStamp DATETIME) INSERT INTO @TableB SELECT 1, 1, 'Version 1', '01/01/2009 15:00:00' UNION SELECT 2, 1, 'Version 2', '01/05/2009 08:15:00' UNION SELECT 3, 1, 'Version 3', '01/06/2009 19:33:00' UNION SELECT 4, 2, 'Version 1', '01/03/2009 09:10:00' UNION SELECT 5, 2, 'Version 2', '01/20/2009 20:00:00' UNION SELECT 6, 3, 'Version 1', '01/01/2009 17:00:00' -- Actually answer SELECT M.ID, M.AName, M.BName, M.DateStamp FROM ( SELECT RANK() OVER(PARTITION BY A.ID ORDER BY B.DateStamp DESC) AS N, A.ID, A.Name AS AName, B.Name AS BName, B.DateStamp FROM @TableA A INNER JOIN @TableB B ON A.ID = B.TableAID ) M WHERE M.N = 1 ``` See [2. Last Date selection with grouping - using RANK() OVER](https://stackoverflow.com/questions/488020/what-is-your-most-useful-sql-trick-to-avoid-writing-more-code/557238#557238)
is this a candidate for a sql groupby query?
[ "", "sql", "" ]
When I set a value of a text node with ``` node.nodeValue="string with &#xxxx; sort of characters" ``` ampersand gets escaped. Is there an easy way to do this?
You need to use Javascript escapes for the Unicode characters: ``` node.nodeValue="string with \uxxxx sort of characters" ```
From [<http://code.google.com/p/jslibs/wiki/JavascriptTips>](http://code.google.com/p/jslibs/wiki/JavascriptTips): (converts both entity references and numeric entities) ``` const entityToCode = { __proto__: null, apos:0x0027,quot:0x0022,amp:0x0026,lt:0x003C,gt:0x003E,nbsp:0x00A0,iexcl:0x00A1,cent:0x00A2,pound:0x00A3, curren:0x00A4,yen:0x00A5,brvbar:0x00A6,sect:0x00A7,uml:0x00A8,copy:0x00A9,ordf:0x00AA,laquo:0x00AB, not:0x00AC,shy:0x00AD,reg:0x00AE,macr:0x00AF,deg:0x00B0,plusmn:0x00B1,sup2:0x00B2,sup3:0x00B3, acute:0x00B4,micro:0x00B5,para:0x00B6,middot:0x00B7,cedil:0x00B8,sup1:0x00B9,ordm:0x00BA,raquo:0x00BB, frac14:0x00BC,frac12:0x00BD,frac34:0x00BE,iquest:0x00BF,Agrave:0x00C0,Aacute:0x00C1,Acirc:0x00C2,Atilde:0x00C3, Auml:0x00C4,Aring:0x00C5,AElig:0x00C6,Ccedil:0x00C7,Egrave:0x00C8,Eacute:0x00C9,Ecirc:0x00CA,Euml:0x00CB, Igrave:0x00CC,Iacute:0x00CD,Icirc:0x00CE,Iuml:0x00CF,ETH:0x00D0,Ntilde:0x00D1,Ograve:0x00D2,Oacute:0x00D3, Ocirc:0x00D4,Otilde:0x00D5,Ouml:0x00D6,times:0x00D7,Oslash:0x00D8,Ugrave:0x00D9,Uacute:0x00DA,Ucirc:0x00DB, Uuml:0x00DC,Yacute:0x00DD,THORN:0x00DE,szlig:0x00DF,agrave:0x00E0,aacute:0x00E1,acirc:0x00E2,atilde:0x00E3, auml:0x00E4,aring:0x00E5,aelig:0x00E6,ccedil:0x00E7,egrave:0x00E8,eacute:0x00E9,ecirc:0x00EA,euml:0x00EB, igrave:0x00EC,iacute:0x00ED,icirc:0x00EE,iuml:0x00EF,eth:0x00F0,ntilde:0x00F1,ograve:0x00F2,oacute:0x00F3, ocirc:0x00F4,otilde:0x00F5,ouml:0x00F6,divide:0x00F7,oslash:0x00F8,ugrave:0x00F9,uacute:0x00FA,ucirc:0x00FB, uuml:0x00FC,yacute:0x00FD,thorn:0x00FE,yuml:0x00FF,OElig:0x0152,oelig:0x0153,Scaron:0x0160,scaron:0x0161, Yuml:0x0178,fnof:0x0192,circ:0x02C6,tilde:0x02DC,Alpha:0x0391,Beta:0x0392,Gamma:0x0393,Delta:0x0394, Epsilon:0x0395,Zeta:0x0396,Eta:0x0397,Theta:0x0398,Iota:0x0399,Kappa:0x039A,Lambda:0x039B,Mu:0x039C, Nu:0x039D,Xi:0x039E,Omicron:0x039F,Pi:0x03A0,Rho:0x03A1,Sigma:0x03A3,Tau:0x03A4,Upsilon:0x03A5, Phi:0x03A6,Chi:0x03A7,Psi:0x03A8,Omega:0x03A9,alpha:0x03B1,beta:0x03B2,gamma:0x03B3,delta:0x03B4, epsilon:0x03B5,zeta:0x03B6,eta:0x03B7,theta:0x03B8,iota:0x03B9,kappa:0x03BA,lambda:0x03BB,mu:0x03BC, nu:0x03BD,xi:0x03BE,omicron:0x03BF,pi:0x03C0,rho:0x03C1,sigmaf:0x03C2,sigma:0x03C3,tau:0x03C4, upsilon:0x03C5,phi:0x03C6,chi:0x03C7,psi:0x03C8,omega:0x03C9,thetasym:0x03D1,upsih:0x03D2,piv:0x03D6, ensp:0x2002,emsp:0x2003,thinsp:0x2009,zwnj:0x200C,zwj:0x200D,lrm:0x200E,rlm:0x200F,ndash:0x2013, mdash:0x2014,lsquo:0x2018,rsquo:0x2019,sbquo:0x201A,ldquo:0x201C,rdquo:0x201D,bdquo:0x201E,dagger:0x2020, Dagger:0x2021,bull:0x2022,hellip:0x2026,permil:0x2030,prime:0x2032,Prime:0x2033,lsaquo:0x2039,rsaquo:0x203A, oline:0x203E,frasl:0x2044,euro:0x20AC,image:0x2111,weierp:0x2118,real:0x211C,trade:0x2122,alefsym:0x2135, larr:0x2190,uarr:0x2191,rarr:0x2192,darr:0x2193,harr:0x2194,crarr:0x21B5,lArr:0x21D0,uArr:0x21D1, rArr:0x21D2,dArr:0x21D3,hArr:0x21D4,forall:0x2200,part:0x2202,exist:0x2203,empty:0x2205,nabla:0x2207, isin:0x2208,notin:0x2209,ni:0x220B,prod:0x220F,sum:0x2211,minus:0x2212,lowast:0x2217,radic:0x221A, prop:0x221D,infin:0x221E,ang:0x2220,and:0x2227,or:0x2228,cap:0x2229,cup:0x222A,int:0x222B, there4:0x2234,sim:0x223C,cong:0x2245,asymp:0x2248,ne:0x2260,equiv:0x2261,le:0x2264,ge:0x2265, sub:0x2282,sup:0x2283,nsub:0x2284,sube:0x2286,supe:0x2287,oplus:0x2295,otimes:0x2297,perp:0x22A5, sdot:0x22C5,lceil:0x2308,rceil:0x2309,lfloor:0x230A,rfloor:0x230B,lang:0x2329,rang:0x232A,loz:0x25CA, spades:0x2660,clubs:0x2663,hearts:0x2665,diams:0x2666 }; var charToEntity = {}; for ( var entityName in entityToCode ) charToEntity[String.fromCharCode(entityToCode[entityName])] = entityName; function EscapeEntities(str) str.replace(/[^\x20-\x7E]/g, function(str) charToEntity[str] ? '&'+charToEntity[str]+';' : str ); ``` ``` function unescapeEntities(str) { return str.replace( /&(.+?);/g, function(str, ent) { return String.fromCharCode( ent[0]!='#' ? entityToCode[ent] : ent[1]=='x' ? parseInt(ent.substr(2),16): parseInt(ent.substr(1)) ); }); } ```
Setting nodeValue of text node in Javascript when string contains html entities
[ "", "javascript", "dom", "html-entities", "nodevalue", "" ]
Ex : I want something like abc.hyd.mycompany.com. My requirement is to parse this name and initialize appropriate service. ``` using System.Net; Dns.GetHostName() // doesn't return fully qualified name it just gives "abc" ```
You may be able to get the whole DNS string like this: ``` System.Net.Dns.GetHostEntry("").HostName ``` We don't have full fledged DNS names where I work, but it does give me a three level faux domain name instead of just the hostname. Edit 2011/03/17: Incorporated changes suggested by mark below.
I used this very similar method: ``` var serverName = System.Environment.MachineName; //host name sans domain var fqhn = System.Net.Dns.GetHostEntry(serverName).HostName; //fully qualified hostname ```
How do I find the fully qualified hostname of my machine in C#?
[ "", "c#", "environment-variables", "" ]
Some hosters let your script CREATE DATABASE, some do not, and require you to use their control panels instead. How do I check whether database would let me run this query with given user/password without actually creating any databases? Because if I don’t have enough rights, I just want to hide the “Create database” button from UI altogether. I’m using PHP and MySQL. Thanks.
You can obtain rights with: ``` SHOW GRANTS FOR CURRENT_USER; ```
As Vartec said, `SHOW GRANTS FOR CURRENT_USER` is the way to go. I'm just adding this answer to show the output of that statement when you don't have full rights: ``` GRANT USAGE ON *.* TO 'myusername'@'%' IDENTIFIED BY PASSWORD '*8D4A4D198E31D6EA9D7997F7B29A2BCA254178B6' GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, REFERENCES, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES, CREATE ROUTINE ON `mydb1`.* TO 'myusername'@'%' GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, REFERENCES, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES, CREATE ROUTINE ON `mydb2`.* TO 'myusername'@'%' GRANT SELECT, INSERT, UPDATE, DELETE, CREATE, DROP, REFERENCES, INDEX, ALTER, CREATE TEMPORARY TABLES, LOCK TABLES, CREATE ROUTINE ON `mydb3`.* TO 'myusername'@'%' ```
Check user rights before attempting to CREATE DATABASE
[ "", "php", "mysql", "" ]