Prompt
stringlengths
10
31k
Chosen
stringlengths
3
29.4k
Rejected
stringlengths
3
51.1k
Title
stringlengths
9
150
Tags
listlengths
3
7
I'm aware that there is a [realloc](http://www.cplusplus.com/reference/clibrary/cstdlib/realloc/) function that would allow me to resize the memory block (and it's paired with a free function). However, I'm trying to do the same to a c++ class with some member pointers allocated memory using **new** instead of **realloc**. Is there an equivalent keyword to **realloc** in c++ that would allow me to achieve the same goal when the memory is paired using new/delete rather than malloc or realloc and free? Thanks in advance.
No, there isn't. And frankly, if you are using new or new[]. your C++ code is probably not well designed. Look at using **std::vector** instead of new[], and at using values instead of new.
I am not aware of if there is one or not, but you could probably use a vector as you are just resizing an array of elements :) ``` std::vector<char> iVector(1000); // 1000 element as initial size iVector.resize(2500); // resize the vector to 2500 elements // or just use it without worrying about memory management ```
realloc function that would work for memory allocated using new instead of realloc
[ "", "c++", "memory-management", "" ]
I have a form that starts a thread. Now I want the form to auto-close when this thread terminates. The only solution I found so far is adding a timer to the form and check if thread is alive on every tick. But I want to know if there is a better way to do that? Currently my code looks more less like this ``` partial class SyncForm : Form { Thread tr; public SyncForm() { InitializeComponent(); } void SyncForm_Load(object sender, EventArgs e) { thread = new Thread(new ThreadStart(Synchronize)); thread.IsBackground = true; thread.Start(); threadTimer.Start(); } void threadTimer_Tick(object sender, EventArgs e) { if (!thread.IsAlive) { Close(); } } void Synchronize() { // code here } } ```
The BackgroundWorker class exists for this sort of thread management to save you having to roll your own; it offers a RunWorkerCompleted event which you can just listen for.
Edit to make it call a helper method so it's cleaner. ``` thread = new Thread(() => { Synchronize(); OnWorkComplete(); }); ... private void OnWorkComplete() { Close(); } ```
Calling a method when thread terminates
[ "", "c#", "multithreading", "asynchronous", "methods", "" ]
I have a div in an html file defined as follows: ``` <div id="rangeTabAll"></div> ``` In an externally defined style sheet I define the following style. ``` #rangeTabAll{ top:45px; left:124px; width:186px; height:114px; display:none; background:#ffffff url(../images/rangetab0.jpg) no-repeat; } ``` How do i read/write the background value using jQuery? The ``` $('#rangeTabAll').css('background') ``` method wont work because its not an inline style. And ``` $('#rangeTabAll').attr('class') ``` is undefined. I can do this with javascript quite simply but i wonder how its done via jQuery.
`background` is a "magic" CSS property that is expanded to all the different `background-*` properties, such as `background-image`, `background-color`, `background-repeat`... To get them in jQuery you would call `$('#rangeTabAll').css('backgroundColor')` and so on. Note the camelCase instead of separating the words with dashes. I just noticed that jQuery converts `background-color` to `backgroundColor` etc. for you, so you won't have to worry about that. You can do `$('#rangeTabAll').css('background-color')` as well.
remember: > Shorthand CSS properties (e.g. **margin**, > **background**, **border**) are not supported. > For example, if you want to retrieve > the rendered margin, use: > $(elem).css('**marginTop**') and > $(elem).css('**marginRight**'), and so on. from [jQuery Documentation: CSS](http://docs.jquery.com/CSS/css#name) in your example, the shorthand **background** is not supported, you need to write the full property. for ``` #rangeTabAll { top:45px; left:124px; width:186px; height:114px; display:none; background:#ffffff url(../images/rangetab0.jpg) no-repeat; } ``` you would write: ``` $("#rangeTabAll").css("backgroundColor", "myNewValue"); $("#rangeTabAll").css("backgroundImage", "myNewValue"); $("#rangeTabAll").css("backgroundRepeat", "myNewValue"); ``` or ``` $("#rangeTabAll").css("background-color", "myNewValue"); $("#rangeTabAll").css("background-image", "myNewValue"); $("#rangeTabAll").css("background-repeat", "myNewValue"); ```
How to use jQuery to read/write the values of an elements externally defined css class?
[ "", "javascript", "jquery", "css", "class", "" ]
how to write a regular expression to check whether a number is consisting only of 5 digits?
This regular expression should work nicely: ``` /^\d{5}$/ ``` This will check if a string consists of only 5 numbers. * `/` is the delimiter. It is at the beginning and the end of a regular expression. (User-defined, you can use any character as delimiter). * `^` is a start of string anchor. * `\d` is a shorthand for `[0-9]`, which is a character class matching only digits. * `{5}` means repeat the last group or character `5` times. * `$` is the end of string anchor. * `/` is the closing delimiter. --- If you want to make sure that the number doesn't start with 0, you can use the following variant: ``` /^[1-9]\d{4}$/ ``` Where: * `/` is the delimiter. It is at the beginning and the end of a regular expression. (User-defined, you can use any character as delimiter). * `^` is a start of string anchor. * `[1-9]` is a character class matching digits ranging from `1` to `9`. * `\d` is a shorthand for `[0-9]`, which is a character class matching only digits. * `{4}` means repeat the last group or character `4` times. * `$` is the end of string anchor. * `/` is the closing delimiter. --- *Note that using regular expressions for this kind of validation is far from being ideal.*
This regex will make sure the number does not start with zeros: ``` if(preg_match('/^[1-9]\d{4}$/', $number)) echo "Number is 5 digits\n"; else echo "Number is not five digits\n"; ``` But why not use [`is_numeric()`](http://php.net/is_numeric) instead? ``` if(is_numeric($number) && $number >= 10000 && $number <= 99999) echo "Number is 5 digits\n"; else echo "Number is not five digits\n"; ``` Or you can even just cast it to an integer to make sure it only has an integer value: ``` if(strval(intval($number)) === "$number" && $number >= 10000 && $number <= 99999) echo "Number is 5 digits\n"; else echo "Number is not five digits\n"; ```
php regular expression to check whether a number consists of 5 digits
[ "", "php", "regex", "" ]
Which is the best way to debug an PHP application as we can debug ASP.NET application with Visual Studio ?
I'm using the IDE [Eclipse PDT](http://eclipse.org/pdt), which can use the PHP extension [Xdebug](http://xdebug.org/) to provide debugging functionnalities, kind of the same way as Visual Studio (a bit less powerful, maybe), which gives you the ability to do things like : * step by step * step in / out of functions / methods * see the content of variables * have a stack trace showing where you are That's really nice to debug big programs -- especially ones you didn't write, to understand how they work *(or don't ^^ )* It can also use the extension "zend debugger" ; but I've never tried this one. Even without using a debugger like the one provided by PDT, Xdebug is a nice extension to have on a development server : it gives nice stack traces when there's an error/exception, it allows you to get nice-looking `var_dump`'s output, ... It can also be used to get profiling data, which you can visualize with tools like [KCacheGrind](http://kcachegrind.sourceforge.net/html/Home.html), [WinCacheGrind](http://sourceforge.net/projects/wincachegrind/), or [Webgrind](http://code.google.com/p/webgrind/). *But note it is hurting performance badly, so it definitly should not be installed on a production server !*
[PHP Console](http://chrome.google.com/extensions/detail/nfhmhhlpfleoednkpnnnkolmclajemef) is good if you want to debug WEB 2.0 (AJAX) web-projects.
How to debug a PHP application?
[ "", "php", "visual-studio", "debugging", "web-applications", "" ]
I have a class with number of methods and want to have one exception handler for them all. There are so many of these methods and they have different parameters, that it would be ugly to write try/catch for each of them. Do you maybe know a way where I can do it with having a one in class exception handler, which will handle them all. **UPDATE:** --- Many of you ask me why. The reason is that I am calling a data source with various methods. so my class has functions getData1, gedData2, getData3,getData4, ...., getDataN. The problem is that there is no way to check if the connection is still open and creating new connection is very very expensive. So I am trying to reuse connection and if the connection on the next call has failed, i would catch this and reconnect and try again. That is why i need this try/catch all block. to do this for all the functions: ``` try{ datasource.getData() } catch(ConnectionException) { datasource.Connect(); datasource.getData() } ``` --- Thanks
You could use a delegate to pass your method's code into a single try catch like the following example: ``` private void GlobalTryCatch(Action action) { try { action.Invoke(); } catch (ExpectedException1 e) { throw MyCustomException("Something bad happened", e); } catch (ExpectedException2 e) { throw MyCustomException("Something really bad happened", e); } } public void DoSomething() { GlobalTryCatch(() => { // Method code goes here }); } ```
I can't figure out any reason why you may benefit from handling all the exceptions in a class using a single method (can you elaborate? I'm curious...) Anyway, you can use [AOP](http://en.wikipedia.org/wiki/Aspect-oriented_programming) (Aspect Oriented Programming) techniques to inject (statically or at runtime) exception handling code around the methods of your class. There's a good assembly post-processing library called [PostSharp](http://www.postsharp.org/) that you can configure using attributes on the methods in your class: You may define an aspect like this (from PostSharp website): ``` public class ExceptionDialogAttribute : OnExceptionAspect { public override void OnException(MethodExecutionEventArgs eventArgs) { string message = eventArgs.Exception.Message; MessageBox.Show(message, "Exception"); eventArgs.FlowBehavior = FlowBehavior.Continue; } } ``` And then you'll apply the attribute to the methods you want to watch for exceptions, like this: ``` public class YourClass { // ... [ExceptionDialog] public string DoSomething(int param) { // ... } } ``` You can also apply the attribute to the whole class, like this: ``` [ExceptionDialog] public class YourClass { // ... public string DoSomething(int param) { // ... } public string DoSomethingElse(int param) { // ... } } ``` This will apply the advice (the exception handling code) to every method in the class.
One Exception handler for all exceptions of a CLASS
[ "", "c#", "exception", "" ]
I'm iterating over a list of tuples in Python, and am attempting to remove them if they meet certain criteria. ``` for tup in somelist: if determine(tup): code_to_remove_tup ``` What should I use in place of `code_to_remove_tup`? I can't figure out how to remove the item in this fashion.
You can use a [list comprehension](https://en.wikipedia.org/wiki/List_comprehension#Python) to create a new list containing only the elements you don't want to remove: ``` somelist = [x for x in somelist if not determine(x)] ``` Or, by assigning to the slice `somelist[:]`, you can mutate the existing list to contain only the items you want: ``` somelist[:] = [x for x in somelist if not determine(x)] ``` This approach could be useful if there are other references to `somelist` that need to reflect the changes. Instead of a comprehension, you could also use `itertools`. In Python 2: ``` from itertools import ifilterfalse somelist[:] = ifilterfalse(determine, somelist) ``` Or in Python 3: ``` from itertools import filterfalse somelist[:] = filterfalse(determine, somelist) ```
The answers suggesting [list comprehensions](https://en.wikipedia.org/wiki/List_comprehension#Python) are *almost* correct—except that they build a completely new list and then give it the same name the old list as, they do *not* modify the old list in place. That's different from what you'd be doing by selective removal, as in [Lennart's suggestion](https://stackoverflow.com/a/1207427/3064538)—it's faster, but if your list is accessed via multiple references the fact that you're just reseating one of the references and *not* altering the list object itself can lead to subtle, disastrous bugs. Fortunately, it's extremely easy to get both the speed of list comprehensions AND the required semantics of in-place alteration—just code: ``` somelist[:] = [tup for tup in somelist if determine(tup)] ``` Note the subtle difference with other answers: this one is *not* assigning to a barename. It's assigning to a list slice that just happens to be the entire list, thereby replacing the list *contents* **within the same Python list object**, rather than just reseating one reference (from the previous list object to the new list object) like the other answers.
How to remove items from a list while iterating?
[ "", "python", "iteration", "" ]
I will only have a relative link available to me but I want to use jQuery to navigate to this rel link. I only see AJAX functionality in jQuery. How can I do this using jQuery or just pure HTML/JavaScript?
Other answers rightly point out that there is no need to use jQuery in order to navigate to another URL; that's why there's no jQuery function which does so! If you're asking how to click a link via jQuery then assuming you have markup which looks like: ``` <a id="my-link" href="/relative/path.html">Click Me!</a> ``` You could [`click()`](http://docs.jquery.com/Events/click) it by executing: ``` $('#my-link').click(); ```
``` window.location.href = "/somewhere/else"; ```
Use jQuery to navigate away from page
[ "", "javascript", "jquery", "" ]
I have an on line project "question of the week"; this project allows the users to submit their questions. These questions are saved in a mysql table; the question is also sent over to another simplepost.php which stores the question in a phpBB. I want to use this phpBB for every question, for discussions on that question. So now, my project stores the question in sql table as well as posts the question in the phpBB. But when the question is posted in phpBB it stores in it "<http://servername.com/phpBB3/viewtopic.php?f=5&t=24>" where t=24 is the question. I somehow want to grab this url and extract the t=24, so that I can have a click able link for each question in my project that directs the question of its particular phpBB page. Suppose my project is on: <http://servername.com/qotw/profile.html> (this allows the user to post a question and the question is inserted in sql table and also calls in phpBB/simplepost.php is posts the question in phpBB) and this question in php can be seen on : "<http://servername.com/phpBB3/viewtopic.php?f=5&t=24>" Please suggest to me what should I do. how can I grab this "t=24" from this url. When my simplepost.php is called, is posts the question using posting.php and a return value is sent back. The code in simplepost.php looks like: ``` $title = "This is the title of the message."; //$body = "This is the message body."; $post_fields = array( 'subject' => $title, 'addbbcode20' => 100, 'message' => $body, 'lastclick' => $lclick[0], 'post' => 'Submit', 'attach_sig' => 'on', 'creation_time' => $lclick[0], 'form_token' => $security123[1], 'filecomment' => '', ); //Wait (you might also do this by setting lastclick in the past by 3 seconds sleep(3); //Set up curl session for posting the message $ch1 = curl_init(); curl_setopt($ch1, CURLOPT_URL,$purl); curl_setopt($ch1, CURLOPT_POST, true); curl_setopt($ch1, CURLOPT_POSTFIELDS, $post_fields); curl_setopt($ch1, CURLOPT_RETURNTRANSFER,true); curl_setopt($ch1, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch1, CURLOPT_HEADER, false ); curl_setopt($ch1, CURLOPT_COOKIE,'cookie.txt'); curl_setopt($ch1, CURLOPT_COOKIEJAR,'cookie.txt'); curl_setopt($ch1, CURLOPT_COOKIEFILE,'cookie.txt'); $result2= curl_exec ($ch1); //$result3= curl_exec ($ch1, CURLOPT_URL,$purl); curl_close ($ch1); echo $result2; ``` The respond come in $result2. and the pages goes over to <http://servername.com/phpBB3/viewtopic.php?f=5&t=24>". But the thing is all this is happening in the back end. My project does not shows the viewtopic.php page of the phpBB.
If I'm not mistaken you should be able to use PHP to get the 'value' (24) stored in the 't' variable in the URL using `$_GET['t']`. This will only work if you are currently at that URL though. See: <https://www.php.net/manual/en/reserved.variables.get.php> if you are trying to grab just that section when you are not on that specific page you could try: ``` ereg("t=[0-9]+", $url, $res) ``` then just strip off the "t=" from the result in the $res array
To extract components from the URL, you can use [`parse_url`](http://php.net/manual/en/function.parse-url.php) -- well, if you only want to get the query string, `$_SERVER['QUERY_STRING']` will do just fine too. Then, to get the params/values from the query string, you can have a look at [`parse_str`](http://php.net/manual/en/function.parse-str.php) : there is an example that shows just what you want : ``` <?php $str = "first=value&arr[]=foo+bar&arr[]=baz"; parse_str($str); echo $first; // value echo $arr[0]; // foo bar echo $arr[1]; // baz parse_str($str, $output); echo $output['first']; // value echo $output['arr'][0]; // foo bar echo $output['arr'][1]; // baz ?> ``` Obvisouly, you will probably prefer the second way, to avoid injection of *(unknown and potentially dangerous, like `register_globals`)* variables in your script.
Grabbing the information from a url?
[ "", "php", "phpbb", "" ]
I'm building a web page screen capture application for an internal R&D project. Environment: Ubuntu 9.04 (default desktop install), Apache, PHP. So far I've got a bash script that takes one parameter (URL), fires up firefox, grabs the screen and saves it as a PNG. I've tried running this from terminal and it works fine. Here's the Bash script: ``` #!/bin/bash firefox $1 # Start firefox and go to the passed in URL scrot -d 5 test.png # Take screen grab with 5 second delay ``` Next I created a simple PHP page that uses shell\_exec to run the script: ``` <? // Sample URL $url = 'http://www.google.com'; // Run the script shell_exec('sh script.sh ' . $url); // Out put HTML to display image echo '<img src="test.png" />'; ?> ``` However, when the PHP page is called the screen is not captured. A quick look in the apache error logs show the following message: > ``` > Error: no display specified > giblib error: Can't open X display. It *is* running, yeah > ``` I'm guessing this is because apache is running as a different user and hasn't got access to my X display. So, can anyone shed any light on what I'm doing wrong or how I can capture the current user display. Thanks.
Launching firefox from PHP running under Apache seems to me like a bad idea (it definitly feels wrong). The way I would do that : * a PHP webpage (which runs under Apache) that receives the URL ; something like a form, for instance + that page inserts the URL in a database-like system, that will be used as a queue + this URL is marked as "to process" * a PHP (or another language) script, totally independant from Apache ; for instance, launched by the crontab + this scripts selects an URL from the queue in the database (least recent one, for instance), and marks it as "processing" + it then lauches your shell-script, which launches firefox and does the screenshot + one the screenshot is done, the URL in the queue is marked as "done", and the screenshot's path is associated to the URL + this will work, as it is independant from Apache * another web page displays the queue, and the status of each URL ("to process", "processing", "done + path to the screenshot" + you can even imagine having an association betwen a user and an URL, to not display every URL+screenshot to everyone. With this system, several advantages : * php+apache for the webpages * php outside of apache for the "system" parts * you can have the webpages on one server * and you can have several machines (linux, windows, mac -- maybe using virtual machines) to make the screenshots + allow you to get screenshots from different OSes + scales way better ^^ It's not really an answer to the question, but I think it's a better way... Hope this helps !
Here is a [guide](http://www.semicomplete.com/blog/geekery/xvfb-firefox.html) to do screen-capturing using firefox and [xvfb](http://www.x.org/archive/X11R6.8.1/doc/Xvfb.1.html). The advantage with this approach is that there will be no firefox windows opening and closing on your main X server. It will also solve your problem with permissions.
How to capture x screen using PHP, shell_exe and scrot
[ "", "php", "linux", "bash", "screenshot", "" ]
I've recently started to learn C++ and am completely confused with the choices of IDEs and compilers out there. I am competent with interpreted languages and like the simplicity of using any IDE or text editor and then running the interpreter from the command line. Everything works as I expect, regardless of the IDE used, because I use the same interpreter each time. Now that I have started learning C++ I am overwhelmed by the choice of different compilers and more importantly, their differences. It seems that things will be simpler for me (not necessarily easier) if, while learning, I use a text editor and a compiler that I run from the command line. I have a basic understanding of how compiling and linking works and I understand the role of header files. Firstly, are there any books or websites that teach C++ from this approach? (IDE-less) Many books try to point out the differences between IDEs and compilers by selecting two and comparing them, which confuses me. Secondly, how should I set up my workflow? (Ignore the choice of text editor, I am talking about compilers, linkers etc.) I am struggling to understand what differences different compilers have and so please bear this in mind when answering. It seems like the most popular compilers are g++ and CL. Similar question but I am more interested in why some programs will work with some compilers and not others: [C++ Compiler for Windows without IDE?](https://stackoverflow.com/questions/958695/c-compiler-for-windows-without-ide) **Further information:** I am developing on Windows and from what I understand, it seems that there is 'pure' C++ and then C++ that is somehow related to windows, is this Visual C++? I would like to write programs that make use of Windows features but I want to know when I am using windows features and when I am writting code that would work on any platform. **Update**: So it seems that I shouldn't be worrying about compilers when I am just starting out. The reason for me wanting to understand the differences is because I don't want to write code for a specific compiler and get into bad habits. Is this a non-issue?
> Firstly, are there any books or websites that teach C++ from this approach? (IDE-less) Yes, definitely. [Stroustrup's book](https://rads.stackoverflow.com/amzn/click/com/0201700735) has already been mentioned. For learning C++ I'd also recommend two other books: If you like thorough explanations and don't shy away from 1000 pages, look at [Lippman et al](https://rads.stackoverflow.com/amzn/click/com/0201721481). If you rather like a short introduction and don't fear a steep learning curve, look at [Koenig/Moo](https://rads.stackoverflow.com/amzn/click/com/020170353X). Both are excellent books. (BTW, a good place to look for good books has always been the book review section at the [ACCU](http://www.accu.org).) As for which tool chain you want to use: If you rather have a standalone editor and invoke the compiler from the command line, you can do this with either GCC or VC. This approach has the advantage that it is more unlikely to lure you into using something proprietary (like C++/CLI). If you would like to try an IDE, VC Express is fine, once you're past setting up a new C++ project. Of course, the number of options you can tweak for a new project can be very overwhelming. But on the other hand you get things like an integrated debugger. Note that there are other integrated solutions, too. The most mature and prominent is probably eclipse. *Edit*: If you don't mind spending a little money, look at [Comeau](http://www.comeaucomputing.com). It's not free, but it's not expensive either and it's usually considered to be the most standard-conforming C++ compiler around and has excellent error messages. (You can test-drive it at [the website](http://www.comeaucomputing.com/tryitout).) Note that it emits C code, though. That means you have to have another compiler to create an executable program. But both GCC and VC Express will do, so there's no other cost. (Note that using VC you will get Dinkumware's std lib implementation, which is also considered to be a very good one.)
Use [MinGW](http://www.mingw.org/) - it's a command-line C++ development toolchain that allows you create Windows applications. The SO link you quoted seems to have all the relevant details, so I don't really understand why you posted this question.
Learning C++ without an IDE
[ "", "c++", "compiler-construction", "" ]
I have a CSV file which I am processing and putting the processed data into a text file. The entire data that goes into the text file is one big table(comma separated instead of space). My problem is How do I remember the column into which a piece of data goes in the text file? For eg. Assume there is a column called 'col'. I just put some data under col. Now after a few iterations, I want to put some other piece of data under col again (In a different row). How do I know where exactly col comes? (And there are a lot of columns like this.) Hope I am not too vague...
Go with a list of lists. That is: ``` [[col1, col2, col3, col4], # Row 1 [col1, col2, col3, col4], # Row 2 [col1, col2, col3, col4], # Row 3 [col1, col2, col3, col4]] # Row 4 ``` To modify a specific column, you can transform this into a list of columns with a single statement: ``` >>> cols = zip(*rows) >>> cols [[row1, row2, row3, row4], # Col 1 [row1, row2, row3, row4], # Col 2 [row1, row2, row3, row4], # Col 3 [row1, row2, row3, row4]] # Col 4 ```
Python's CSV library has a [function named DictReader](http://docs.python.org/library/csv.html#csv.DictReader) that allow you to view and manipulate the data as a Python dictionary, which allows you to use normal iterative tools.
Whats the best way of putting tabular data into python?
[ "", "python", "file", "csv", "" ]
Does anyone have a more sophisticated solution/library for truncating strings with JavaScript and putting an ellipsis on the end, than the obvious one: ``` if (string.length > 25) { string = string.substring(0, 24) + "..."; } ```
Essentially, you check the length of the given string. If it's longer than a given length `n`, clip it to length `n` (`substr` or `slice`) and add html entity `&hellip;` (…) to the clipped string. Such a method looks like ``` function truncate(str, n){ return (str.length > n) ? str.slice(0, n-1) + '&hellip;' : str; }; ``` If by 'more sophisticated' you mean truncating at the last word boundary of a string then you need an extra check. First you clip the string to the desired length, next you clip the result of that to its last word boundary ``` function truncate( str, n, useWordBoundary ){ if (str.length <= n) { return str; } const subString = str.slice(0, n-1); // the original check return (useWordBoundary ? subString.slice(0, subString.lastIndexOf(" ")) : subString) + "&hellip;"; }; ``` You can extend the native `String` prototype with your function. In that case the `str` parameter should be removed and `str` within the function should be replaced with `this`: ``` String.prototype.truncate = String.prototype.truncate || function ( n, useWordBoundary ){ if (this.length <= n) { return this; } const subString = this.slice(0, n-1); // the original check return (useWordBoundary ? subString.slice(0, subString.lastIndexOf(" ")) : subString) + "&hellip;"; }; ``` More dogmatic developers may chide you strongly for that ("*Don't modify objects you don't own*". I wouldn't mind though). [**edit 2023**] A method to extend the String without tampering with its prototype may be to use a `Proxy`. See [this stackblitz snippet](https://stackblitz.com/edit/web-platform-gxttr1?file=index.js). An approach without extending the `String` prototype is to create your own helper object, containing the (long) string you provide and the beforementioned method to truncate it. That's what the snippet below does. ``` const LongstringHelper = str => { const sliceBoundary = str => str.substr(0, str.lastIndexOf(" ")); const truncate = (n, useWordBoundary) => str.length <= n ? str : `${ useWordBoundary ? sliceBoundary(str.slice(0, n - 1)) : str.slice(0, n - 1)}&hellip;`; return { full: str, truncate }; }; const longStr = LongstringHelper(`Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum`); const plain = document.querySelector("#resultTruncatedPlain"); const lastWord = document.querySelector("#resultTruncatedBoundary"); plain.innerHTML = longStr.truncate(+plain.dataset.truncateat, !!+plain.dataset.onword); lastWord.innerHTML = longStr.truncate(+lastWord.dataset.truncateat, !!+lastWord.dataset.onword); document.querySelector("#resultFull").innerHTML = longStr.full; ``` ``` body { font: normal 12px/15px verdana, arial; } p { width: 450px; } #resultTruncatedPlain:before { content: 'Truncated (plain) n='attr(data-truncateat)': '; color: green; } #resultTruncatedBoundary:before { content: 'Truncated (last whole word) n='attr(data-truncateat)': '; color: green; } #resultFull:before { content: 'Full: '; color: green; } ``` ``` <p id="resultTruncatedPlain" data-truncateat="120" data-onword="0"></p> <p id="resultTruncatedBoundary" data-truncateat="120" data-onword="1"></p> <p id="resultFull"></p> ``` Finally, you can use css only to truncate long strings in HTML nodes. It gives you less control, but may well be viable solution. ``` body { font: normal 12px/15px verdana, arial; margin: 2rem; } .truncate { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; width: 30vw; } .truncate:before{ content: attr(data-longstring); } .truncate:hover::before { content: attr(data-longstring); width: auto; height: auto; overflow: initial; text-overflow: initial; white-space: initial; background-color: white; display: inline-block; } ``` ``` <div class="truncate" data-longstring="Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."></div> ```
Note that this only needs to be done for Firefox. All other browsers support a CSS solution (see [support table](http://caniuse.com/text-overflow)): ``` p { white-space: nowrap; width: 100%; /* IE6 needs any width */ overflow: hidden; /* "overflow" value must be different from visible"*/ -o-text-overflow: ellipsis; /* Opera < 11*/ text-overflow: ellipsis; /* IE, Safari (WebKit), Opera >= 11, FF > 6 */ } ``` The irony is I got that code snippet from Mozilla MDC.
Smart way to truncate long strings
[ "", "javascript", "string", "truncation", "" ]
I probably should have just put all this in one question, sorry for that :( # Second error Ok, this should be the end of errors (hopefully): ``` private static string getCRC(string input, bool appendDate) { string toEnc = string.Format("{0}{1}", input, appendDate == true ? string.Format("{0:yyyyMMdd}", System.DateTime.Now) : ""); System.IO.MemoryStream mStream = new System.IO.MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(toEnc), false); CRC32 oCRC = new CRC32(); return oCRC.GetCrc32(((System.IO.Stream)mStream)).ToString(); } ``` Error is on the return line: > **Compiler Error Message:** CS1502: The best overloaded method match for 'CRC.CRC32.GetCrc32(ref System.IO.Stream)' has some invalid arguments Here is the function it is referring to: ``` public UInt32 GetCrc32(ref System.IO.Stream stream) { //Dim crc32Result As Integer = &HFFFFFFFF UInt32 crc32Result = UInt32.MaxValue; try { byte[] buffer = new byte[BUFFER_SIZE]; int readSize = BUFFER_SIZE; int count = stream.Read(buffer, 0, readSize); int i; UInt32 iLookup; //Dim tot As Integer = 0 while ((count > 0)) { for (i = 0; i <= count - 1; i++) { iLookup = (crc32Result & 0xff) ^ buffer[i]; //crc32Result = ((crc32Result And &HFFFFFF00) \ &H100) And &HFFFFFF ' nasty shr 8 with vb :/ crc32Result = ((UInt32)((crc32Result & 4294967040L) / 256) & UInt32.MaxValue); // nasty shr 8 with vb :/ crc32Result = crc32Result ^ crc32Table[iLookup]; } count = stream.Read(buffer, 0, readSize); } } catch (Exception ex) { HttpContext.Current.Response.Output.Write(string.Format("{0}{1}{2}", ex.Message, Environment.NewLine, ex.StackTrace)); System.Diagnostics.Debugger.Break(); } return (~crc32Result); } ``` As you can see I tried to cast the memorystream as a stream, but I don't think it liked that too much. # First error ([solved here](https://stackoverflow.com/questions/1179682/need-a-little-more-help-converting-a-crc-function-from-vb-net-to-c/1179695#1179695)) If you have not seen my last couple of questions, I have a CRC function written in VB.NET. I used an online converter to convert it over to C#. Here is the original VB code: ``` Public Sub New() Dim dwPolynomial As UInt32 = 3988292384 Dim i As Integer, j As Integer ReDim crc32Table(256) Dim dwCrc As UInt32 For i = 0 To 255 dwCrc = i For j = 8 To 1 Step -1 If (dwCrc And 1) Then dwCrc = ((dwCrc And &HFFFFFFFE) \ 2&) And &H7FFFFFFF dwCrc = dwCrc Xor dwPolynomial Else dwCrc = ((dwCrc And &HFFFFFFFE) \ 2&) And &H7FFFFFFF End If Next j crc32Table(i) = dwCrc Next i End Sub ``` Here is my converted code. I fixed a few of the errors I was having but there are few more that I cannot figure out: ``` public CRC32() { UInt32 dwPolynomial = ((UInt32)3988292384L); int i; int j; UInt32[] crc32Table; crc32Table = new UInt32[256]; UInt32 dwCrc; for (i = 0; i <= 255; i++) { dwCrc = ((UInt32)i); for (j = 8; j >= 1; j -= 1) { if ((dwCrc & 1)) { dwCrc = ((dwCrc & 0xfffffffe) / 2L) & 0x7fffffff; dwCrc = dwCrc ^ dwPolynomial; } else { dwCrc = ((dwCrc & 0xfffffffe) / 2L) & 0x7fffffff; } } crc32Table[i] = dwCrc; } } ``` The first error is on this line: > **Compiler Error Message:** CS0030: Cannot convert type 'uint' to 'bool' > > `if ((dwCrc & 1))` Should I be comparing these two values with a different operator? I am not too sure about why the `&` operator is there to be honest. Thanks SO.
There's no implicit integer-to-boolean conversion in C#. You have to compare against 0 explicity: ``` if ((dwCrc & 1) != 0) ... ```
C# do not assume that 0 is equal false, and that 1 is equal true. Thus ``` if ((dwCrc & 1) == 1) { } ``` Would be what you need.
Need a little more help converting a CRC function from VB.NET to C#
[ "", "c#", "code-conversion", "" ]
Can somebody provide a real life example regarding use of iterators. I tried searching google but was not satisfied with the answers.
Iterators are an abstraction that decouples the concept of position in a collection from the collection itself. The iterator is a separate object storing the necessary state to locate an item in the collection and move to the next item in the collection. I have seen collections that kept that state inside the collection (i.e. a current position), but it is often better to move that state to an external object. Among other things it enables you to have multiple iterators iterating the same collection.
You've probably heard of arrays and containers - objects that store a list of other objects. But in order for an object to represent a list, it doesn't actually have to "store" the list. All it has to do is provide you with methods or properties that allow you to obtain the items of the list. In the .NET framework, the interface [IEnumerable](http://msdn.microsoft.com/en-us/library/9eekhta0.aspx) is all an object has to support to be considered a "list" in that sense. To simplify it a little (leaving out some historical baggage): ``` public interface IEnumerable<T> { IEnumerator<T> GetEnumerator(); } ``` So you can get an enumerator from it. That interface (again, simplifying slightly to remove distracting noise): ``` public interface IEnumerator<T> { bool MoveNext(); T Current { get; } } ``` So to loop through a list, you'd do this: ``` var e = list.GetEnumerator(); while (e.MoveNext()) { var item = e.Current; // blah } ``` This pattern is captured neatly by the `foreach` keyword: ``` foreach (var item in list) // blah ``` But what about creating a new kind of list? Yes, we can just use `List<T>` and fill it up with items. But what if we want to discover the items "on the fly" as they are requested? There is an advantage to this, which is that the client can abandon the iteration after the first three items, and they don't have to "pay the cost" of generating the whole list. To implement this kind of lazy list by hand would be troublesome. We would have to write two classes, one to represent the list by implementing `IEnumerable<T>`, and the other to represent an active enumeration operation by implementing `IEnumerator<T>`. Iterator methods do all the hard work for us. We just write: ``` IEnumerable<int> GetNumbers(int stop) { for (int n = 0; n < stop; n++) yield return n; } ``` And the compiler converts this into two classes for us. Calling the method is equivalent to constructing an object of the class that represents the list.
Why do we need iterators in c#?
[ "", "c#", "iterator", "" ]
Is there a way in jQuery to loop through or assign to an array all of the classes that are assigned to an element? ex. ``` <div class="Lorem ipsum dolor_spec sit amet">Hello World!</div> ``` I will be looking for a "special" class as in "dolor\_spec" above. I know that I could use hasClass() but the actual class name may not necessarily be known at the time.
You can use `document.getElementById('divId').className.split(/\s+/);` to get you an array of class names. Then you can iterate and find the one you want. ``` var classList = document.getElementById('divId').className.split(/\s+/); for (var i = 0; i < classList.length; i++) { if (classList[i] === 'someClass') { //do something } } ``` jQuery does not really help you here... ``` var classList = $('#divId').attr('class').split(/\s+/); $.each(classList, function(index, item) { if (item === 'someClass') { //do something } }); ``` You can use ``` if ($('#divId').hasClass('someClass')) { //do something } ```
Why has no one simply listed. ``` $(element).attr("class").split(/\s+/); ``` EDIT: Split on `/\s+/` instead of `' '` to fix @[MarkAmery](https://stackoverflow.com/q/1227286/673991#comment43501745_10159062)'s objection. (Thanks @[YashaOlatoto](https://stackoverflow.com/q/1227286/673991#comment97559336_10159062).)
Get class list for element with jQuery
[ "", "javascript", "jquery", "html", "" ]
How can I use a class instance variable as an argument for a method decorator in Python? The following is a minimal example shows what I'm trying to do. It obviously fails as the decorator function does not have access to the reference to the instance and I have no idea how to get access to the reference from the decorator. ``` def decorator1(arg1): def wrapper(function): print "decorator argument: %s" % arg1 return function return wrapper class Foo(object): def __init__(self, arg1): self.var1 = arg1 @decorator1(self.var1) def method1(self): print "method1" foo = Foo("abc") foo.method1() ```
It's not going to work; the decorator is called during *class creation* time, which is long before an instance is created (*if* that ever happens). So if your "decorator" needs the instance, you have to do the "decorating" at instantiation time: ``` def get_decorator(arg1): def my_decorator(function): print "get_decorator argument: %s" % arg1 return function return my_decorator class Foo(object): def __init__(self, arg1): self.var1 = arg1 self.method1 = get_decorator(self.var1)(self.method1) def method1(self): print "method1" foo = Foo("abc") foo.method1() ``` Note that I changed the function names according to their meanings; the actual "decorator", i.e. the function that (potentially) modifies the method, is `wrapper` in your case, not `decorator1`.
Your “warper” function is actually a decorator, rather than a warper. Your “decorator1” function is a decorator constructor. If you want to have access to self.var1 in runtime you have to make a warper not decorator: ``` def decorator(function): def wrapper(self,*args,**kwargs): print "Doing something with self.var1==%s" % self.var1 return function(self,*args,**kwargs) return wrapper class Foo(object): def __init__(self, arg1): self.var1 = arg1 @decorator def method1(self): print "method1" foo = Foo("abc") foo.method1() ``` If you want to have more generic decorator, it's better idea to declare a callable class: ``` class decorator: def __init__(self,varname): self.varname = varname def __call__(self,function): varname=self.varname def wrapper(self,*args,**kwargs): print "Doing something with self.%s==%s" % (varname,getattr(self,varname)) return function(self,*args,**kwargs) return wrapper ``` Using: ``` @decorator("var1") ```
How can I use a class instance variable as an argument for a method decorator in Python?
[ "", "python", "decorator", "" ]
I am very surprised to see `HttpWebRequest` has no close method, but its counter-part `HttpWebResponse` has. It makes me a little bit confused and inconvenient. :-) So, we only need to call Close on response and no need to treat with request? My concern is about leaks and better resource usage efficiency. I am using VSTS2008 + C# + .Net 3.5.
Yes, you just need to call it on the response object. A request does absolutely nothing on its own. It doesn't open up a socket or something. It just holds some data and you can just ignore it and throw it away if you don't need it (it's a pure managed resource and garbage collector will take care of it). Actual stuff happens after one of the `GetResponse` methods is called.
An analogy: If I want to talk to you and I am already sure I want to speak to you I will simply call your name (Request). However, is up to you to decide when, how and what to answer to me (Response). So you will have more control over the communication than me, I just started it.
HttpWebRequest has no close method?
[ "", "c#", ".net", ".net-3.5", "" ]
When I compile this code in Visual Studio 2005: ``` template <class T> class CFooVector : public std::vector<CFoo<T>> { public: void SetToFirst( typename std::vector<CFoo<T>>::iterator & iter ); }; template <class T> void CFooVector<T>::SetToFirst( typename std::vector<CFoo<T>>::iterator & iter ) { iter = begin(); } ``` I get these errors: ``` c:\home\code\scantest\stltest1\stltest1.cpp(33) : error C2244: 'CFooVector<T>::SetToFirst' : unable to match function definition to an existing declaration c:\home\code\scantest\stltest1\stltest1.cpp(26) : see declaration of 'CFooVector<T>::SetToFirst' definition 'void CFooVector<T>::SetToFirst(std::vector<CFoo<T>>::iterator &)' existing declarations 'void CFooVector<T>::SetToFirst(std::_Vector_iterator<_Ty,_Alloc::rebind<_Ty>::other> &)' ``` If I add a typedef to the CFooVector template, I can get the code to compile and work: ``` template <class T> class CFooVector : public std::vector<CFoo<T>> { public: typedef typename std::vector<CFoo<T>>::iterator FooVIter; void SetToFirst( FooVIter & iter ); }; template <class T> void CFooVector<T>::SetToFirst( FooVIter & iter ) { iter = begin(); } ``` My question is, why does the typedef work when using the bare `'typename std::vector>::iterator'` declaration did not work?
This compiles as well and reveals the source of VC++ confusion -- allocator type. Apparently outside of the class VS selects different default. Or maybe it can't recognize them to be the same. Compiles on VS2008 (as is) and VS2003 (with space between >>) ``` template <class T> class CFoo { public: T m_t; }; template <class T> class CFooVector : public std::vector<CFoo<T>> { public: void SetToFirst(typename std::vector<CFoo<T>, typename CFooVector::_Alloc>::iterator & iter); }; template <class T> void CFooVector<T>::SetToFirst( typename std::vector<CFoo<T>, typename CFooVector::_Alloc>::iterator & iter ) { iter = begin(); } ``` GCC 3.4 wanted this->begin() and space, but otherwise it can compile the code without explicit allocator type... Definitely looks like MS compiler not as smart as it should be...
The question isn't really about typedef but typename. Whenever the compiler encounters a name that is dependent on a template (basically, anything using `::` after a template, it is unable to determine if that is a type or a value (it could be a static int, for example), so it needs a hint. When you add `typename` you're specifying that the dependent member is actually a type. In your typedef example, you still have the typename in the typedef declaration, but once the typedef is declared, that is not a dependent name. It's just a type, so the `typename` isn't necessary when referring to the typedef. Basically, the compiler can't be sure that `std::vector<CFoo<T>>::iterator` is a type. But it knows that `FooVIter` is a type, because it's a typedef. Typedefs are always types.
Why is the use of typedef in this template necessary?
[ "", "c++", "templates", "typedef", "typename", "" ]
``` if($country == 224 || $country == 223 || $country == 39 && $zip == '' ){ $_SESSION['sess_msg'] = "Please enter a Valid zipcode"; header("location: $SITE_PATH?p=account.profile.name"); exit; } ``` ``` variable value -------- ----- $country 224 $zip 11111 ``` I know that `$zip` isn't empty, but the code executes as if it is. I even print it out to the browser in a debugging statement to verify that it has a value. What is causing my program to act as if `$zip` does not have a value?
The `&&` operator has a higher [precedence](http://docs.php.net/manual/en/language.operators.precedence.php) than the `||` operator. So your expression is equal to: ``` $country == 224 || $country == 223 || ($country == 39 && $zip == '') ``` The solution: ``` ($country == 224 || $country == 223 || $country == 39) && $zip == '' ```
Have you tried using parentheses to give order to your operations? ``` ($country == 22 || $country == 223 || $country == 39) && ($zip == '') ```
Strange php if statement problem
[ "", "php", "conditional-statements", "" ]
I need to shorten a string down.. Lets say we have a string with the length 500. I only want the first part of it - **max 180 characters**, ending with the **last word** before reaching the 180. I don't want to cut the string short in the middle of a word. How is this achived? it does not have to perform all that well.. it is something that happens a couple of times a day, not more.
A really easy way is by using this regex: ``` string trimmed = Regex.Match(input,@"^.{1,180}\b").Value; ``` The only problem with that one is that it could contain trailing whitespace. To fix that, we can add a little negative look-behind: ``` string trimmed = Regex.Match(input,@"^.{1,180}\b(?<!\s)").Value; ``` That should do the trick.
How about looking at char 180, and move backwards to find the first char in (lets say space, comma, exclamation etc) indicating the start of the previous word?
180 first characters of a string ending with a word
[ "", "c#", "asp.net", "" ]
I wanted to break a css file into an array with PHP. Ex: ``` #selector{ display:block; width:100px; } #selector a{ float:left; text-decoration:none; } ``` Into a php array... ``` array(2) { ["#selector"] => array(2) { [0] => array(1) { ["display"] => string(5) "block" } [1] => array(1) { ["width"] => string(5) "100px" } } ["#selector a"] => array(2) { [0] => array(1) { ["float"] => string(4) "left" } [1] => array(1) { ["text-decoration"] => string(4) "none" } } } ``` Any ideas? Oh : Edit : I am not worried about ill formed CSS files in this instance. Doesn't ahve to be bulletproof as long as its not greedy
This should do it: ``` <?php $css = <<<CSS #selector { display:block; width:100px; } #selector a { float:left; text-decoration:none } CSS; // function BreakCSS($css) { $results = array(); preg_match_all('/(.+?)\s?\{\s?(.+?)\s?\}/', $css, $matches); foreach($matches[0] AS $i=>$original) foreach(explode(';', $matches[2][$i]) AS $attr) if (strlen(trim($attr)) > 0) // for missing semicolon on last element, which is legal { list($name, $value) = explode(':', $attr); $results[$matches[1][$i]][trim($name)] = trim($value); } return $results; } var_dump(BreakCSS($css)); ``` Quick Explanation: The regexp is simple and boring. It just matches all "anything, possible space, curly bracket, possible space, anything, close curly bracket". From there, the first match is the selector, the second match is the attribute list. Split that by semicolons, and you're left with key/value pairs. Some trim()'s in there to get rid of whitespace, and that's about it. I'm guessing that your next best bet would probably be to explode the selector by a comma so that you can consolidate attributes that apply to the same thing etc., but I'll save that for you. :) Edit: As mentioned above, a real grammar parser would be more practical... but if you're assuming well-formed CSS, there's no reason why you need to do anything beyond the simplest of "anything { anything }". Depends on what you want to do with it, really.
If you need the same for CSS rules with multi selectors and with breaklines: ``` <?php $css = " #selector { display:block; width:100px; } #selector a:hover div.asd, #asd h1.asd { float:left; text-decoration:none; } "; preg_match_all( '/(?ims)([a-z0-9\s\,\.\:#_\-@]+)\{([^\}]*)\}/', $css, $arr); $result = array(); foreach ($arr[0] as $i => $x) { $selector = trim($arr[1][$i]); $rules = explode(';', trim($arr[2][$i])); $result[$selector] = array(); foreach ($rules as $strRule) { if (!empty($strRule)) { $rule = explode(":", $strRule); $result[$selector][][trim($rule[0])] = trim($rule[1]); } } } var_dump($result); ?> ``` output: ``` array(2) { ["#selector"]=> array(2) { [0]=> array(1) { ["display"]=> string(5) "block" } [1]=> array(1) { ["width"]=> string(5) "100px" } } ["#selector a:hover div.asd, #asd h1.asd"]=> array(2) { [0]=> array(1) { ["float"]=> string(4) "left" } [1]=> array(1) { ["text-decoration"]=> string(4) "none" } } } ``` **Update: Added support for multiple selectors like: .box, .element, div{ ... }**
Break a CSS file into an array with PHP
[ "", "php", "css", "regex", "parsing", "" ]
I have a sample xml file created using Editplus( in windows). ``` < ?xml version="1.0" encoding="UTF-8" ?> < badges > < row UserId="3714" Name="Teacher" Date="2008-09-15T08:55:03.923"/> < row UserId="994" Name="Teacher" Date="2008-09-15T08:55:03.957"/> < / badges> ``` My goal here is to get this information into Oracle DB table. As suggested here <https://stackoverflow.com/questions/998055?sort=newest#sort-top>, I tried to execute the sql commands. But couldn't succeed, ========================= sql query 1 ============================ ``` SQL> SELECT XMLTYPE(bfilename('D', 'tmp.xml'), nls_charset_id('UTF8')) xml_data FROM dual; XML_DATA ------------------------------------------------------------ <?xml version="1.0" encoding="WINDOWS-1252"?> <badges> <row UserId="3714" Name ``` In the output, I see half of the xml file got truncated. And the encoding type in output is seen as WINDOWS-1252. Could someone explain why is it happening so? ========================================================================== =============================== sql query 2 =============================== ``` SQL> SELECT UserId, Name, to_timestamp(dt, 'YYYY-MM-DD"T"HH24:MI:SS.FF3') dt 2 FROM (SELECT XMLTYPE(bfilename('D', 'tmp.xml'), 3 nls_charset_id('WINDOWS-1252')) xml_data 4 FROM dual), 5 XMLTable('for $i in /badges/row 6 return $i' 7 passing xml_data 8 columns UserId NUMBER path '@UserId', 9 Name VARCHAR2(50) path '@Name', 10 dt VARCHAR2(25) path '@Date'); ``` `XMLTable('for $i in /badges/row * ERROR at line 5: ORA-00933: SQL command not properly ended` ===================================================================== The same query was working here <https://stackoverflow.com/questions/998055?sort=newest#sort-top>. But for me it doesn't. I have oracle 10g installed on my machine. Could someone suggest the corrections to make the queries work. Thanks.
Considering your first point, your output is only truncated on display. You can change how many bytes are displayed in SQL\*Plus with `SET LONG`: ``` SQL> SELECT XMLTYPE(bfilename('D', 'test.xml'), 2 nls_charset_id('WINDOWS-1252')) xml_data FROM dual; XML_DATA -------------------------------------------------------------------------------- <?xml version="1.0" encoding="UTF-8"?> <badges> <row UserId="3714" Name= SQL> SET LONG 4000 SQL> / XML_DATA -------------------------------------------------------------------------------- <?xml version="1.0" encoding="UTF-8"?> <badges> <row UserId="3714" Name="Teacher" Date="2008-09-15T08:55:03.923"/> <row UserId="994" Name="Teacher" Date="2008-09-15T08:55:03.957"/> </badges> ``` As you have noticed, your character set will be modified per your NLS session parameters (i-e: the file will be translated to the character set of your client). For the second point: * What version of SQL\*Plus are you using ? It might be older than the database and not recognizing the synthax * could you post the exact query as you typed it in SQL\*Plus (Please use the CODE feature of SO) because I can not reproduce with Oracle 10.2.0.3: ``` SQL> SELECT UserId, NAME, to_timestamp(dt, 'YYYY-MM-DD"T"HH24:MI:SS.FF3') dt 2 FROM (SELECT XMLTYPE(bfilename('D', 'test.xml'), 3 nls_charset_id('WINDOWS-1252')) xml_data FROM dual), 4 XMLTable('for $i in /badges/row 5 return $i' 6 passing xml_data columns UserId NUMBER path '@UserId', 7 NAME VARCHAR2(50) path '@Name', 8 dt VARCHAR2(25) path '@Date'); USERID NAME DT ---------- --------- ---------------------------- 3714 Teacher 15/09/08 08:55:03,923000000 994 Teacher 15/09/08 08:55:03,957000000 ``` **Update:** This XMLTable synthax must be a new feature of the 10gR2 (10.2.\*) (needs confirmation) You can however use another method of accessing XML Data(described in [another SO](https://stackoverflow.com/questions/985894/oracle-pl-sql-loop-through-xmltype-nodes/985985#985985)): ``` SQL> SELECT extractvalue(column_value, '/row/@UserId') "userID", 2 extractvalue(column_value, '/row/@Name') "Name", 3 extractvalue(column_value, '/row/@Date') "Date" 4 FROM TABLE(XMLSequence(XMLTYPE(bfilename('D', 'tmp.xml'), 5 nls_charset_id('WINDOWS-1252')).extract('/badges/row'))) t; userID Name Date ------- --------- ------------------------ 3718 Teacher 2008-09-15T08:55:03.923 994 Teacher 2008-09-15T08:55:03.957 ```
I had the exact same problem, I was wondering why: ``` encoding="UTF-8" ``` changed to ``` encoding="WINDOWS-1250" ``` in my case (after loading). Then I realised what Oracle does here: it converts the utf-8 encoded xml to the default character set of your database, in order to be able to store it. That's why it changes the value of 'encoding'. If the default character set of your databse is utf-8, then 'encodig' will not change. If your xml *actually* has utf-8 encoded characters, then trying to load it in the database with `nls_charset_id('WINDOWS-1252')` will throw an error. So to put it short: you should not worry about `encoding="UTF-8"` changing to `encoding="WINDOWS-1252"`, just ignore it - the database is doing its job.
xml to oracle DB table : encountering problems
[ "", "sql", "oracle", "oracle10g", "ora-00933", "" ]
I'd like to get a table which stores students data in [long format](https://en.wikipedia.org/wiki/Wide_and_narrow_data#Narrow) and the marks they receive for all of their subjects in one query. This is my table structure: Table: `markdetails` ``` ## studid ## ## subjectid ## ## marks ## A1 3 50 A1 4 60 A1 5 70 B1 3 60 B1 4 80 C1 5 95 ``` Table: `student info` Actual Structure: ``` ## studid ## ## name ## A1 Raam B1 Vivek c1 Alex ``` I want the result set to have the following [wide format](https://en.wikipedia.org/wiki/Wide_and_narrow_data#Wide) structure as result of the pivotization: Table: `Student Info` ``` ## studid ## ## name## ## subjectid_3 ## ## subjectid_4 ## ## subjectid_5 ## A1 Raam 50 60 70 B1 Vivek 60 80 null c1 Alex null null 95 ``` How can I accomplish this in SQLite?
First you need to change the current table to a temp table: ``` alter table student_info rename to student_name ``` Then, you'll want to recreate `student_info`: ``` create table student_info add column ( stuid VARCHAR(5) PRIMARY KEY, name VARCHAR(255), subjectid_3 INTEGER, subjectid_4 INTEGER, subjectid_5 INTEGER ) ``` Then, populate `student_info`: ``` insert into student_info select u.stuid, u.name, s3.marks as subjectid_3, s4.marks as subjectid_4, s5.marks as subjectid_5 from student_temp u left outer join markdetails s3 on u.stuid = s3.stuid and s3.subjectid = 3 left outer join markdetails s4 on u.stuid = s4.stuid and s4.subjectid = 4 left outer join markdetails s5 on u.stuid = s5.stuid and s5.subjectid = 5 ``` Now, just drop your temp table: ``` drop table student_temp ``` And that's how you can quickly update your table. SQLite lacks a `pivot` function, so the best you can do is hard-code some left joins. A `left join` will bring match any rows in its join conditions and return `null` for any rows from the first, or left, table that don't meet the join conditions for the second table.
Here is the SQL to create the schema for this example. For anyone who wants to try the solution from @Eric. ``` create table markdetails (studid, subjectid, marks); create table student_info (studid, name); insert into markdetails values('A1', 3, 50); insert into markdetails values('A1', 4, 60); insert into markdetails values('A1', 5, 70); insert into markdetails values('B1', 3, 60); insert into markdetails values('B1', 4, 80); insert into markdetails values('C1', 5, 95); insert into student_info values('A1', 'Raam'); insert into student_info values('B1', 'Vivek'); insert into student_info values('C1', 'Alex'); ``` Here is an alternative solution using `case` with `group by`. ``` select si.studid, si.name, sum(case when md.subjectid = 3 then md.marks end) subjectid_3, sum(case when md.subjectid = 4 then md.marks end) subjectid_4, sum(case when md.subjectid = 5 then md.marks end) subjectid_5 from student_info si join markdetails md on md.studid = si.studid group by si.studid, si.name ; ``` For comparison, here is the same select statement from @Eric's solution: ``` select u.stuid, u.name, s3.marks as subjectid_3, s4.marks as subjectid_4, s5.marks as subjectid_5 from student_info u left outer join markdetails s3 on u.stuid = s3.stuid and s3.subjectid = 3 left outer join markdetails s4 on u.stuid = s4.stuid and s4.subjectid = 4 left outer join markdetails s5 on u.stuid = s5.stuid and s5.subjectid = 5 ; ```
How to pivot in SQLite or i.e. select in wide format a table stored in long format?
[ "", "sql", "sqlite", "pivot", "" ]
I'm now writing a searching application on C#/ASP.NET. User inputs a keyword into a textbox, and then my app finds appropriate results from SQL Server through ADO.NET. I want to implement ability to search using AND/OR keyword in my application. For example: Now my users can input a keyword such as "Cisco". Now they want to search with "Cisco AND Microsoft" or "Cisco OR Microsoft" How can I do this?
[Full text search and contains?](http://msdn.microsoft.com/en-us/library/ms513993.aspx)
Are you sure you want to use SQL Server for search? Consider [Lucene.NET](http://incubator.apache.org/lucene.net/)
And/or keyword when search with ASP.NET
[ "", "c#", "asp.net", "sql-server", "ado.net", "" ]
I'm programming an interprocess communication module (Process A and Process B). Is there any way the communication thread in B can run (be unlock) as soon as process A finishes a specific action, I mean without B doing any polling nor B waiting too much after A finishes its action? Which are the concepts/models/design patterns governing these issues? (Something more precise than interprocess synchronization). Which libraries/methods do you recommend? Thanks. Edit: I'm looking for methods suitable for each of the three main OSes: Ms Windows, Apple Mac OS X, GNU/Linux.
This is quite hard job: For Unix OSes you can use: * pthread condition and mutex with setpshared argument. Note: it is supported well under Linux 2.6, Solaris, but it does not supported FreeBSD and Cygwin (don't know about Mac OS X) * For Unixes you may also use named semaphores, but I don't know the support level of them * For Windows there are some events... This is hard job, especially for IPC... So if you want something portable, I'd suggest to take a look on Boost.Interprocess that has conditions and mutexes... But make sure that all feature supported on all OSes you want to support. **Things you should note about Boost.Interprocess** Check carefully level of support for each Unix OS you need to work with, because Boost.Interprosess uses pthread\_\* functions that are not always supported... and then fails back to emulation -- check the quality of such emulation Also, check how this stuff works on Windows -- as far as I know that there is no "in-shared-memory" mutexes in Win32 API, generally named objects should be used, so check what is supported and how.
**EDIT:** I mistakenly thought you needed inter thread synchronizing, Revised for IPC I think you need something like waitable events. In Windows you can use [`CreateEvent()`](http://msdn.microsoft.com/en-us/library/ms682396(VS.85).aspx), to create (or get an existing) named, auto-reset event. When process A completes processing, it should call [`SetEvent()`](http://msdn.microsoft.com/en-us/library/ms686211(VS.85).aspx), while process B should call [`WaitForSingleObject()`](http://msdn.microsoft.com/en-us/library/ms687032(VS.85).aspx) to sleep until completion (or timeout). Alternately, you can use semaphores created by [`CreateSemaphore()`](http://msdn.microsoft.com/en-us/library/ms682438(VS.85).aspx), initialized to 0. Process A signals completion by calling [`ReleaseSemaphore()`](http://msdn.microsoft.com/en-us/library/ms685071(VS.85).aspx), while process B again uses [`WaitForSingleObject()`](http://msdn.microsoft.com/en-us/library/ms687032(VS.85).aspx) to wait for completion. Under Linux and OS X you can use semaphores to a similar effect. use [`sem_open()`](http://www.kernel.org/doc/man-pages/online/pages/man3/sem_open.3.html) to create a named semaphore, with 0 as its initial value. When process A completes, it should call [`sem_post()`](http://www.kernel.org/doc/man-pages/online/pages/man3/sem_post.3.html) to increment the semaphore, while process B should call [`sem_wait()`](http://www.kernel.org/doc/man-pages/online/pages/man3/sem_wait.3.html) to sleep until completion. **NOTE**: the semaphore method may allow multiple completions to be signaled, you should handle this by setting a maximum count under Windows, or checking the current sem value for sanity with [`sem_getvalue()`](http://www.kernel.org/doc/man-pages/online/pages/man3/sem_getvalue.3.html) --- I think condition variables fit what you're trying to do, here's a sample that would work on Linux and OSX ``` #include <pthread.h> /* no error checking, quick and dirty sample */ pthread_mutex_t g_mutex; pthread_cond_t g_cond; int a_done = 0; void init(void) { pthread_mutex_init(&g_mutex, NULL); pthread_cond_init(&g_cond, NULL); } void thread_a(void *arg) { /* do something here... */ pthread_mutex_lock(&g_mutex); a_done = 1; pthread_cond_signal(&g_cond); pthread_mutex_unlock(&g_mutex); } void thread_b(void *arg) { /* wait for a to complete */ pthread_mutex_lock(&g_mutex); while (!a_done) pthread_cond_wait(&g_cond, &g_mutex); a_done = 0; pthread_mutex_unlock(&g_mutex); } ``` Under Windows, you can use [pthreads-win32](http://sourceware.org/pthreads-win32/), or native condition variables under Vista, see the [MSDN Condition Variables](http://msdn.microsoft.com/en-us/library/ms682052(VS.85).aspx) page for more information. References: * [`pthread_cond_wait`](http://linux.die.net/man/3/pthread_cond_wait) * [`pthread_cond_signal`](http://linux.die.net/man/3/pthread_cond_signal)
Unlock a thread from another process, in c++
[ "", "c++", "synchronization", "ipc", "interprocess", "" ]
There is probably a really straightforward answer to this but I'm having difficulty finding it. Simple, I have a TreeNode and I would like to make its visibility false. (or another way of not allowing it to be shown until required). **Edit - Another Question?** I'm confused as to how there isn't a Visible attribute but then there is the property: ``` Node.PrevVisibleNode; ``` What is the difference between this and `Node.PrevNode`? Thanks,
I don't think you can do that. There is an `IsVisible` property, but it is readonly and will indicate whether the node is currently visible within the client area of the `TreeView` control. I think you will need to remove it from the nodes collection in which it resides (and optionally remember the position of it to be able to restore it.
Hmm... I originally (and incorrectly) mentioned `IsVisible`. However, on inspection I expect the answer is simply: don't add it until you need it. This is easier if your UI model is an abstraction *above* your actual data model, so you can store items in the data model *regardless* of their visibility, and simply update the UI (add/remove/update nodes) as necessary.
How do I make a TreeNode not visible? (C#)
[ "", "c#", ".net", "winforms", "c#-2.0", "treenode", "" ]
I have two frames in a frameset - `frame[0]` contains a script that loads a page into `frame[1]` using ``` top.frames[1].location.href = 'http://some_location.com/page.html'; ``` and then performs actions on that page, for example searching text within the page. I need the script to wait until `page.html` has loaded in the second frame before doing this, and I can't use `onload=...` in the second page because I have no control over its source. Is there a way to do this?
use onload event of FRAME element edit: ``` <frame onload = "if( top.frames[1].location.pathname == '/page.html' " ) alert( 'loaded' )"; ``` or if you load different pages to the same frame use this: ``` <frame onload = "if( top.frames[1].location.pathname != 'about:blank' " ) alert( 'loaded' )"; ``` or ``` <frame src = '/dummyInitial.html' onload = "if( top.frames[1].location.pathname != '/dummyInitial.html' " ) alert( 'loaded' )"; ```
If you have no control over the loaded page's source and more importantly, if it is coming from another domain, then there is only one answer: You can't. Interframe communication between different domains is NOT possible. And you need interframe communication because you would need something like jquery's ready function in the loaded page to determine if the entire page (the DOM) is loaded.
How to get javascript in one frame to wait until a page has loaded in a second frame
[ "", "javascript", "frame", "wait", "frameset", "" ]
I've got a union : ``` union my_union { short int Int16; float Float; }; ``` I'd like to create : ``` const my_union u1 = ???; const my_union u2 = ???; ``` and initialize their values to be of different types respectively : u1 -> int16 u2 -> float How do I do that ? If the above is not possible, are there any workarounds?
union can have any number of constructors - this will work for any datatypes without constructor, so your example is well if exclude string (or make pointer to string) ``` #include <string> using namespace std; union my_union { my_union(short i16): Int16(i16){} my_union(float f): Float(f){} my_union(const string *s): str(s){} short int Int16; float Float; const string *str; }; int main() { const my_union u1 = (short)5; const my_union u2 = (float)7.; static const string refstr= "asdf"; const my_union u3 = &refstr; } ``` There is more complicated way to create class, that owns by union, class must have a selector (scalar or vector datatype used) - to correctly destroy string.
Notwithstanding the ban on non-POD member data (as elaborated above) the Standard says: at 8.5.1.15: When a union is initialized with a brace-enclosed initializer, the braces shall only contain an initializer for the first member of the union. so ``` const my_union u1 = {1}; ``` should work but this form cannot be used for the second (and subsequent) members.
Initializing aggregate unions
[ "", "c++", "constants", "unions", "" ]
I'm using .NET 2.0 I have a large array of string. I want to check whether a particular string is there in the array or not, I'm not sure, whether following code is optimized or I need to make it more optimized. please guide. ``` string []test_arr= new string[]{"key1","key2","key3"}; Boolean testCondition = (new List<string>(test_arr)).Contains("key3"); ``` I also wants to know more about 1. .NET Generics 2. .NET Attributes 3. .NET Reflections is there any good reference or book, that someone has already refer then help me out !
``` string []test_arr= new string[]{"key1","key2","key3"}; bool testCondition = Array.Exists ( test_arr, delegate(string s) { return s == "key3";} ); ```
If its possible you could sort your array (using static [Array.Sort](http://msdn.microsoft.com/en-us/library/system.array.sort.aspx) method) and then use [Array.BinarySearch](http://msdn.microsoft.com/en-us/library/system.array.binarysearch.aspx) Alternatively you need to use a more optimised data structure for your strings.
How to check Array of strings contains a particular string?
[ "", "c#", "arrays", "generics", "collections", "attributes", "" ]
I have been using so many 3rd party libraries(jar files) that my CLASSPATH is completely messed up as i have to include the path for every single jar file that i use. I've been wondering if there is a way to include all the jar files in a folder using wildcard(\*) operator (like \*.jar). But it seems to be not working. Is there any other way that can shorten the CLASSPATH that currently looks like an essay ;) on my PC?.
From: <http://java.sun.com/javase/6/docs/technotes/tools/windows/classpath.html> > Class path entries can contain the basename wildcard character `*`, which is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR. For example, the class path entry `foo/*` specifies all JAR files in the directory named foo. A classpath entry consisting simply of `*` expands to a list of all the jar files in the current directory. This should work in Java6, not sure about Java5 (If it seems it does not work as expected, try putting quotes. eg: `"foo/*"`)
This works on Windows: ``` java -cp "lib/*" %MAINCLASS% ``` where `%MAINCLASS%` of course is the class containing your main method. Alternatively: ``` java -cp "lib/*" -jar %MAINJAR% ``` where `%MAINJAR%` is the jar file to launch via its internal manifest.
How to use a wildcard in the classpath to add multiple jars?
[ "", "java", "classpath", "wildcard", "" ]
I posted [a question yesterday](https://stackoverflow.com/questions/1231447/jquery-parsing-json-data-having-trouble-with-variable-name) dealing with parsing json data. In one of the follow up answers someone said I was taking a performance hit by using the jQuery append() function within each iteration, while using each(). I was doing: ``` $.getJSON("http://myurl.com/json?callback=?", function(data) { // loop through each post $.each(data.posts, function(i,posts){ ... parsing ... // append $('ul').append('<li>...</li>'); }); }); ``` I modified it to be this: ``` $.getJSON("http://myurl.com/json?callback=?", function(data) { // create array arrPosts = new Array(); // loop through each post $.each(data.posts, function(i,posts){ ... parsing ... arrPosts[i] = '<li> ... </li>'; }); // output for (i=0;i<arrPosts.length;i++){ $('ul').append(arrPosts[i]); } }); ``` And this seems to be working properly, example demo: <http://jsbin.com/isuro> But am I doing this right? I'm somewhat of a noob and just want to make sure I'm approaching this correctly. Thanks for any advice!
you shouldn't have to iterate to output. ``` $('ul').append( arrPosts.join( "\n" ) ); ``` Otherwise looks fine
You are still doing it wrong. The point is you don't want to modify DOM in a loop, because it's just so slow. You were adding items to an array so then you can just add all of them in one function call: ``` $('ul').append(arrPosts.join('')); ```
Appending to the dom inside each iteration or create an array and output?
[ "", "javascript", "jquery", "arrays", "json", "dom", "" ]
jqGrid exposes a property `rowNum` where you can set the number of rows to display for each page. How do you set the grid to just display ALL rows? Right now I'm just setting the `rowNum` to something really high like `<%= int.MaxValue %>` but I'm wondering if there is a better way.
In the latest version of jqGrid, you can set rowNum to **-1** to instruct the grid to always display all rows: ``` rowNum: -1 ``` See the latest jqGrid documentation [here](http://www.trirand.com/jqgridwiki/doku.php?id=wiki:options). Specifically: > Sets how many records we want to view in the grid. This parameter is passed to the url for use by the server routine retrieving the data. Note that if you set this parameter to 10 (i.e. retrieve 10 records) and your server return 15 then only 10 records will be loaded. Set this parameter to -1 (unlimited) to disable this checking. --- **Update** Unfortunately this behavior was broken in jqGrid 3.6.3. According to [this post from Tony](http://www.trirand.net/forum/default.aspx?g=posts&t=204): > Yes, this is true. The reason is the new introduced scroll:1. In the future we will correct this behavior. So the jqGrid developers are aware of this problem and apparently are planning to fix it in a future release. Unfortunately this post was from over a year ago... At this time, all I can recommend is that you set `rowNum` to a very large number to simulate the behavior of `-1`. --- You can also try whatispunk's solution below of using `rowNum: ''`. However, I tried this on a grid containing local data (`loadonce: true`). When attemping to sort the rows all of the grid's local data would disappear. So this solution does not seem to work for grids with local data, unless this defect has been fixed in a later version of jqGrid (I tested it on jqGrid 3.8.2). If you have feedback, please post a comment below! --- **Update - April 16, 2014** [According to the jqGrid team](https://github.com/tonytomov/jqGrid/issues/317) this is now fixed: > I have added support to set different display values on pager select box including -1 for all. I have not had a chance to test to confirm the fix, though. Presumably this change will be in the next release after jqGrid 4.6.0.
jqgrid (3.5 anyway) doesn't seem to have an elegant built in way to do this. The best I have found so far is to add something like the following to your grid options: ``` rowList:[10,20,30,100000000], loadComplete: function() { $("option[value=100000000]").text('All'); }, ``` Where the 100000000 is some arbitrarily higher number than the maximum # of rows you will ever return, and the option[value=] line is so your user interface looks a little nicer. Jenky, but works for me.
How to show all rows in the jqGrid?
[ "", "javascript", "jquery", "jqgrid", "rowcount", "" ]
This is one of those situations where I feel like I'm missing a crucial keyword to find the answer on Google... I have a bag of parameters and I want to make the browser navigate to a GET URL with the parameters. Being a jQuery user, I know that if I wanted to make an ajax request, I would simply do: ``` $.getJSON(url, params, fn_handle_result); ``` But sometimes I don't want to use ajax. I just want to submit the parameters and get a page back. Now, I know I can loop the parameters and manually construct a GET URL. For POST, I can dynamically create a form, populate it with fields and submit. But I'm sure somebody has written a plugin that does this already. Or maybe I missed something and you can do it with core jQuery. So, does anybody know of such a plugin? EDIT: Basically, what I want is to write: ``` $.goTo(url, params); ``` And optionally ``` $.goTo(url, params, "POST"); ```
jQuery Plugin seemed to work great until I tried it on IE8. I had to make this slight modification to get it to work on IE: ``` (function($) { $.extend({ getGo: function(url, params) { document.location = url + '?' + $.param(params); }, postGo: function(url, params) { var $form = $("<form>") .attr("method", "post") .attr("action", url); $.each(params, function(name, value) { $("<input type='hidden'>") .attr("name", name) .attr("value", value) .appendTo($form); }); $form.appendTo("body"); $form.submit(); } }); })(jQuery); ```
Here's what I ended up doing, using the tip from redsquare: ``` (function($) { $.extend({ doGet: function(url, params) { document.location = url + '?' + $.param(params); }, doPost: function(url, params) { var $form = $("<form method='POST'>").attr("action", url); $.each(params, function(name, value) { $("<input type='hidden'>") .attr("name", name) .attr("value", value) .appendTo($form); }); $form.appendTo("body"); $form.submit(); } }); })(jQuery); ``` Usage: ``` $.doPost("/mail/send.php", { subject: "test email", body: "This is a test email sent with $.doPost" }); ``` Any feedback would be welcome. **Update:** see dustin's answer for a version that works in IE8
Non-ajax GET/POST using jQuery (plugin?)
[ "", "javascript", "jquery", "jquery-plugins", "" ]
When should I use a function rather than a stored procedure in SQL, and vice versa? What is the purpose of each?
Functions are computed values and cannot perform permanent environmental changes to `SQL Server` (i.e., no `INSERT` or `UPDATE` statements allowed). A function can be used inline in `SQL` statements if it returns a scalar value or can be joined upon if it returns a result set. *A point worth noting from comments, which summarize the answer. Thanks to @Sean K Anderson:* > Functions follow the computer-science definition in that they MUST return a value and cannot alter the data they receive as parameters > (the arguments). Functions are not allowed to change anything, must > have at least one parameter, and they must return a value. Stored > procs do not have to have a parameter, can change database objects, > and do not have to return a value.
Here's a table summarizing the differences: | | Stored Procedure | Function | | --- | --- | --- | | Returns | Zero or more values | A single value (which may be a scalar or a table) | | Can use transaction? | Yes | No | | Can output to parameters? | Yes | No | | Can call each other? | Can call a function | Cannot call a stored procedure | | Usable in SELECT, WHERE and HAVING statements? | No | Yes | | Supports exception handling (via try/catch)? | Yes | No |
Function vs. Stored Procedure in SQL Server
[ "", "sql", "sql-server", "t-sql", "stored-procedures", "sql-function", "" ]
I have created 2 forms in VS Studio 2008 Express Edition and declare them with public static in main program.cs file I just want to switch between the two forms with ShowDialog and Close but when trying to close the second form and open the first form again with showdialog it says I cannot use showDialog when the form is already visible, whereas it isn't true since I closed it before to show the second form. It asked me to set the form visible property to false before using showdialog, so I did it ``` internal static void CloseSecondForm(FirstForm FirstForm) { FirstForm .Close(); SecondForm.Visible = false; SecondForm.ShowDialog(); } ``` But then it says I cannot use ShowDialog because the form is already shown in Dialog Mode and that I must close it. So I did what it asked ``` internal static void CloseSecondForm(FirstForm FirstForm) { FirstForm .Close(); SecondForm.Visible = false; SecondForm.Close(); SecondForm.ShowDialog(); } ``` But it still pretends that the form is already opened with ShowDialog ! Is this a Bug in my prog or in Winform ? Update: this is the whole code I posted in 5th answer (I want to use showdialog and not show because I may have a 3rd form in Background that I don't want the user to access): ``` [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Form1 = new Form1(); Form2 = new Form2(); Form1.ShowDialog(); Application.Run(); } // called from Form1 BUTTON internal static void ShowForm2(Form1 Form1) { Form1.Hide(); Form2.ShowDialog(); } // called from Form2 BUTTON internal static void ShowForm1(Form2 Form2) { Form2.Hide(); Form1.ShowDialog(); } ``` --- I tried with Hide as suggested but it doesn't work either. This is the whole program, what I want to do is very simple: I have two forms initially created in program with one button on each form to close self and open the other. I put all the logic in program.cs below: ``` using System; using System.Windows.Forms; namespace twoforms { static class Program { /// <summary> /// The main entry point for the application. /// </summary> /// public static Form1 Form1; public static Form2 Form2; [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Form1 = new Form1(); Form2 = new Form2(); Form1.ShowDialog(); Application.Run(); } // called from Form1 BUTTON internal static void ShowForm2(Form1 Form1) { Form1.Hide(); Form2.ShowDialog(); } // called from Form2 BUTTON internal static void ShowForm1(Form2 Form2) { Form2.Hide(); Form1.ShowDialog(); } } } ```
This is from MSDN: > When a form is displayed as a modal > dialog box, clicking the Close button > (the button with an X at the > upper-right corner of the form) causes > the form to be hidden and the > DialogResult property to be set to > DialogResult.Cancel. Unlike modeless > forms, the Close method is not called > by the .NET Framework when the user > clicks the close form button of a > dialog box or sets the value of the > DialogResult property. Instead the > form is hidden and can be shown again > without creating a new instance of the > dialog box. Because a form displayed > as a dialog box is not closed, you > must call the Dispose method of the > form when the form is no longer needed > by your application. So once you show a form using ShowDialog and you now want to close it, just let it return DialogResult.Cancel This will hide (it will still be in memory) your first form. Now you can call ShowDialog on your second form. Again, if you want to switch to first form then let the second form return DialogResult.Cancel and now just call ShowDialog on first form.
This is a bug in your program. When you have two instances of a form (call them A and B), you obviously cannot continually show one from the other using ShowDialog. If you could do this, it would mean that A shows B modally, and B then shows A modally, and A then shows B modally etc. This would be like building a house with two bricks, where you just keep taking the bottom brick and placing it on top of the other. Your best solution is to not make these forms static, and instead just create new instances of each form as you need them. Your second-best solution is to use Show instead of ShowDialog; if you only have one of these forms showing at a time anyway, ShowDialog has no purpose. Static forms are almost always a bad idea (and I'm being polite about "almost"). If your forms are taking a long time to create, you should identify what resource is taking so long to load and cache that as a static object, instead of trying to cache the entire form as static.
Very strange bug when using Show Dialog on C# Winform
[ "", "c#", "winforms", "dialog", "modal-dialog", "" ]
How to make tabulation look different than whitespace in vim (highlighted for example). That would be useful for code in Python.
I use something like this: ``` set list listchars=tab:»·,trail:·,precedes:…,extends:…,nbsp:‗ ``` Requires Vim7 and I'm not sure how well this is going to show up in a browser, because it uses some funky Unicode characters. It's good to use some oddball characters so that you can distinguish a tab from something you may have typed yourself. In addition to showing tabs, showing spaces at the end of lines is useful so you know to remove them (they are annoying).
Many others have mentioned the 'listchars' and 'list' options, but just to add another interesting alternative: ``` if &expandtab == 0 execute 'syn match MixedIndentationError display "^\([\t]*\)\@<=\( \{'.&ts.'}\)\+"' else execute 'syn match MixedIndentationError display "^\(\( \{' . &ts . '}\)*\)\@<=\t\+"' endif hi link MixedIndentationError Error ``` This will look at the current setting of 'expandtab' (i.e. whether you've got hard tabs or spaces pretending to be tabs) and will highlight anything that would *look* like correct indentation but be of the wrong form. These are designed to work by looking at the tab stops, so tabs used for indentation followed by spaces used for simple alignment (not a multiple of 'tabstop') won't be highlighted as erroneous. Simpler options are available: if you just want to highlight any tabs in the wrong file in bright red (or whatever your Error colour is), you could do: ``` syn match TabShouldNotBeThereError display "\t" hi link TabShouldNotBeThereError Error ``` or if you want spaces at the start of a line to be considered an error, you could do: ``` syn match SpacesUsedForIndentationError display "^ +" hi link SpacesUsedForIndentationError Error ``` Just a few more thoughts to add to the mix... more information here: ``` :help 'expandtab' :help 'tabstop' :help 'listchars' :help 'list' :help :exe :help let-option :help :hi-link :help :syn-match :help :syn-display ```
Making tabulation look different than just whitespace
[ "", "python", "vim", "" ]
I am creating a SQL Server Replication using a script. When I try to execute `The job failed. Unable to determine if the owner (STAR\moorer7) of job L3BPT2M-Atlas-14 has server access (reason: Could not obtain information about Windows NT group/user 'STAR\moorer7', error code 0x5. [SQLSTATE 42000] (Error 15404)).` This is a job created by a script that defines replication. How do I debug this?
Active Directory is refusing access to your SQL Agent. The Agent should be running under an account that is recognized by STAR domain controller.
For me, the jobs were running under DOMAIN\Administrator and failing with the error message `"The job failed. Unable to determine if the owner (DOMAIN\administrator) of job Agent history clean up: distribution has server access (reason: Could not obtain information about Windows NT group/user 'DOMAIN\administrator', error code 0x5. [SQLSTATE 42000] (Error 15404)).` To fix this, **I changed the owner of each failing job to `sa`.** Worked flawlessly after that. The jobs were related to replication cleanup, but I'm unsure if they were manually added or were added as a part of the replication set-up - I wasn't involved with it, so I am not sure.
Could not obtain information about Windows NT group user
[ "", "sql", "sql-server", "replication", "sql-server-agent", "" ]
I was just looking at an example, and in it I saw the code ``` return new IntPtr(handle); ``` After poking around our code, I found that we have already used a similar pattern, but in our code we had almost the same thing: ``` return (IntPtr)handle; ``` Is there a difference between those two takes? Will the second one be "better" in any way, since it doesn't allocate new memory, or is the cast just hiding the same constructor underneath?
In your examples, I'm guessing handle is an integer value? IntPtr declares an explicit conversion from Int32 (int) and Int64 (long) which simply calls the same constructor: ``` public static explicit operator IntPtr(int value) { return new IntPtr(value); } ``` So there is effectively no difference other than possible readability concerns.
[Reflector](http://www.red-gate.com/products/reflector/) says that the cast is calling the constructor under the hood anyway: ``` [Serializable, StructLayout(LayoutKind.Sequential), ComVisible(true)] public struct IntPtr : ISerializable { ... [ReliabilityContract(Consistency.MayCorruptInstance, Cer.MayFail)] public static explicit operator IntPtr(int value) { return new IntPtr(value); } } ```
IntPtr cast vs. new
[ "", "c#", "intptr", "" ]
Below query is not returning any rows into the listbox.There is no error message: ``` lstDiff.RowSource = "select TestScenario,TestId from tblTesting where empid= '" & Me.txtEmpId.Value & "' and testid= '" & Me.txtAutoNumber.Value & "'" ``` Could anyone help?
Personally, whenever I use SQL statements in code, I prefer to store the statement in a variable. While testing, on the line after you assign your statement to a variable, you can use Debug.Print to see what your SQL statement looks like after parsing your txtempid and txtautonumber. It would look something like this. ``` Dim sSQL as String sSQL = "select TestScenario,TestId from tblTesting where empid= '" & Me.txtEmpId.Value & "' and testid= '" & Me.txtAutoNumber.Value & "'" Debug.Print sSQL lstDiff.RowSource = sSQL ``` Then as long as your immediate window is visible (Ctrl-G), you can see what your SQL statement really is. If it looks right in the immediate window, copy and paste it into the query builder and run it there.
Your values in the field are numeric, so the extra single quotes aren't needed. Code should look like the following: ``` Me.lstDiff.RowSource = "select TestScenario,TestId from tblTesting where empid= " & Me.txtEmpId & " and testid= " & Me.txtAutoNumber & ";" ``` I've also dropped .Value from the field references, they're not harmful, but also aren't necessary. And I've added a semi-colon to the end of your statement. Depending on when/where you insert this code, you may need to add the following statement as well: ``` Me.lstDiff.Requery ```
VBA select not returning any rows
[ "", "sql", "ms-access", "vba", "syntax", "" ]
Coming from Access, I am totally unfamiliar with building a GUI or even a program. For C# application building, can someone point me to a primer or tutorial that will explain to me how to build a GUI, and what frameworks, widgets, Winforms, WPF, and everything else *are* and how they fit together to result in a usable program? Thank you.
There's a nice [tutorial of David Bolton](http://cplus.about.com/od/learnc/ss/random_2.htm).
If you want to learn WPF instead of WinForms, you can try the [WPF tutorial of Christian Moser](http://www.wpftutorial.net/).
C# GUI primer tutorial
[ "", "c#", "user-interface", "" ]
According to C++'03 Standard 2.3/1: > Before any other processing takes place, each occurrence of one of the following sequences of three characters (“trigraph sequences”) is replaced by the single character indicated in Table 1. > > ``` > ---------------------------------------------------------------------------- > | trigraph | replacement | trigraph | replacement | trigraph | replacement | > ---------------------------------------------------------------------------- > | ??= | # | ??( | [ | ??< | { | > | ??/ | \ | ??) | ] | ??> | } | > | ??’ | ˆ | ??! | | | ??- | ˜ | > ---------------------------------------------------------------------------- > ``` In real life that means that code `printf( "What??!\n" );` will result in printing `What|` because `??!` is a trigraph sequence that is replaced with the `|` character. **My question is what purpose of using trigraphs?** Is there any practical advantage of using trigraphs? **UPD**: In answers was mentioned that some European keyboards don't have all the punctuation characters, so non-US programmers have to use trigraphs in everyday life? **UPD2**: Visual Studio 2010 has trigraph support turned off by default.
[This question (about the closely related digraphs)](https://stackoverflow.com/questions/432443/why-are-there-digraphs-in-c-and-c) has the answer. It boils down to the fact that the ISO 646 character set doesn't have all the characters of the C syntax, so there are some systems with keyboards and displays that can't deal with the characters (though I imagine that these are quite rare nowadays). In general, you don't need to use them, but you need to know about them for exactly the problem you ran into. Trigraphs are the reason the the '`?`' character has an escape sequence: ``` '\?' ``` So a couple ways you can avoid your example problem are: ``` printf( "What?\?!\n" ); printf( "What?" "?!\n" ); ``` But you have to remember when you're typing the two '?' characters that you might be starting a trigraph (and it's certainly never something I'm thinking about). In practice, trigraphs and digraphs are something I don't worry about at all on a day-to-day basis. But you should be aware of them because once every couple years you'll run into a bug related to them (and you'll spend the rest of the day cursing their existance). It would be nice if compilers could be configured to warn (or error) when it comes across a trigraph or digraph, so I could know I've got something I should knowingly deal with. And just for completeness, digraphs are much less dangerous since they get processed as tokens, so a digraph inside a string literal won't get interpreted as a digraph. For a nice education on various fun with punctuation in C/C++ programs (including a trigraph bug that would defintinely have me pulling my hair out), take a look at [Herb Sutter's GOTW #86 article](http://www.gotw.ca/gotw/086.htm). --- Addendum: It looks like GCC will not process (and will warn about) trigraphs by default. Some other compilers have options to turn off trigraph support (IBM's for example). Microsoft started supporting a warning (C4837) in VS2008 that must be explicitly enabled (using -Wall or something).
Kids today! :-) Yes, foreign equipment, such as an IBM 3270 terminal. The 3270 has, if I remember, no curly braces! If you wanted to write C on an IBM mini / mainframe, you *had to* use the wretched trigraphs for every block boundary. Fortunately, I only had to write software in C to *emulate* some IBM minicomputer facilities, not actually write C software *on* the System/36. Look next to the "P" key: [![keyboard](https://i.stack.imgur.com/P9kSu.jpg)](https://i.stack.imgur.com/P9kSu.jpg) Hmmm. Hard to tell. There is an extra button next to "carriage return", and I might have it backwards: maybe it was the "[" / "]" pair that was missing. At any rate, this keyboard would cause you grief if you had to write C. Also, these terminals display EBCDIC, IBM's "native" mainframe character set, not ASCII (thanks, Pavel Minaev, for the reminder). On the other hand, like the GNU C guide says: "You don't need this brain damage." The gcc compiler leaves this "feature" disabled by default.
Purpose of Trigraph sequences in C++?
[ "", "c++", "c++03", "trigraphs", "" ]
I'm new to the whole JavaScript and jQuery coding but I'm currently doing this is my HTML: ``` <a id="tog_table0" href="javascript:toggle_table('#tog_table0', '#hideable_table0');">show</a> ``` And then I have some slightly ponderous code to tweak the element: ``` function toggle_table(button_id, table_id) { // Find the elements we need var table = $(table_id); var button = $(button_id); // Toggle the table table.slideToggle("slow", function () { if ($(this).is(":hidden")) { button.text("show"); } else { button.text("hide"); } }); } ``` I'm mainly wondering if there is a neater way to reference the source element rather than having to pass two IDs down to my function?
Use 'this' inside the event. Typically in jQuery this refers to the element that invoked the handler. Also try and avoid inline script event handlers in tags. it is better to hook those events up in document ready. **NB** The code below assumes the element invoking the handler (the link) is inside the table so it can traverse to it using closest. This may not be the case and you may need to use one of the other traversing options depending on your markup. ``` $(function(){ $('#tog_table0').click( toggle_table ) }); function toggle_table() { //this refers to the element clicked var $el = $(this); // get the table - assuming the element is inside the table var $table = $el.closest('table'); // Toggle the table $table.slideToggle("slow", function () { $el.is(":hidden") ? $el.text("show") : $el.text("hide"); } } ```
You can do this: ``` <a href="" name="#hideable_table0" class="tableHider">show</a> ``` and change your javascript to this: ``` $('a.tableHider').click(function() { var table = $(this.name); // this refers to the link which was clicked var button = $(this); table.slideToggle("slow", function() { if ($(this).is(':hidden')) { // this refers to the element being animated button.html('show'); } else { button.html('hide'); } }); return false; }); ``` edit: changed script to use the name attribute and added a return false to the click handler.
Is there an easier way to reference the source element for an event?
[ "", "javascript", "jquery", "html", "events", "dom", "" ]
What is the point (if any) in having a table in a database with only one row? Note: I'm not talking about the possibility of having only one row in a table, but when a developer deliberately makes a table that is intended to always have exactly one row. **Edit:** The sales tax example is a good one. I've just observed in some code I'm reviewing three different tables that contain three different kinds of certificates (a la SSL), each having exactly one row. I don't understand why this isn't made into one large table; I assume I'm missing something.
I've seen something like this when a developer was asked to create a configuration table to store name-value pairs of data that needs to persist without being changed often. He ended up creating a one-row table with a column for each configuration variable. I wouldn't say it's a good idea, but I can certainly see why the developer did it given his instructions. Needless to say it didn't pass review. > I've just observed in some code I'm reviewing three different tables that contain three different kinds of certificates (a la SSL), each having exactly one row. I don't understand why this isn't made into one row; I assume I'm missing something. This doesn't sound like good design, unless there are some important details you don't know about. If there are three pieces of information that have the same constraints, the same use and the same structure, they should be stored in the same table, 99% of the time. That's a big part of what tables are for fundamentally.
It's not necessarily a bad idea. What if you had some global state (say, a boolean) that you wanted to store somewhere? And you wanted your stored procedures to easily access this state? You could create a table with a primary key whose value range was limited to exactly one value.
SQL table with a single row?
[ "", "sql", "schema", "" ]
I saw [this post](https://stackoverflow.com/questions/398425/maintaining-sort-order-of-database-table-rows) but didn't understand if this was the same issue. My database can be sorted on each column. Once the db is sorted, how do I maintain that order after my next query? For example: Order db by age: sprintf(sql, "select \* from Customer\_Table ORDER BY age\_ID LIMIT 100 OFFSET %s;", offset); then the user looks at the next 100 customers sprintf(sql, "select \* from Customer\_Table LIMIT 100 OFFSET %s;", offset); //next offset The returned data is no longer ordered by age. How would I keep the last sort throughout the next query? Do I have to pass in a variable to maintain state or does the database have some function for recalling it's last state?
Other than selecting the records into a temporary table, then selecting from that table, you would have to specify the ORDER BY in each query. The server does not retain any kind of state in regard to the previous query. Why is it a problem to re-specify the ORDER BY clause in subsequent queries? Whether you use a temporary table or re-specify the entire query is a matter of how your application is structured.
You have to specify the ORDER BY clause at each request. The way this is optimized by your database system doesn't concern your client code.
Maintain SQL sort state throughout next query?
[ "", "sql", "c", "" ]
I have a page with 2 forms and a hidden field that is outside of both of the forms. How can the hidden field be submitted with either of the forms? I thought about doing something like this with jQuery: ``` <script type="text/javascript"> $(function() { $('form').submit(function() { // do something to move or copy the // hidden field to the submitting form }); }); </script> ``` Will this work? Any other ideas? # EDIT The hidden field stores a serialized object graph that doesn't change. Both server methods require the object. The serialized object string can get pretty hefty, so I don't want this thing sent down from the server 2 times.
You can simply inject a copy of the element into each form right before submission. This way, you can have the option of having different information for each hidden form field without affecting the other. --- Something like this: ``` <script type="text/javascript"> $(function() { $('form').submit(function() { $("#hidden_element").clone().appendTo(this); }); }); </script> ``` If you want to use the exact same element for both forms without creating a fresh copy, just don't use `clone()` --- See documentation for [clone()](http://docs.jquery.com/Manipulation/clone) and for [appendTo()](http://docs.jquery.com/Manipulation/appendTo#selector) # EDIT: If you don't want to send the hidden element with every request the form sends. Consider storing it in the database for that user for that time. You can submit its content once, and once only for every page reload, and then just send the database id of the hidden element with each form post. On page load, something like this: ``` $.post("page.php", { reallyBigObject : $("#hiddenfield").val() }, function(insertedID){ $("#hiddenfield").val(insertedID); }); ``` Then, in the server side code: ``` //insert $_POST["reallyBigObject"] into databse //get the just inserted id (in php it's done with mysql_insert_id()) //echo, or print the just inserted id, and exit ``` This way your js gets the callback. Now, you can submit the form as you would, but this time, you're only sending the id (integer number) to the server. You can then simply delete the object from your server (run a cron to do it after X amount of time, or send another request to delete it. Honestly, though, unless you object is HUGE(!!), I think storing it by submitting it only once is a lot more complex to execute than to simply send two requests to the server. Let me know if you have any other questions...
With HTML5, you can include a "form" attribute with an input element. The value of the form attribute is the id of the form(s) the field belongs to. To include the field in more than one form, include all form ids in a space-delimited list. Unfortunately, the form attribute is not supported in IE at all (as of IE 9). FF and Chrome support start in version 4 and 10 respectively.
How can 2 Html forms share 1 hidden field?
[ "", "javascript", "jquery", "html", "forms", "hidden-field", "" ]
I'm using WPF and C#. I want to be able to launch a browser window, most likely IE, and provide known credentials so that the Windows-based application can handle the transition from itself to an outside browser without having the user enter his/her credentials again. I do know how to launch the browser: ``` System.Diagnostics.Process.Start(url); ``` My main question is, how can I attach authentication to that? Perhaps by adding headers to it somehow? Lastly, I don't really want to use the new WebBrowser control inside of WPF due to it's current problems with displaying with a transparent window.
1) You have to know how to "log in". To do this login manually in the web application and trace the http traffic with http debugger like Fiddler. Pay attention what kind of http requests are sent, what names have the parameters, etc. Once you know what sequence of http requests has to be send to log in you has to do this with the browser. 2) Implement log in automatically 2.1) If by any chance log in happens via http GET - just append the right query string to the url and start the browser. This could happen only if you control the web application and build in this mechanism, other wise log in is almost always implemented as POST with https. 2.2) If you have to do POST request you have several options: 2.2.1) You could provide local html document, that contains javascript and make ajax call to the login form from the javascript. To pass the parameters you could use get parameters. 2.2.2) If nothing else works you will have to use the browser via COM (WebBrowser control)
It's going to depend on how the web site handles user authentication. If you own the website, you can create a url that will log the user in with the information you provide.
WPF Launch Browser with Credentials
[ "", "c#", "wpf", "browser", "" ]
How can i use the server.mappath method in a C# class library class ,which acts as my BusinessLayer for My ASP.NET WEbsite
By calling it? ``` var path = System.Web.HttpContext.Current.Server.MapPath("default.aspx"); ``` Make sure you add a reference to the System.Web assembly.
You can get the base path by using the following code and append your needed path with that. ``` string path = System.AppDomain.CurrentDomain.BaseDirectory; ```
Server.Mappath in C# classlibrary
[ "", "c#", "server.mappath", "" ]
Currently I'm wondering if there is a way to post to a website using captcha for a human-check. The following question is asked, ofcourse this is done with random numbers: ``` Type this number in digits; 'twohundredandfive': [ input ] ``` The form is sent using AJAX. So when reloading the website the number to be typed changes. A way to get pass this is reading and converting the number, then post some data, but at the second request the number already has been changed (which is good). But IS there a way to avoid this? Don't think I'm using this for bad intensions, the described form is used in one of my applications. It is just a check to get sure bots can't get pass. Thanks so far :-)
A [CAPTCHA](http://en.wikipedia.org/wiki/CAPTCHA) should test whether the entity solving it is human. To my eyes, the problem you are setting looks like it would be fairly trivial to solve algorithmically. Given that a human can pass the test, then it's certainly possible to write an automated bot which will pass it too. As to whether there is a "back door" which allows access without solving the CAPTCHA, only you can decide that by analysing your source code.
I hate CAPTCHAs. More often than not, they are unreadable to humans as well :) I heard one Microsoft researcher offer the following scheme: put 4 pictures up, 3 of little puppies, one with a kitten. Ask the user to click the kitten. With a large enough sample base, you can create a random picture/question any time the page refreshes. No one will bother developing an algorithm to analyze photos to that degree. read [this post](http://www.guyvider.com/2007/12/technological-digest-v.html) for another interesting idea.
Posting to website using captcha
[ "", "php", "ajax", "post", "captcha", "" ]
Say I have the following set of urls in a db ``` url data ^(.*)google.com/search foobar ^(.*)google.com/alerts barfoo ^(.*)blah.com/foo/(.*) foofoo ... 100's more ``` Given any url in the wild, I would like to check to see if that url belongs to an existing set of urls and get the corresponding data field. My questions are: 1. How would I design the db to do it 2. django does urlresolution by looping through each regex and checking for a match given that there maybe 1000's of urls is this the best way to approach this? 3. Are there any existing implementations I can look at?
The plan I'm leaning towards is one which picks of the domain name + tld from a url, uses that as a key to find out all the regexes and than loops through each of this regex subset to find a match. I use two tables for this ``` class Urlregex(db.Model): """ the data field is structured as a newline separated record list and each record is a space separated list of regex's and dispatch key. Example of one such record domain_tld: google.com data: ^(.*)google.com/search(.*) google-search """ domain_tld = db.StringProperty() data = db.TextProperty() class Urldispatch(db.Model): urlkey = db.StringProperty() data = db.TextProperty() ``` So, for the cost of 2 db reads and looping through a domain specific url subset any incoming url should be able to be matched against a large db of urls.
> "2. django does urlresolution by looping through each regex and checking for a match given that there maybe 1000's of urls is this the best way to approach this?" > > "3. Are there any existing implementations I can look at?" If running a large number of regular expressions does turn out to be a problem, you should check out [esmre](http://code.google.com/p/esmre/), which is a Python extension module for speeding up large collections of regular expressions. It works by extracting the fixed strings of each regular expression and putting them in an [Aho-Corasick](http://en.wikipedia.org/wiki/Aho-Corasick_algorithm)-inspired pattern matcher to quickly eliminate almost all of the work.
how would i design a db to contain a set of url regexes (python) that could be matched against an incoming url
[ "", "python", "regex", "url-routing", "" ]
We have a python project that we want to start testing using buildbot. Its unit tests include tests that should only work on some platforms. So, we've got tests that should pass on all platforms, tests that should only run on 1 specific platform, tests that should pass on platforms A, B, C and tests that pass on B and D. What is the best way of doing this? Simple suites would be a hassle, since, as described, each test can have a different list of target platforms. I thought about adding "@run\_on" and "@ignore\_on" decorators that would match platforms to test methods. Is there anything better?
We've decided to go with decorators that, using platform module and others, check whether the tests should be executed, and if not simply let it pass (though, we saw that python2.7 already has in its trunk a SkipTest exception that could be raised in such cases, to ignore the test).
On a couple of occasions I have used this very simple approach in test modules: ``` import sys import unittest if 'win' in sys.platform: class TestIt(unittest.TestCase): ... if 'linux' in sys.platform: class TestIt(unittest.TestCase): ... ```
How to distribute and execute platform-specific unit tests?
[ "", "python", "unit-testing", "buildbot", "" ]
``` // Get the image information and display the image: if ($image = @getimagesize ("../uploads/$pid")) { echo "<div align=\"center\"><img src=\"show_image.php?image=$pid&name=" . urlencode($row['image_name']) . "\" $image[3] alt=\"{$row['print_name']}\" /></div>\n"; } else { echo "<div align=\"center\">No image available.</div>\n"; } ``` What does @ do in @getimagesize?
It stops errors from being displayed and/or being logged from that specific function call.
It is an [Error Control Operator](http://www.php.net/manual/en/language.operators.errorcontrol.php), that will mask (prevent from being displayed) any error the `getimagesize` function could generate. It it generally not considered a good practice to use it : it makes your code really harder to debug *(if there is an error, you won't know about it)* : > Currently the "@" error-control > operator prefix will even disable > error reporting for critical errors > that will terminate script execution. > Among other things, this means that if > you use "@" to suppress errors from a > certain function and either it isn't > available or has been mistyped, the > script will die right there with no > indication as to why. There is even a PHP extension, called [scream](http://pecl.php.net/package/scream), that disables this operator -- can be pretty useful when you are maintaintaing an apllication that used this operator a lot... Generally, it is better to set [`error_reporting`](https://www.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting) ([see also](http://php.net/manual/en/function.error-reporting.php)) level and [`display_errors`](https://www.php.net/manual/en/errorfunc.configuration.php#ini.display-errors) so that errors are displayed in development, and not in production -- that's way more useful that just always hiding them !
What does @ do in this php?
[ "", "php", "" ]
I have a simple C# foreach loop, how can I break out of the loop when a button is pressed? It is not in a backgroundWorker thread so I can't use backgroundWorker.CancellationPending.
Create a boolean flag in the form. Attach an event handler to the buttons click event and set the flag to true in the event handler. Check for the flag in the loop and if it's true, call "break". (A better option would be to use a while loop instead of a for loop with the check of the flag in the while condition) Obviously the for loop will need to be on some form of background thread otherwise the GUI won't be responsive. If you don't know how to do this, check out either [ThreadPool.QueueUserWorkItem](http://msdn.microsoft.com/en-us/library/system.threading.threadpool.queueuserworkitem.aspx) or the [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx). If you do use a BackgroundWorker you can use the inbuilt CancelAsync() method instead of coding your own cancel flag. **[Edit: As pointed out by others (below) and discussed in more depth [here](https://stackoverflow.com/questions/1222184/do-i-need-to-lock-or-mark-as-volatile-when-accessing-a-simple-boolean-flag-in-c) and [here](https://stackoverflow.com/questions/458173/can-a-c-thread-really-cache-a-value-and-ignore-changes-to-that-value-on-other-th/458193#458193); you do need to either lock before accessing the bool or mark it as volatile]** [Don't forget to set the correct state of the flag before you start the loop.]
Here is a not-so-good solution. Call `Application.DoEvents()` in every iteration your loop. On Button-Click set a variable to True and in loop check that variable. If it is true, break otherwise continue. As I said, this is not a very good solution. `Application.DoEvents()` can be very dangerous. The best option here to do is to have a background thread.
C# Break out of loop on button press
[ "", "c#", "foreach", "" ]
I'm wanting to assign a variable only it hasn't already been assigned. What's the PHP way of doing the following? ``` $result = null; $result ||= check1(); $result ||= check2(); $result ||= "default"; ``` I checked the [standard operators](https://www.php.net/manual/en/language.operators.php) and the [is\_null](https://www.php.net/is_null) function, but there doesn't seem to be an easy way of doing the above operation.
[`isset()`](https://www.php.net/isset) is the usual way of doing this: ``` if (!isset($blah)) { $blah = 'foo'; } ``` **Note:** you can assign `null` to a variable and it will be assigned. This will yield different results with `isset()` and [`is_null()`](https://www.php.net/manual/en/function.is-null.php) so you need to be clear on what you mean by "not assigned". See [Null vs. isset()](http://brian.moonspot.net/null-isset-php). This is also one case where you need to be careful about doing automatic type conversion, meaning using the `!=/==` or `===/!==` depending on the desired result. You can use boolean shorthand for this too (which is what the Perl `||=` operator is). As of PHP 5.2.x there is no operator like you speak of. In Perl: ``` $a ||= $b; ``` is equivalent to: ``` $a = $a || $b; ``` You can do the second form in PHP but PHP has some funky rules about [type juggling](http://us.php.net/manual/en/language.types.type-juggling.php). See [Converting to boolean](http://us.php.net/manual/en/language.types.boolean.php#language.types.boolean.casting): > When converting to [boolean](http://us.php.net/manual/en/language.types.boolean.php), the > following values are considered FALSE: > > * the [boolean](http://us.php.net/manual/en/language.types.boolean.php) `FALSE` itself > * the [integer](http://us.php.net/manual/en/language.types.integer.php) 0 (zero) > * the [float](http://us.php.net/manual/en/language.types.float.php) 0.0 (zero) > * the empty [string](http://us.php.net/manual/en/language.types.string.php), and the [string](http://us.php.net/manual/en/language.types.string.php) "0" > * an [array](http://us.php.net/manual/en/language.types.array.php) with zero elements > * an [object](http://us.php.net/manual/en/language.types.object.php) with zero member variables (PHP 4 only) > * the special type [`NULL`](http://us.php.net/manual/en/language.types.null.php) (including unset variables) > * [SimpleXML](http://us.php.net/manual/en/ref.simplexml.php) objects created from empty tags > > Every other value is considered TRUE (including any resource). So after: ``` $a = 0; $a = $a || 5; ``` $a would equal 5. Likewise: ``` $a = 0; $b = ''; $c = $a == $b; // true $d = $a === $b; // false ``` You have to watch out for these things.
``` isset($foo) || $foo = 'bar'; ```
Does PHP have an equivalent to the ||= operator?
[ "", "php", "" ]
I have an app which calls another process in a command window and that process has updating stats that output to the console window. I thought this was a fairly simple operation but I can't seem to get it to work. Am I missing something? ``` string assemblyLocation = Assembly.GetExecutingAssembly().Location; Process process = new Process { ProcessStart = { RedirectStandardOutput = true, UseShellExecute = false, WindowStyle = ProcessWindowStyle.Hidden, Arguments = arg, FileName = assemblyLocation.Substring(0, assemblyLocation.LastIndexOf("\\")) + "\\ffmpeg.exe", CreateNoWindow = true } }; process.Start(); Console.WriteLine(process.StandardOutput.ReadToEnd()); process.WaitForExit(); ``` Ideally what I would like is as the output changes within that process I hit or data comes into the reader that I get events off it. Any help would be great, I feel like this is a newbie question but seem to be missing something.
I've experienced this before. Sometimes, the way in which the process you're calling outputs to the console is not compatible with this sort of output redirection. I've been fortunate enough in this case to be able to modify the external process to get around this. You might try running your code on another process that outputs to the console, and see if it works properly. It reads about right to me right now. EDIT: I went and pulled a code block I've used to do this. This is in a WPF app which redirects the process output to the window. Notice the event binding. Since this is WPF I have to invoke my call to write the data out. Since you aren't worried about blocking, ou should be able to simply replace that with: ``` Console.WriteLine(e.Data); ``` Hopefully it helps! ``` private static void LaunchProcess() { Process build = new Process(); build.StartInfo.WorkingDirectory = @"dir"; build.StartInfo.Arguments = ""; build.StartInfo.FileName = "my.exe"; build.StartInfo.UseShellExecute = false; build.StartInfo.RedirectStandardOutput = true; build.StartInfo.RedirectStandardError = true; build.StartInfo.CreateNoWindow = true; build.ErrorDataReceived += build_ErrorDataReceived; build.OutputDataReceived += build_ErrorDataReceived; build.EnableRaisingEvents = true; build.Start(); build.BeginOutputReadLine(); build.BeginErrorReadLine(); build.WaitForExit(); } // write out info to the display window static void build_ErrorDataReceived(object sender, DataReceivedEventArgs e) { string strMessage = e.Data; if (richTextBox != null && !String.Empty(strMessage)) { App.Instance.Dispatcher.BeginInvoke(DispatcherPriority.Send, (ThreadStart)delegate() { Paragraph para = new Paragraph(new Run(strMessage)); para.Margin = new Thickness(0); para.Background = brushErrorBrush; box.Document.Blocks.Add(para); }); } } ```
I'm not sure exactly what problem you're running into, but if you're looking to act on output as soon as it's generated, try hooking into the process's `OutputDataReceived` event. You can specify handlers to receive output asynchronously from the process. I've used this approach successfully. ``` Process p = new Process(); ProcessStartInfo info = p.info; info.UseShellExecute = false; info.RedirectStandardOutput = true; info.RedirectStandardError = true; p.OutputDataReceived += p_OutputDataReceived; p.ErrorDataReceived += p_ErrorDataReceived; p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); p.WaitForExit(); ``` .. ``` void p_OutputDataReceived(object sender, DataReceivedEventArgs e) { Console.WriteLine("Received from standard out: " + e.Data); } void p_ErrorDataReceived(object sender, DataReceivedEventArgs e) { Console.WriteLine("Received from standard error: " + e.Data); } ``` See the [OutputDataReceived](http://msdn.microsoft.com/en-us/library/system.diagnostics.process.outputdatareceived.aspx) event off Process for more information.
ProcessInfo and RedirectStandardOutput
[ "", "c#", ".net", "redirectstandardoutput", "startprocessinfo", "" ]
``` <?PHP $bannedIPs = array('127.0.0.1','72.189.218.85'); function ipban() { if (in_array($_SERVER['REMOTE_ADDR'], $bannedIPs)) { echo 'test'; } } ipban(); ?> ``` The output of this script is: > Warning: in\_array() [function.in-array]: Wrong datatype for second > argument in C:\webserver\htdocs\test\array.php on line 93 Can someone tell me why? I don't get it And yes `$_SERVER['REMOTE_ADDR']` is displaying 127.0.0.1 ***UPDATE*** As suggested I tried this now but still get the same error ``` function ipban() { $bannedIPs = array('127.0.0.1','72.189.218.85'); if (in_array($_SERVER['REMOTE_ADDR'], $bannedIPs)) { echo 'test'; } } ipban(); ```
You have run into a little problem with your variable scoping. Any variables outside a function in PHP is not accessible inside. There are multiple ways to overcome this. You could either declare `$bannedIPs` inside your function as such: ``` function ipban() { $bannedIPs = array('127.0.0.1','72.189.218.85'); if (in_array($_SERVER['REMOTE_ADDR'], $bannedIPs)) { echo 'test'; } } ``` Tell your function to access `$bannedIPs` outside the function using the **`global`** keyword: ``` $bannedIPs = array('127.0.0.1','72.189.218.85'); function ipban() { global $bannedIPs; if (in_array($_SERVER['REMOTE_ADDR'], $bannedIPs)) { echo 'test'; } } ``` Or, use the `$GLOBALS` super global: ``` $bannedIPs = array('127.0.0.1','72.189.218.85'); function ipban() { if (in_array($_SERVER['REMOTE_ADDR'], $GLOBALS['bannedIPs'])) { echo 'test'; } } ``` I recommend you read the manual page on Variable scope: [PHP: Variable Scope](http://www.php.net/manual/en/language.variables.scope.php) --- **If it's still not working, you have another problem in your code. In which case, you might want to consider using a `var_dump()` to check what datatype is `$bannedIPs` before down voting us all.** ``` function ipban() { global $bannedIPs; var_dump($bannedIPs); } ```
Your variable `$bannedIPs` is out-of-scope inside the function. Read up on variables scope: <http://php.net/variables.scope> ``` $var = 'xyz'; function abc() { // $var does not exist here $foo = 'abc'; } // $var exists here // $foo does not exist here ``` RE: Update: Moving the variable inside the function works, your code snippet executes fine. There's got to be something else in your code.
php in array error
[ "", "php", "arrays", "" ]
If I return nothing explicitly, what does a php function exactly return? ``` function foo() {} ``` 1. What type is it? 2. What value is it? 3. How do I test for it exactly with === ? 4. Did this change from php4 to php5? 5. Is there a difference between `function foo() {}` and `function foo() { return; }` (I am not asking how to test it like `if (foo() !=0) ...`)
1. `null` 2. `null` 3. `if(foo() === null)` 4. - 5. Nope. You can try it out by doing: ``` $x = foo(); var_dump($x); ```
Not returning a value from a PHP function has the same semantics as a function which returns null. ``` function foo() {} $x=foo(); echo gettype($x)."\n"; echo isset($x)?"true\n":"false\n"; echo is_null($x)?"true\n":"false\n"; ``` This will output ``` NULL false true ``` You get the same result if foo is replaced with ``` function foo() {return null;} ``` There has been no change in this behaviour from php4 to php5 to php7 (I just [tested](https://3v4l.org/UHCMA#tabs) to be sure!)
What does a PHP function return by default?
[ "", "php", "function", "variables", "language-design", "" ]
I have a library of different words/phrases, and in order to build sentences at present I add a combination of these phrases into a playlist to make a sentence. Unfortunately if the user is running CPU intensive applications (which most of my users are) there can be a lag of a few seconds mid-sentence (in between phrases). In order to combat this I was thinking of an approach which will merge the right combination of MP3 files on the fly into an appropriate phrase, save this in the %temp% directory, and then play this 1 MP3 file which should overcome the problem I'm experiencing with gaps. What is the easiest way to do this in C#? Is there an easy way to do this? The files are fairly small, 3-4 seconds long each, and a sentence can consist of 3-20ish phrases.
MP3 files consist of "frames", that each represent a short snippet (I think around 25 ms) of audio. So yes, you *can* just concatenate them without a problem.
here's how you can concatenate MP3 files using [NAudio](http://naudio.codeplex.com): ``` public static void Combine(string[] inputFiles, Stream output) { foreach (string file in inputFiles) { Mp3FileReader reader = new Mp3FileReader(file); if ((output.Position == 0) && (reader.Id3v2Tag != null)) { output.Write(reader.Id3v2Tag.RawData, 0, reader.Id3v2Tag.RawData.Length); } Mp3Frame frame; while ((frame = reader.ReadNextFrame()) != null) { output.Write(frame.RawData, 0, frame.RawData.Length); } } } ``` see [here](http://mark-dot-net.blogspot.com/2010/11/merging-mp3-files-with-naudio-in-c-and.html) for more info
How do I merge/join MP3 files with C#?
[ "", "c#", "join", "merge", "mp3", "" ]
Using Python I want to create a property in a class, but having the name of it in a string. Normally you do: ``` blah = property(get_blah, set_blah, del_blah, "bleh blih") ``` where get\_, set\_ and del\_blah have been defined accordingly. I've tried to do the same with the name of the property in a variable, like this: ``` setattr(self, "blah", property(self.get_blah, self.set_blah, self.del_blah, "bleh blih")) ``` But that doesn't work. The first case blah returns the value of the property, on the second case, it returns a property, that is `<property object at 0xbb1aa0>`. How should I define it so it works?
As much I would say, the difference is, that in the first version, you change the classes attribute blah to the result of property and in the second you set it at the instance (which is different!). How about this version: ``` setattr(MyClass, "blah", property(self.get_blah, self.set_blah, self.del_blah, "bleh blih")) ``` you can also do this: ``` setattr(type(self), "blah", property(self.get_blah, self.set_blah, self.del_blah, "bleh blih")) ```
One way is to write into locals(): ``` class X: for attr in ["a","b","c"]: def getter(self, name=attr): return name+"_value" locals()[attr] = property(getter, None, None, attr) x = X() print x.a print x.b print x.c ``` gives ``` a_value b_value c_value ```
How to create a property with its name in a string?
[ "", "python", "properties", "setattr", "" ]
I have trouble understanding the underlying errors with the code below: ``` class myClass { public void print(string mess) { Console.WriteLine(mess); } } class myOtherClass { public static void print(string mess) { Console.WriteLine(mess); } } public static class Test { public static void Main() { myClass mc = new myClass(); mc.print("hello"); myOtherClass moc = new myOtherClass(); moc.print("vhhhat?"); //This says I can't access static method in non static context, but am I not? } } ``` I can't ever think of a reason why one would declare a static method in a non-static class, so why will .NET not throw an exception error. Furthermore, ``` moc.print("vhhhat?"); ``` This will say I can't access static method in non static context but Test and main are static, what is it referring to ?
A static class means that you cannot use it in a non-static context, meaning that you cannot have an object instantiation of that class and call the method. If you wanted to use your print method you would have to do: ``` myOtherClass.print("vhhhat?"); ``` This is not static, as you created an instantiation of the class called `moc`: ``` myOtherClass moc = new myOtherClass(); ```
First, the error: ``` moc.print("vhhhat?"); ``` Is trying to call a static method on an instance of the class (i.e. a non-static context). To properly call print(), you would do ``` myOtherClass.print("vhhhat?"); ``` For the first question, there are many reasons to have static methods in a non-static class. Basically, if there is an operation associated with the class, but not with any particular instance of the class, it should be a static method. For example, String.Format() (or any of the String static methods) should not operate on string instances, but they should be associated with the String class. Therefore they are static.
What is the point of a static method in a non-static class?
[ "", "c#", "static", "scope", "" ]
Ok, so my PHP is, to say the least, horrible. I inherited an application and am having to fix errors in it from someone that wrote it over 7 years ago. When I run the page, there is no return, so I checked the logs to see the error and here is what i get: > PHP Parse error: syntax error, unexpected '=', expecting ',' or ';' in /httpdocs/cron123/purge.php on line 4 Here is the code: ``` <? ob_start(); global $siteRoot = '/httpdocs/'; global $reportRoot = '/reports/'; include('billing1.php'); $date='Purge report for: ' .date('M d, Y \a\t g:i a'); ?> <html> <head><title><?=$date?></title></head> <body> <?php $account = new billing(); $ftresult = $account->purge(); new dBug($ftresult); echo "successfully wrote"; ?> </body> <? $filename = "purge_report_" . date('y.m.d_\a\t_g_i_a') . ".html"; $loc = $reportRoot . 'purge_reports/'; $f = $loc . $filename; $fp = @fopen($f, 'w'); @fwrite($fp, ob_get_contents()); @fclose($fp); ob_end_flush(); ?> ```
[`global`](http://nl2.php.net/global) is a keyword that should be used by itself. It must not be combined with an assignment. So, chop it: ``` global $x; $x = 42; ``` Also, as [Zenham](https://stackoverflow.com/questions/1145970/php-syntax-error-in-setting-global-variable/1145985#1145985) mentions, `global` is used inside functions, to access variables in an outer scope. So the use of `global` as it is presented makes little sense. Another tip (though it will not really help you with syntax errors): add the following line to the top of the main file, to help debugging ([documentation](http://nl2.php.net/manual/en/errorfunc.configuration.php#ini.error-reporting)): ``` error_reporting(E_ALL); ```
The **global** keyword is used inside of functions to declare that they will use a globally defined variable, not to define one. Just remove the word **global**, and if you need those values in functions, add: ``` global $a; ``` ...to the start to the function.
PHP Syntax Error in Setting Global Variable
[ "", "php", "syntax", "global-variables", "" ]
Is there a way to empty an array and if so possibly with `.remove()`? For instance, ``` A = [1,2,3,4]; ``` How can I empty that?
Ways to clear an existing array `A`: **Method 1** (this was my original answer to the question) ``` A = []; ``` This code will set the variable `A` to a new empty array. This is perfect if you don't have **references to the original array `A`** anywhere else because this actually creates a brand new (empty) array. You should be careful with this method because if you have referenced this array from another variable or property, the original array will remain unchanged. Only use this if you only reference the array by its original variable `A`. This is also the fastest solution. This code sample shows the issue you can encounter when using this method: ``` var arr1 = ['a','b','c','d','e','f']; var arr2 = arr1; // Reference arr1 by another variable arr1 = []; console.log(arr2); // Output ['a','b','c','d','e','f'] ``` **Method 2** (as [suggested](https://stackoverflow.com/a/1234337/113570) by [Matthew Crumley](https://stackoverflow.com/users/2214/matthew-crumley)) ``` A.length = 0 ``` This will [clear the existing array](https://tc39.es/ecma262/multipage/ordinary-and-exotic-objects-behaviours.html#sec-arraysetlength) by setting its length to 0. It also works when using "strict mode" in ECMAScript 5 because the length property of an array is a read/write property. **Method 3** (as [suggested](https://stackoverflow.com/a/8134354/113570) by [Anthony](https://stackoverflow.com/users/1047275/anthony)) ``` A.splice(0,A.length) ``` Using `.splice()` will work perfectly, but since the `.splice()` function will return an array with all the removed items, it will actually return a copy of the original array. Benchmarks suggest that this has no effect on performance whatsoever. **Method 4** (as [suggested](https://stackoverflow.com/a/17306971/113570) by [tanguy\_k](https://stackoverflow.com/users/990356/tanguy-k)) ``` while(A.length > 0) { A.pop(); } ``` This solution is not very succinct, and it is also the slowest solution, contrary to earlier benchmarks referenced in the original answer. **Performance** Of all the methods of clearing an ***existing array***, methods 2 and 3 are very similar in performance and are a lot faster than method 4. See this [benchmark](http://jsben.ch/#/hyj65). As pointed out by [Diadistis](https://stackoverflow.com/users/47401/diadistis) in their [answer](https://stackoverflow.com/a/28548360/113570) below, the original benchmarks that were used to determine the performance of the four methods described above were flawed. The original benchmark reused the cleared array so the second iteration was clearing an array that was already empty. The following benchmark fixes this flaw: <http://jsben.ch/#/hyj65>. It clearly shows that methods #2 (length property) and #3 (splice) are the fastest (not counting method #1 which doesn't change the original array). --- This has been a hot topic and the cause of a lot of controversy. There are actually many correct answers and because this answer has been marked as the accepted answer for a very long time, I will include all of the methods here.
If you need to keep the original array because you have other references to it that should be updated too, you can clear it without creating a new array by setting its length to zero: ``` A.length = 0; ```
How do I empty an array in JavaScript?
[ "", "javascript", "arrays", "" ]
Say I have an `$input` array, that contains something like this : ``` array 0 => string 'a' (length=1) 1 => string 'b' (length=1) 2 => string 'c' (length=1) 3 => string 'd' (length=1) 4 => string 'e' (length=1) 5 => string 'f' (length=1) 6 => string 'g' (length=1) 7 => string 'h' (length=1) 8 => string 'i' (length=1) 9 => string 'j' (length=1) ``` I want to get an `$output` array, that would contain this : ``` array 0 => string 'a' (length=1) 1 => string 'c' (length=1) 2 => string 'e' (length=1) 3 => string 'g' (length=1) 4 => string 'i' (length=1) ``` The `$output` array contains half the values that were in `$input` ; those that had even numbered keys in the input; the first one is kept, second one is not, third one is, and so one... *(Note: the keys are not preserved ; only the values are important)* **How could I do that ? Keeping only one on two values of the array ?** --- I have already tried some ideas, and already have a couple different solutions : **First idea:** iterate over the input array, and copy the interesting values to the output array: ``` $input = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', ); $output = array(); $nbr = count($input); for ($i = 0 ; $i < $nbr ; $i += 2) { $output[] = $input[$i]; } var_dump(array_values($output)); ``` **Second idea:** iterate over the array, and `unset` what I don't want to keep: ``` $input = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', ); $output = $input; $nbr = count($input); for ($i = 1 ; $i < $nbr ; $i += 2) { unset($output[$i]); } var_dump(array_values($output)); ``` **Third idea:** use a combinaison of `array_flip`, `range`, `array_diff_key`, ... : ``` $input = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', ); $output = array(); $keys_to_exclude = array_flip(range(1, count($input)-1, 2)); $output = array_diff_key($input, $keys_to_exclude); var_dump(array_values($output)); ``` **Fourth idea:** about the same thing, but with `array_intersect_key`: ``` $input = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', ); $output = array(); $keys_to_include = array_flip(range(0, count($input)-1, 2)); $output = array_intersect_key($input, $keys_to_include); var_dump(array_values($output)); ``` Any other idea ? Even / particularly if it sounds kinda hacky or anything ? *My goal is not to get the most efficient nor simple syntax ; it's just for fun and because I am curious, actually ^^* *If the title is not using the right words to describe what I want, don't hesitate to tell ; or edit it* **:-)**
``` <?php $x = range('a', 'f'); $x = array_map('array_shift', array_chunk($x, 2) ); var_dump($x); ``` or another one ``` <?php class ArrayEvenIterator extends ArrayIterator { public function next() { parent::next(); return parent::next(); } } $x = range('a', 'f'); $x = iterator_to_array(new ArrayEvenIterator( $x ), false); var_dump($x); ``` or with a php 5.3 closure (which isn't better than global in this case ;-) ) ``` <?php $x = range('a', 'f'); $x = array_filter( $x, function($e) use(&$c) { return 0===$c++%2; }); var_dump($x); ```
Assuming numeric keys: ``` foreach ($array as $key => $value) { if ($key % 2 != 0) { unset($array[$key]); } } ``` --- **EDIT** Here goes my slightly more insane solution which keeps the index continuous without re-indexing. ;o) ``` foreach ($array as $key => $value) { if (!($key%2)) { $array[$key/2] = $value; } } $array = array_slice($array, 0, ceil(count($array)/2)); ```
Keeping even numbered elements of an array?
[ "", "php", "arrays", "" ]
So, the comparison would be between: ``` MyClass foo = new MyClass(); foo.Property1 = 4; foo.Property2 = "garfield"; ``` and ``` MyClass foo = new MyClass { Property1 = 4, Property2 = "garfield" }; ``` Is it syntactic sugar, or is there actually some kind of performance gain (however minute it's likely to be?)
It's actually potentially *very, very* slightly slower to use an object initializer than to call a constructor and then assign the properties, as it has one extra assignment: ``` MyClass foo = new MyClass(); foo.Property1 = 4; foo.Property2 = "garfield"; ``` vs ``` MyClass tmp = new MyClass(); tmp.Property1 = 4; tmp.Property2 = "garfield"; MyClass foo = tmp; ``` The properties are all assigned before the reference is assigned to the variable. This difference is a *visible* one if it's reusing a variable: ``` using System; public class Test { static Test shared; string First { get; set; } string Second { set { Console.WriteLine("Setting second. shared.First={0}", shared == null ? "n/a" : shared.First); } } static void Main() { shared = new Test { First = "First 1", Second = "Second 1" }; shared = new Test { First = "First 2", Second = "Second 2" }; } } ``` The output shows that in the second line of `Main`, when `Second` is being set (after `First`), the value of `shared.First` is still "First 1" - i.e. `shared` hasn't been assigned the new value yet. As Marc says though, you'll almost certainly never actually spot a difference. Anonymous types are guaranteed to use a constructor - the form is given in section 7.5.10.6 of the C# 3 language specification.
It is **entirely sugar** for standard types. For anonymous types, you may find that it uses a constructor behind the scenes, but since the initializer syntax is the **only** way of assigning them, it is a moot point. This involves a few more calls than, say, a specific constructor - but I'd be **amazed** if you ever saw a difference as a result. Just use initializer syntax - it is friendlier ;-o
Is there a performance improvement if using an object initializer, or is it asthetic?
[ "", "c#", "" ]
I have `IQueryable<someClass>` baseList and `List<someOtherClass>` someData What I want to do is update attributes in some items in baseList. For every item in someData, I want to find the corresponding item in baselist and update a property of the item. someOtherClass.someCode == baseList.myCode can I do some type of join with Linq and set baseList.someData += someOtherClass.DataIWantToConcantenate. I could probably do this by iteration, but is there a fancy Linq way I can do this in just a couple lines of code? Thanks for any tips, ~ck in San Diego
To pair elements in the two lists you can use a LINQ join: ``` var pairs = from d in someData join b in baseList.AsEnumerable() on d.someCode equals b.myCode select new { b, d }; ``` This will give you an enumeration of each item in `someData` paired with its counterpart in `baseList`. From there, you can concatenate in a loop: ``` foreach(var pair in pairs) pair.b.SomeData += pair.d.DataIWantToConcantenate; ``` If you really meant set concatenation rather than `+=`, take a look at LINQ's Union, Intersect or Except methods.
LINQ is for *querying* - not for updating. That means it'll be fine to use LINQ to find the corresponding item, but for the modification you *should* be using iteration. Admittedly you might want to perform some appropriate query to get `baseList` into an efficient form first - e.g. a `Dictionary<string, SomeClass>` based on the property you'll be using to find the corresponding item.
Linq to update a collection with values from another collection?
[ "", "c#", "linq", "collections", "" ]
i have the following code below (i have stuck in xxx to not publish the real name). this code works fine when i upload to the server and will send out emails perfectly. ``` MailMessage msg = new MailMessage(); msg.From = new MailAddress(fromEmailAddress_); msg.To.Add(new MailAddress(toEmailAddress_)); msg.Subject = subject_; msg.Body = body_; msg.IsBodyHtml = true; msg.Priority = MailPriority.High; NetworkCredential basicAuthenticationInfo = new System.Net.NetworkCredential("xxx@xxxx.org", "password"); try { SmtpClient c = new SmtpClient("mail.xxx.org"); c.UseDefaultCredentials = false; c.Credentials = basicAuthenticationInfo; c.Send(msg); } catch (Exception ex) { throw ex; Console.Write(ex.Message.ToString()); } ``` but when i test locally on my machine in visual studio, i get an error: [SocketException (0x274d): **No connection could be made because the target machine actively refused it** 66.226.21.251:25] System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) +239 System.Net.Sockets.Socket.InternalConnect(EndPoint remoteEP) +35 System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception) +224 [WebException: **Unable to connect to the remote server**] System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6, Int32 timeout) +5420699 System.Net.PooledStream.Activate(Object owningObject, Boolean async, Int32 timeout, GeneralAsyncDelegate asyncCallback) +202 System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback) +21 System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout) +332 System.Net.Mail.SmtpConnection.GetConnection(String host, Int32 port) +160 System.Net.Mail.SmtpTransport.GetConnection(String host, Int32 port) +159 any suggestions of why this wouldn't work
The first thing I'd do to run this down is to see whether the target machine is, as the error message says, actually refusing the connections. I can connect to port 25 on that IP address from here, so it's possible that your error message is misleading. These are all possible causes of a failure to connect: * there's some problem in your code * there's some problem in the library you're using * you have a local firewall preventing outbound mail from strange programs * your ISP does not permit outbound SMTP connections except to their own servers * some intermediate network is blocking things * the mail server's ISP is blocking SMTP connections from your network * the mail server really is rejecting you, perhaps because you're on a blocklist To get more detail, download and install [Wireshark](http://www.wireshark.org/). It's like a debugger for networks. Start a capture between your system and the target network and then run your code. Interpreting the captured packets takes some experience, so if you get stuck feel free to post more data here.
Relay restrictions are most likely preventing you from sending mail from outside an allowed set of IPs. If the SMTP Server is configured on a web/application server, it's probably set up to allow mail to be sent via the 127.0.0.1 only. You can configure a local SMTP Server via the IIS Manager. If you go down this path, make sure port 25 is opened up on your local machine. Often times anti-virus type software block/monitor this port and it mucks with email delivery.
sending mail works on server but not on my local machine
[ "", "c#", "asp.net", "email", "smtpclient", "" ]
They could be used as follows: ``` FieldInfo field = fieldof(string.Empty); MethodInfo method1 = methodof(int.ToString); MethodInfo method2 = methodof(int.ToString(IFormatProvider)); ``` `fieldof` could be compiled to IL as: ``` ldtoken <field> call FieldInfo.GetFieldFromHandle ``` `methodof` could be compiled to IL as: ``` ldtoken <method> call MethodBase.GetMethodFromHandle ``` Whenever the `typeof` operator is used, you get perfect Find All References results. Unfortunately, as soon as you go to fields or methods, you end up with nasty hacks. I think you could do the following... or you can go back to getting a field by name. ``` public static FieldInfo fieldof<T>(Expression<Func<T>> expression) { MemberExpression body = (MemberExpression)expression.Body; return (FieldInfo)body.Member; } public static MethodInfo methodof<T>(Expression<Func<T>> expression) { MethodCallExpression body = (MethodCallExpression)expression.Body; return body.Method; } public static MethodInfo methodof(Expression<Action> expression) { MethodCallExpression body = (MethodCallExpression)expression.Body; return body.Method; } public static void Test() { FieldInfo field = fieldof(() => string.Empty); MethodInfo method1 = methodof(() => default(string).ToString()); MethodInfo method2 = methodof(() => default(string).ToString(default(IFormatProvider))); MethodInfo method3 = methodof(() => default(List<int>).Add(default(int))); } ```
Eric Lippert (on the C# design team) has an excellent overview/discussion on this topic [here](http://blogs.msdn.com/ericlippert/archive/2009/05/21/in-foof-we-trust-a-dialogue.aspx). To quote: > It’s an awesome feature that pretty much everyone involved in the design process wishes we could do, but there are good practical reasons why we choose not to. If there comes a day when designing it and implementing it is the best way we could spend our limited budget, we’ll do it. Until then, use Reflection.
You can actually avoid using both reflection and lambdas (.NET Framework 2.0). Consider the following class: ``` public class methodof<T> { private MethodInfo method; public methodof(T func) { Delegate del = (Delegate)(object)func; this.method = del.Method; } public static implicit operator methodof<T>(T methodof) { return new methodof<T>(methodof); } public static implicit operator MethodInfo(methodof<T> methodof) { return methodof.method; } } ``` and it's usage: ``` MethodInfo writeln = (methodof<Action>)Console.WriteLine; MethodInfo parse = (methodof<Func<string, int>>)int.Parse; ```
Why is there not a `fieldof` or `methodof` operator in C#?
[ "", "c#", "reflection", "" ]
Sorry I can't find a question answering this, I'm almost certain someone else has raised it before. My problem is that I'm writing some system libraries to run embedded devices. I have commands which can be sent to these devices over radio broadcasts. This can only be done by text. inside the system libraries I have a thread which handles the commands which looks like this ``` if (value.equals("A")) { doCommandA() } else if (value.equals("B")) { doCommandB() } else if etc. ``` The problem is that there are a lot of commands to it will quickly spiral to something out of control. Horrible to look out, painful to debug and mind boggling to understand in a few months time.
using [Command pattern](http://en.wikipedia.org/wiki/Command_pattern): ``` public interface Command { void exec(); } public class CommandA() implements Command { void exec() { // ... } } // etc etc ``` then build a `Map<String,Command>` object and populate it with `Command` instances: ``` commandMap.put("A", new CommandA()); commandMap.put("B", new CommandB()); ``` then you can replace your **if**/**else if** chain with: ``` commandMap.get(value).exec(); ``` **EDIT** you can also add special commands such as `UnknownCommand` or `NullCommand`, but you need a `CommandMap` that handles these corner cases in order to minimize client's checks.
My suggestion would be a kind of lightweight combination of enum and Command object. This is an idiom recommended by Joshua Bloch in Item 30 of Effective Java. ``` public enum Command{ A{public void doCommand(){ // Implementation for A } }, B{public void doCommand(){ // Implementation for B } }, C{public void doCommand(){ // Implementation for C } }; public abstract void doCommand(); } ``` Of course you could pass parameters to doCommand or have return types. This solution might be not really suitable if the implementations of doCommand does not really "fit" to the enum type, which is - as usual when you have to make a tradeoff - a bit fuzzy.
Long list of if statements in Java
[ "", "java", "design-patterns", "command-pattern", "" ]
In PHP I want to be able to set a variable value "superglobally" - that is a *me-defined* value that is accessible to EVERY script that runs on the server at its FIRST line of code (i.e. without having to require\_once() anything or anything like that). Currently I'm using **$\_ENV[ 'varname' ]** by setting an environment variable on my system called **varname**. But it requires a reboot to make a change to the variable value on a Windows system, which is not good. Are there any other solutions short of modifying php source?
You can set a value in your `php.ini` which you can then retrieve with [`get_cfg_var`](http://www.php.net/manual/en/function.get-cfg-var.php).
If you are using Apache, you could take a look at [`mod_env`](http://httpd.apache.org/docs/2.2/mod/mod_env.html) It will allow you to use the `SetEnv` directive in Apache's configuration *(and in .htaccess files, if your Apache server is configured so you can use those)*, like this : In my Apache's file : ``` <VirtualHost *> ServerName tests DocumentRoot /home/squale/developpement/tests .... SetEnv MY_TEST_VARIABLE "Hello, World!" .... </VirtualHost> ``` *(Require's an Apache restart to be taken into account)* Or in an .htaccess file : ``` SetEnv MY_OTHER_TEST_VARIABLE "This is looking nice !" ``` *(Immediatly taken into account)* And, then, these variables are available in `$_SERVER` : ``` var_dump($_SERVER); ``` Gives me : ``` array 'MY_TEST_VARIABLE' => string 'Hello, World!' (length=13) 'MY_OTHER_TEST_VARIABLE' => string 'This is looking nice !' (length=22) 'HTTP_HOST' => string 'tests' (length=5) 'HTTP_USER_AGENT' => string 'Mozilla/5.0 (X11; U; Linux x86_64; en-US; rv:1.9.1.1) Gecko/20090716 Ubuntu/9.04 (jaunty) Shiretoko/3.5.1' (length=105) 'HTTP_ACCEPT' => string 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8' (length=63) 'HTTP_ACCEPT_LANGUAGE' => string 'en-us,en;q=0.5' (length=14) .... .... ``` It's not `$_ENV` like you requested... But almost ;-) And the idea is really the same ^^
Modifying PHP superglobals other than $_ENV
[ "", "php", "" ]
The following code leads to `java.lang.IllegalThreadStateException: Thread already started` when I called `start()` method **second time** in program. ``` updateUI.join(); if (!updateUI.isAlive()) updateUI.start(); ``` This happens the **second** time `updateUI.start()` is called. I've stepped through it multiple times and the thread is called and completly runs to completion before hitting `updateUI.start()`. Calling `updateUI.run()` avoids the error but causes the thread to run in the UI thread (the calling thread, as mentioned in other posts on SO), which is not what I want. Can a Thread be *started* only once? If so than what do I do if I want to run the thread again? This particular thread is doing some calculation in the background, if I don't do it in the thread than it's done in the UI thread and the user has an unreasonably long wait.
From the [Java API Specification](http://java.sun.com/javase/6/docs/api/) for the [`Thread.start`](http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#start()) method: > It is never legal to start a thread > more than once. In particular, a > thread may not be restarted once it > has completed execution. Furthermore: > Throws: > [`IllegalThreadStateException`](http://java.sun.com/javase/6/docs/api/java/lang/IllegalThreadStateException.html) - if the thread was already started. So yes, a `Thread` can only be started once. > If so than what do I do if I want to > run the thread again? If a `Thread` needs to be run more than once, then one should make an new instance of the `Thread` and call `start` on it.
Exactly right. [From the documentation](http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#start%28%29): > It is never legal to start a thread > more than once. In particular, a > thread may not be restarted once it > has completed execution. In terms of what you can do for repeated computation, it seems as if you could use [SwingUtilities invokeLater method](http://java.sun.com/javase/6/docs/api/javax/swing/SwingUtilities.html#invokeLater%28java.lang.Runnable%29). You are already experimenting with calling `run()` directly, meaning you're already thinking about using a `Runnable` rather than a raw `Thread`. Try using the `invokeLater` method on just the `Runnable` task and see if that fits your mental pattern a little better. Here is the example from the documentation: ``` Runnable doHelloWorld = new Runnable() { public void run() { // Put your UI update computations in here. // BTW - remember to restrict Swing calls to the AWT Event thread. System.out.println("Hello World on " + Thread.currentThread()); } }; SwingUtilities.invokeLater(doHelloWorld); System.out.println("This might well be displayed before the other message."); ``` If you replace that `println` call with your computation, it might just be exactly what you need. EDIT: following up on the comment, I hadn't noticed the Android tag in the original post. The equivalent to invokeLater in the Android work is `Handler.post(Runnable)`. From its javadoc: ``` /** * Causes the Runnable r to be added to the message queue. * The runnable will be run on the thread to which this handler is * attached. * * @param r The Runnable that will be executed. * * @return Returns true if the Runnable was successfully placed in to the * message queue. Returns false on failure, usually because the * looper processing the message queue is exiting. */ ``` So, in the Android world, you can use the same example as above, replacing the `Swingutilities.invokeLater` with the appropriate post to a `Handler`.
Is it legal to call the start method twice on the same Thread?
[ "", "java", "android", "multithreading", "" ]
I've got a simple Listbox on a HTML form and this very basic jQuery code ``` //Toggle visibility of selected item $("#selCategory").change(function() { $(".prashQs").addClass("hide"); var cat = $("#selCategory :selected").attr("id"); cat = cat.substr(1); $("#d" + cat).removeClass("hide"); }); ``` The change event fires fine when the current item is selected using the Mouse, but when I scroll through the items using the keyboard the event is not fired and my code never executes. Is there a reason for this behavior? And what's the workaround?
The `onchange` event isn't generally fired until the element loses focus. You'll also want to use `onkeypress`. Maybe something like: ``` var changeHandler = function() { $(".prashQs").addClass("hide"); var cat = $("#selCategory :selected").attr("id"); cat = cat.substr(1); $("#d" + cat).removeClass("hide"); } $("#selCategory").change(changeHandler).keypress(changeHandler); ``` You'll want both `onchange` and `onkeypress` to account for both mouse and keyboard interaction respectively.
Sometimes the change behavior can differ per browser, as a workaround you could do something like this: ``` //Toggle visibility of selected item $("#selCategory").change(function() { $(".prashQs").addClass("hide"); var cat = $("#selCategory :selected").attr("id"); cat = cat.substr(1); $("#d" + cat).removeClass("hide"); }).keypress(function() { $(this).change(); }); ``` You can chain whatever events you want and manually fire the change event. IE: ``` var changeMethod = function() { $(this).change(); }; ....keypress(changeMethod).click(changeMethod).xxx(changeMethod); ```
Jquery Listbox Change event does not fire on Keyboard scrolling
[ "", "javascript", "jquery", "jquery-events", "" ]
I have code using `XmlSerializer` to serialize/deserialize a data structure for persistance. I've read and heard in several places here on StackOverflow that `XmlSerializer` is one or more of: * Bad * Poorly supported/implemented * Possibly won't be supported into the future My question is two-fold; is any of the above true, and if so, what alternatives exist? For my purposes, XML works very well, and I would like to keep that much constant, but everything else is open to change. **EDIT:** If you want to suggest something other to XML, I'm open to it, but it does need to be human-readable.
`XmlSerializer` is perfectly supportable, but has some glitches; * *relatively* slow; but usually this is still fast enough * only supports public members; can be a pain * requires write accessors lists - just ugly However, I expect it to continue to be there for a considerable time; IMO, it is `BinaryFormatter` that has the *real* problems (when used for persistence). I'm very biased (since I'm the author), but I'd choose [protobuf-net](http://code.google.com/p/protobuf-net/); a binary serializer using Google's "protocol buffers" wire format; fast, portable between languages/platforms, very small output, version tolerant, etc (and free, of course). Clearly not xml, though - so not human readable.
As far as the XML Serializer, there's "supported", and there's "supported". An increasing number of Connect bug reports on the XML Serializer are coming back acknowledging bugs, and stating that the bugs will not be fixed. I'm sure that if you ran into a security-critical bug in the XML Serializer, that it would be fixed. However, I think it's unlikely that other bugs that are not as critical will ever be fixed.
Replacement for XML Serialization
[ "", "c#", "xml", "xml-serialization", "" ]
Specifically, I have two lists of strings that I'd like to combine into a string where each line is the next two strings from the lists, separated by spaces: ``` a = ['foo1', 'foo2', 'foo3'] b = ['bar1', 'bar2', 'bar3'] ``` I want a function combine\_to\_lines() that would return: ``` """foo1 bar1 foo2 bar2 foo3 bar3""" ``` I admit I've already solved this problem, so I'm going to post the answer. But perhaps someone else has a better one or sees a flaw in mine. **Update**: I over-simplified my example above. In my real-world problem the lines were formatted in a more complicated manner that required the tuples returned from zip() to be unpacked. But kudos to [mhawke](https://stackoverflow.com/users/21945/mhawke) for coming up to the simplest solution to this example.
It's not necessary to unpack and repack the tuples returned by zip: ``` '\n'.join(' '.join(x) for x in zip(a, b)) ```
The [zip function](http://docs.python.org/library/functions.html#zip) "returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables." ``` def combine_to_lines(list1, list2): return '\n'.join([' '.join((a, b)) for a, b in zip(list1, list2)]) ```
How do I iterate over the tuples of the items of two or more lists in Python?
[ "", "python", "loops", "" ]
Let's say I have three tables: table1 fields: ``` memberid | name ``` table2 fields: ``` interestId | interestName ``` table3 (used to make a relation between member and interest) fields: ``` memberid | interestId ``` and now I know I can user `inner join` to `select` one member's all interests. But how can I cascade all the interests in a single row??? For example, I can select this result: ``` memberid name interstId interestName 1 dennis 1 play basketball 1 dennis 2 music 1 dennis 3 moive ``` but the result i want to get is: ``` memberid name interests 1 dennis play basketball, music, moive ``` How can I write the SQL query? Thanks in advance!
In SQL Server 2005 onwards, You can use XML Path() to concatenate values. It appears to be very performant too. **EDIT :** Have tested the following and works ``` SELECT t1.memberid, t1.[name], ISNULL(STUFF( ( SELECT ', ' + t2.interestName FROM table2 t2 INNER JOIN table3 t3 ON t2.interestId = t3.interestId WHERE t3.memberid = t1.memberid FOR XML PATH('') ), 1, 2, '' ), 'None') As interests FROM table1 t1 GROUP BY t1.memberid, t1.[name] ``` Example code: ``` DECLARE @table1 TABLE ( memberid INT IDENTITY(1,1), name VARCHAR(25) ) INSERT INTO @table1 VALUES('dennis'); INSERT INTO @table1 VALUES('mary'); INSERT INTO @table1 VALUES('bill'); DECLARE @table2 TABLE ( interestId INT IDENTITY(1,1), interestName VARCHAR(25) ) INSERT INTO @table2 VALUES('play basketball'); INSERT INTO @table2 VALUES('music'); INSERT INTO @table2 VALUES('movie'); INSERT INTO @table2 VALUES('play hockey'); INSERT INTO @table2 VALUES('wine tasting'); INSERT INTO @table2 VALUES('cheese rolling'); DECLARE @table3 TABLE ( memberid INT, interestId INT ) INSERT INTO @table3 VALUES(1,1); INSERT INTO @table3 VALUES(1,2); INSERT INTO @table3 VALUES(1,3); INSERT INTO @table3 VALUES(2,2); INSERT INTO @table3 VALUES(2,4); INSERT INTO @table3 VALUES(2,6); INSERT INTO @table3 VALUES(3,1); INSERT INTO @table3 VALUES(3,5); INSERT INTO @table3 VALUES(3,6); SELECT t1.memberid, t1.[name], ISNULL(STUFF( ( SELECT ', ' + t2.interestName FROM @table2 t2 INNER JOIN @table3 t3 ON t2.interestId = t3.interestId WHERE t3.memberid = t1.memberid FOR XML PATH('') ), 1, 2, '' ), 'None') As interests FROM @table1 t1 GROUP BY t1.memberid, t1.[name] ``` Results ``` memberid name interests ----------- ----------------------------------------------------------------------- 1 dennis play basketball, music, movie 2 mary music, play hockey, cheese rolling 3 bill play basketball, wine tasting, cheese rolling ```
It depends on the DB you are using. Take a look at this question: [Show a one to many relationship as 2 columns - 1 unique row (ID & comma separated list)](https://stackoverflow.com/questions/715350/show-a-one-to-many-relationship-as-2-columns-1-unique-row-id-comma-separated)
How can i select multiple row and cascade them?
[ "", "sql", "" ]
I am using Qt's `QGraphicsView` — and `QGraphicsItem` — subclasses. Is there a way to not scale the graphical representation of the item in the view when the view rectangle is changed, e.g., when zooming in. The default behavior is that my items scale in relation to my view rectangle. I would like to visualize 2d points which should be represented by a thin rectangle which should not scale when zooming in the view. See a typical 3d modelling software for reference, where vertex points are always shown at the same size.
Set the `QGraphicItem`'s flag `QGraphicsItem::ItemIgnoresTransformations` to true does not work for you?
Extend a QGraphicsItem class, override `paint()`. Inside the `paint()`, reset the transformation's scaling factor to 1 (which are `m11` and `m22`), and save the `m11` (x scaling factor) and `m22` (y scaling factor) before the reset. Then, draw like you would normally do, but multiply your x with `m11` and y with `m22`. This avoids drawing with the default transformation, but explicitly calculates the positions according to the scene's transformation. ``` void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *item, QWidget *widget) { QTransform t = painter->transform(); qreal m11 = t.m11(), m22 = t.m22(); painter->save(); // save painter state painter->setTransform(QTransform(1, t.m12(), t.m13(), t.m21(), 1, t.m23(), t.m31(), t.m32(), t.m33())); int x = 0, y = 0; // item's coordinates painter->drawText(x*m11, y*m22, "Text"); // the text itself will not be scaled, but when the scene is transformed, this text will still anchor correctly painter->restore(); // restore painter state } ``` The following code block is drawing with default transformation: ``` void MyItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *item, QWidget *widget) { int x = 0, y = 0; painter->drawText(x, y, "Text"); } ``` You can try both to see the difference.
Prevent scaling an item when scaling the view rect
[ "", "c++", "qt", "transformation", "qgraphicsview", "qgraphicsscene", "" ]
Can one use Window.Onscroll method to include detection of scroll direction?
If you record the scrollX and scrollY on page load and each time a scroll event occurs, then you can compare the previous values with the new values to know which direction you scrolled. Here's a proof of concept: ``` function scrollFunc(e) { if ( typeof scrollFunc.x == 'undefined' ) { scrollFunc.x=window.pageXOffset; scrollFunc.y=window.pageYOffset; } var diffX=scrollFunc.x-window.pageXOffset; var diffY=scrollFunc.y-window.pageYOffset; if( diffX<0 ) { // Scroll right } else if( diffX>0 ) { // Scroll left } else if( diffY<0 ) { // Scroll down } else if( diffY>0 ) { // Scroll up } else { // First scroll event } scrollFunc.x=window.pageXOffset; scrollFunc.y=window.pageYOffset; } window.onscroll=scrollFunc ```
With jquery, you can also register a custom scroll event which supplies the scroll change as an argument to the event handler: ``` var previous_scroll = $(window).scrollTop(); $(window).on('scroll', function() { var scroll = $(window).scrollTop(), scroll_change = scroll - previous_scroll; previous_scroll = scroll; $(window).trigger('custom_scroll', [scroll_change]); }); ``` Then instead of `scroll`, bind to `custom_scroll`: ``` $(window).on('custom_scroll', function pos(e, scroll_change) { console.log(scroll_change); }); ```
Can one use Window.Onscroll method to include detection of scroll direction?
[ "", "javascript", "" ]
I have two code samples. The first does not compile, but the second does. **Code Sample 1** *(does not compile)* ``` public void MyMethod(){ int i=10; for(int x=10; x<10; x++) { int i=10; // Point1: compiler reports error var objX = new MyOtherClass(); } var objX = new OtherClassOfMine(); // Point2: compiler reports error } ``` I understand why the compiler reports an error at `Point1`. But I don't understand why it reports an error at `Point2`. And if you say it is because of the organization inside MSIL, then why does the second code example compile? **Code sample 2** *(compiles)* ``` public void MyMethod(){ for(int x=10; x<10; x++) { int i=10; var objX = new MyOtherClass(); } for(int x=10; x<10; x++) { int i=10; var objX = new MyOtherClass(); } } ``` If the simple rules of variable scope apply in Code Sample 2, then why don't those same rules apply to Code Sample 1?
There are two relevant rules here. The first relevant rule is: > It is an error for a local variable > declaration space and a nested local > variable declaration space to contain > elements with the same name. (And another answer on this page calls out another location in the specification where we call this out again.) That alone is enough to make this illegal, but in fact a second rule makes this illegal. The second relevant rule in C# is: > For each occurrence of a given > identifier as a simple-name in an > expression or declarator, within the > local variable declaration space, > immediately enclosing block, or > switch-block of that occurrence, > every other occurrence of the same > identifier as a simple-name in an > expression or declarator within the > immediately enclosing block or > switch-block must refer to the same > entity. This rule ensures that the > meaning of a name is always the same > within a given block, switch block, > for-, foreach- or using-statement, or > anonymous function. (UPDATE: This answer was written in 2009; in recent versions of C# this rule has been eliminated because it was considered to be too confusing; the user confusion produced was not worth the small number of bugs that were prevented. [See this answer](https://stackoverflow.com/questions/59973000/why-can-i-declare-a-child-variable-with-the-same-name-as-a-variable-in-the-paren/59973360#59973360) for details.) You also need to know that a for-loop is treated as though there are "invisible braces" around the whole thing. Now that we know that, let's annotate your code: ``` public void MyMethod() { // 1 int i=10; // i1 { // 2 -- invisible brace for(int x=10; x<10; x++) // x2 { // 3 int i=10; // i3 var objX = new MyOtherClass(); // objX3 } // 3 } // 2 var objX = new OtherClasOfMine(); // objX1 } // 1 ``` You have three "simple names", i, x and objX. You have five variables, which I've labeled i1, x2, i3, objX3, and objX1. The outermost block that contains usages of i and objX is block 1. Therefore, within block 1, i and objX must always refer to the same thing. But they do not. Sometimes i refers to i1 and sometimes it refers to i3. Same with objX. x, however, only ever means x2, in every block. Also, both "i" variables are in the same local variable declaration space, as are both "objX" variables. Therefore, this program is an error in several ways. In your second program: ``` public void MyMethod() { // 1 { // 2 -- invisible for(int x=10; x<10; x++) // x2 { // 3 int i=10; // i3 var objX = new MyOtherClass(); // objX3 } //3 } // 2 { // 4 -- invisible for(int x=10; x<10; x++) // x4 { // 5 int i=10; // i5 var objX = new MyOtherClass(); // objX5 } //5 } // 4 } // 1 ``` Now you have three simple names again, and six variables. The outermost blocks that first contain a usage of simple name x are blocks 2 and 4. Throughout block 2, x refers to x2. Throughout block 4, x refers to x4. Therefore, this is legal. Same with i and objX -- they are used in blocks 3 and 5 and mean different things in each. But nowhere is the same simple name used to mean two different things throughout the same block. Now, you might note that **considering all of block 1**, x is used to mean both x2 and x4. But there's no mention of x that is inside block 1 but NOT also inside another block. Therefore we don't count the inconsistent usage in block 1 as relevant. Also, none of the declaration spaces overlap in illegal ways. Therefore, this is legal.
From the C# Language Specification... > The scope of a local variable declared > in a local-variable-declaration is the > block in which the declaration occurs. > It is an error to refer to a local > variable in a textual position that > precedes the local-variable-declarator > of the local variable. Within the > scope of a local variable, it is a > compile-time error to declare another > local variable or constant with the > same name. In code sample 1, both i and objX are declared in the scope of the function, so no other variable in any block inside that function can share a name with them. In code sample 2, both objXs are declared inside of the for loops, meaning that they do not violate the rule of not redeclaring local variables in inner scopes from another declaration.
Variable scope confusion in C#
[ "", "c#", "scope", "" ]
I have a simple class library written in c#. ``` using System; namespace TestDll { public class Test { public string HelloWorld { get { return "Hello World"; } } } } ``` My question is how can I call this HelloWorld function from Microsoft Office Visual Basic (which I think is VB6)? My first step was to add the DLL as a reference - but on browsing and selecting the compiled DLL the message "Can't add a reference to the specified file." was thrown. Can anyone point me in the right direction as to why/how to get this working? Thanks in advance SO!
You can't access a static member via COM interop. In fact your code doesn't even compile, the method should be in a class. Here is how you can do it: ``` [InterfaceType(ComInterfaceType.InterfaceIsDual)] [Guid("01A31113-9353-44cc-A1F4-C6F1210E4B30")] //Allocate your own GUID public interface _Test { string HelloWorld { get; } } [ClassInterface(ClassInterfaceType.None)] [Guid("E2F07CD4-CE73-4102-B35D-119362624C47")] //Allocate your own GUID [ProgId("TestDll.Test")] public class Test : _Test { public string HelloWorld { get { return "Hello, World! "; } } } ``` The project properties Build tab, select Register for COM interop. So you can see the results quickly. To install the dll on another machine you need to use regasm. To then consume this: ``` Dim o : Set o = CreateObject("TestDll.Test") MsgBox o.HelloWorld ``` You can also reference the dll and use early binding: ``` Dim o As TestDll.Test Set o = New TestDll.Text MsgBox o.HelloWorld ```
And to expand on registering the DLL on different computers. Once you compile and build the above code on your development machine, if you have > The project properties Build tab, select Register for COM interop. your Visual Studio output folder (usually bin\Debug) where the compiled \*.dll is found will also have a \*.tlb file. This \*.tlb file is a 'Type Library'. And is needed by the client machine to understand the different 'Types' in your \*.dll and to basically tell the client machine how to use it. By setting the above 'Register for COM interop' -- aswell as a \*.tlb file being produced, the assembly(dll) is registered on your machine, and is therefore accessible. In VBA you can now add this file as a reference by > VBA Editor -> Tools -> References -> Browse -> Select this will allow you to then declare the classes found in your library. ``` Dim TestClass As Test Set TestClass = New Test MsgBox TestClass.HelloWorld ``` HOWEVER - if you want to then use your dll on a different client machine, you will have to use regasm.exe - to register the assembly(dll) on that machine. This can be done by the command line, > regasm.exe in this case > regasm.exe TestDll.dll once you have registered the assembly on the new client machine, you will be able to access it by again adding a reference to its \*.tlb Hope this helps!
A Simple C# DLL - how do I call it from Excel, Access, VBA, VB6?
[ "", "c#", "excel", "dll", "vb6", "interop", "" ]
Does anybody knows fate of Global Interpreter Lock in Python 3.1 against C++ multithreading integration
GIL is still there in CPython 3.1; the [Unladen Swallow](http://code.google.com/p/unladen-swallow/) projects aims (among many other performance boosts) to eventually remove it, but it's still a way from its goals, and is working on 2.6 first with the intent of eventually porting to 3.x for whatever x will be current by the time the 2.y version is considered to be done. For now, multiprocessing (instead of threading) remains the way of choice for using multiple cores in CPython (IronPython and Jython are fine too, but they don't support Python 3 currently, nor do they make C++ integration all that easy either;-).
Significant changes will occur in the GIL for Python 3.2. Take a look at the [What's New for Python 3.2](http://docs.python.org/dev/py3k/whatsnew/3.2.html#multi-threading), and [the thread that initiated it in the mailing list](http://mail.python.org/pipermail/python-dev/2009-October/093359.html). While the changes don't signify the end of the GIL, they herald potentially enormous performance gains. ## Update * The general performance gains with the new GIL in 3.2 by Antoine Pitrou were negligible, and instead focused on [improving contention issues](http://bugs.python.org/issue7316) that arise in certain corner cases. * An [admirable effort](http://bugs.python.org/issue7946) by David Beazley was made to implement a scheduler to significantly improve performance when CPU and IO bound threads are mixed, which was unfortunately shot down. * The Unladen Swallow work was [proposed for merging](http://www.python.org/dev/peps/pep-3146/) in Python 3.3, but this has been withdrawn due to lack of results in that project. [PyPy](http://pypy.org/) is now the preferred project and is currently [requesting funding](http://pypy.org/py3donate.html) to add Python3k support. There's very little chance that PyPy will become the default at present. Efforts have been made for the last 15 years to remove the GIL from CPython but for the foreseeable future it is here to stay.
GIL in Python 3.1
[ "", "python", "multithreading", "gil", "" ]
Given the function ``` def f(): x, y = 1, 2 def get(): print 'get' def post(): print 'post' ``` is there a way for me to access its local get() and post() functions in a way that I can call them? I'm looking for a function that will work like so with the function f() defined above: ``` >>> get, post = get_local_functions(f) >>> get() 'get' ``` I can access the code objects for those local functions like so ``` import inspect for c in f.func_code.co_consts: if inspect.iscode(c): print c.co_name, c ``` which results in ``` get <code object get at 0x26e78 ...> post <code object post at 0x269f8 ...> ``` but I can't figure out how to get the actual callable function objects. Is that even possible? Thanks for your help, Will.
You are pretty close of doing that - just missing `new` module: ``` import inspect import new def f(): x, y = 1, 2 def get(): print 'get' def post(): print 'post' for c in f.func_code.co_consts: if inspect.iscode(c): f = new.function(c, globals()) print f # Here you have your function :]. ``` But why the heck bother? Isn't it easier to use class? Instantiation looks like a function call anyway.
You can return functions just like any other object in Python: ``` def f(): x, y = 1, 2 def get(): print 'get' def post(): print 'post' return (get, post) get, post = f() ``` Hope this helps! Note, though, that if you want to use your 'x' and 'y' variables in get() or post(), you should make them a list. If you do something like this: ``` def f(): x = [1] def get(): print 'get', x[0] x[0] -= 1 def post(): print 'post', x[0] x[0] += 1 return (get, post) get1, post1 = f() get2, post2 = f() ``` get1 and post1 will reference a different 'x' list than get2 and post2.
Introspecting a given function's nested (local) functions in Python
[ "", "python", "function", "introspection", "inspect", "" ]
I'm a .NET and MVC newbie, and learning it for the first time after suffering too long with ASP, and it's about time I converted over to make my job of building web applications that much easier. I've been going through Stephen Walther's helpful video tutorials to get my head around most things, and I'm making good progress thus far. Where I've come unstuck is creating a details page for a record in my application, ConversationApp. Listing data and inserting new data is working perfectly, but everytime I go to view the details page for any specific record I receive the error message "Object reference not set to an instance of an object". URL being passed to the controller is: /Home/Details/X (where X is unique ID for the record) I would appreciate any help to get me past what is likely a very stupid mistake of mine or an oversight. Here's where I am so far, code wise: **HomeController.CS** ``` using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Mvc.Ajax; using ConversationApp.Models; namespace ConversationApp.Controllers { public class HomeController : Controller { private conversationDBEntities _entities = new conversationDBEntities(); // // GET: /Home/ public ActionResult Index() { return View(_entities.conversation.ToList()); } // // GET: /Home/Details/5 public ActionResult Details(int id) { return View(); } // // GET: /Home/Create public ActionResult Create() { return View(); } // // POST: /Home/Create [AcceptVerbs(HttpVerbs.Post)] public ActionResult Create([Bind(Exclude="conversation_id")]conversation conversationToCreate) { try { // TODO: Add insert logic here _entities.AddToconversation(conversationToCreate); _entities.SaveChanges(); return RedirectToAction("Index"); } catch { return View(); } } // // GET: /Home/Edit/5 public ActionResult Edit(int id) { return View(); } // // POST: /Home/Edit/5 [AcceptVerbs(HttpVerbs.Post)] public ActionResult Edit(int id, FormCollection collection) { try { // TODO: Add update logic here return RedirectToAction("Index"); } catch { return View(); } } } } ``` **Details.aspx** ``` <%@ Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage<ConversationApp.Models.conversation>" %> <asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server"> Details </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server"> <h2>Details</h2> <fieldset> <legend>Fields</legend> <p> conversation_name: <%= Html.Encode(Model.conversation_name) %> </p> <p> conversation_owner: <%= Html.Encode(Model.conversation_owner) %> </p> <p> conversation_description: <%= Html.Encode(Model.conversation_description) %> </p> <p> conversation_homeurl: <%= Html.Encode(Model.conversation_homeurl) %> </p> </fieldset> <p> <%=Html.ActionLink("Edit", "Edit", new { id=Model.conversation_id }) %> | <%=Html.ActionLink("Back to List", "Index") %> </p> ``` **Error message for /Home/Details/X (where X is unique ID for record)** ``` Server Error in '/' Application. -------------------------------------------------------------------------------- Object reference not set to an instance of an object. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. Exception Details: System.NullReferenceException: Object reference not set to an instance of an object. Source Error: Line 13: <p> Line 14: conversation_name: Line 15: <%= Html.Encode(Model.conversation_name) %> Line 16: </p> Line 17: <p> Source File: c:\Users\Michael Harris\Documents\Visual Studio 2008\Projects\ConversationApp\ConversationApp\Views\Home\Details.aspx Line: 15 Stack Trace: [NullReferenceException: Object reference not set to an instance of an object.] ASP.views_home_details_aspx.__RenderContent2(HtmlTextWriter __w, Control parameterContainer) in c:\Users\Michael Harris\Documents\Visual Studio 2008\Projects\ConversationApp\ConversationApp\Views\Home\Details.aspx:15 System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +256 System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19 System.Web.UI.Control.Render(HtmlTextWriter writer) +10 System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27 System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99 System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25 ASP.views_shared_site_master.__Render__control1(HtmlTextWriter __w, Control parameterContainer) in c:\Users\Michael Harris\Documents\Visual Studio 2008\Projects\ConversationApp\ConversationApp\Views\Shared\Site.Master:26 System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +256 System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19 System.Web.UI.Control.Render(HtmlTextWriter writer) +10 System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27 System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99 System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25 System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +134 System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19 System.Web.UI.Page.Render(HtmlTextWriter writer) +29 System.Web.Mvc.ViewPage.Render(HtmlTextWriter writer) +59 System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27 System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99 System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1266 -------------------------------------------------------------------------------- Version Information: Microsoft .NET Framework Version:2.0.50727.4918; ASP.NET Version:2.0.50727.4918 ```
In your Details action method on the controller you are not passing the model back to the view. ``` public ActionResult Details(int id) { // get model object return View(//pass model object to view here); } ```
It doesn't look like you're passing any data to the `Details` view: ``` public ActionResult Details(int id) { return View(); } ``` Retrieve your model class from your repository and pass it to the view: ``` return View(conversation); ```
ASP.NET MVC C#: Object reference errors when going to view record details
[ "", "c#", "asp.net-mvc", "" ]
I am working with a one dimensional array in PHP. I would like to detect the presence of duplicate values, then count the number of duplicate values and output the results. For example, given the following array: ``` $array = [ 'apple', 'orange', 'pear', 'banana', 'apple', 'pear', 'kiwi', 'kiwi', 'kiwi' ]; ``` I would like to print: ``` apple (2) orange pear (2) banana kiwi (3) ``` Any advice on how to approach this problem?
You can use [array\_count\_values](https://www.php.net/manual/en/function.array-count-values.php) function ``` $array = array('apple', 'orange', 'pear', 'banana', 'apple', 'pear', 'kiwi', 'kiwi', 'kiwi'); print_r(array_count_values($array)); ``` will output ``` Array ( [apple] => 2 [orange] => 1 [pear] => 2 etc... ) ```
``` if(count(array_unique($array))<count($array)) { // Array has duplicates } else { // Array does not have duplicates } ```
Count and display occurrences of unique values in an array
[ "", "php", "arrays", "counting", "" ]
While reading "C++ Primer Plus 5th edition", I saw this piece of code: ``` cin.get(ch); ++ch; cout << ch; ``` So, this will lead to display the following character after ch. But, If I did it that way: ``` cin.get(ch); cout << ch+1; ``` Now, cout will think ch is an int(try typecasting). So, why cout does so? And why if I added 1 to a char it will produce a number?. And why there's a difference between: ch++, and ch + 1.
The reason this occurs is the type of the literal `1` is int. When you add an int and a char you get an int, but when you increment a char, it remains a char. Try this: ``` #include <iostream> void print_type(char) { std::cout << "char\n"; } void print_type(int) { std::cout << "int\n"; } void print_type(long) { std::cout << "long\n"; } int main() { char c = 1; int i = 1; long l = 1; print_type(c); // prints "char" print_type(i); // prints "int" print_type(l); // prints "long" print_type(c+i); // prints "int" print_type(l+i); // prints "long" print_type(c+l); // prints "long" print_type(c++); // prints "char" return 0; } ```
**Please note - this is the answe to the original question, which has since been edited.** > Now, cout will think ch is an int(try > typecasting). No it won't. It is not possible to change the type of a variable in C++. ``` ++ch; ``` increments whatever is in ch. ch + 1; takes the value (contents) of ch, adds 1 to it and discards the result. Whatever is in ch is unchanged.
"Ch++" or "ch+1" in C++?
[ "", "c++", "cout", "" ]
is there anyone who knows how to install / configure php under apache? I have emerge php apache both. I wanted to use mod\_php for apache in GENTOO OS. php temp.php command line runs fine, but <http://localhost/temp.php> is not executing on web server instead it shows the content of the php code.
I found a blog and I followed his instruction and it works ! I'm sharing the solution [Referenced Blog](http://tronprog.blogspot.com/2007/02/apache2-php-mysql-gentoo-linux.html) I put these lines in /etc/make.conf: ``` USE="apache2 mysql php pam ssl xml xml2 berkdb innodb jpeg png" ``` If you want to install also phpmyadmin, then you should also add pcre session unicode: ``` USE="apache2 mysql php pam ssl xml xml2 berkdb innodb jpeg png pcre session unicode" ``` I then changed the file /etc/init.d/apache2, in order to enable public\_html folders for users (corresponding to the ~ directory), setting -D USERDIR: ``` APACHE2_OPTS="-D DEFAULT_VHOST -D PHP5 -D USERDIR ``` Before starting mysql, you must create (once and for all) the mysql main database, and this can be done simply by running: ``` /usr/bin/mysql_install_db ```
There appear to be a number of ways to achieve this but many seem a bit out of date or overly complicated. As of Feb 1 2010 all I did to get PHP and Apache2 working on Gentoo was to install Apache and PHP like this: 1. `bash$ emerge apache` 2. Followed the instructions for the particular extensions I wanted at [this list at the Gentoo site](http://overlays.gentoo.org/proj/php/wiki/ManagingExtensions) * NOTE: this is the important one to get Apache and PHP working together: + `bash$ echo "dev-lang/php apache2" >> /etc/portage/package.use` * Another common PHP extension: + `bash$ echo "dev-lang/php mysql" >> /etc/portage/package.use` * And so on. 3. Then just run `bash$ emerge dev-lang/php` and restart Apache with the /etc/init.d/apache2 script. PHP should now be available.
How to configure PHP under Apache web server in GENTOO Operating System?
[ "", "php", "apache", "gentoo", "mod-php", "" ]
Here is another old function I have from my C# 1 days, what would be a more elegant way to write it: ``` //method: gets the text in a string in front of a marker, if marker is not there, then return empty string //example: GetTextAfterMarker("documents/jan/letter043.doc","/") returns "documents" //example: GetTextAfterMarker("letter043.doc","/") returns "" //rank:8 public static string GetTextAfterMarker(string line, string marker) { string r = ""; int pos = line.IndexOf(marker); if(pos != -1) { r = line.Substring(pos+(marker.Length),line.Length-pos-(marker.Length)); } else { r = ""; } return r; } ```
I find the name somewhat strange, given that it should return the text appearing *before* the first marker. But this one does the same job, I think (I took the liberty to change the name): ``` public static string GetTextBeforeMarker(string line, string marker) { if (line == null) { throw new ArgumentNullException("line"); } if (marker == null) { throw new ArgumentNullException("marker"); } string result = line.Split(new string[] { marker }, StringSplitOptions.None)[0]; return line.Equals(result) ? string.Empty : result; } ``` Explanation: split the string into an array using the marker as split argument. If the first element of the result is the same as the input, the marker was not in the string, so we return an empty string, otherwise we return the first element (which is the text up to the first occurrence of the marker).
Am I missing something? Wouldn't this be more simple? Also I prefer `Substring` to `Split`. ``` public static string GetTextAfterMarker(string line, string marker) { int pos = line.IndexOf(marker); if (pos == -1) return string.Empty; return line.Substring(0,pos); } ```
What is the most elegant way to implement GetTextAfterMarker()
[ "", "c#", "string", "refactoring", "" ]
How can I configure the maven compiler to use java 5 for my test code and java 1.4 for my main code?
If you want to set compliance to the relevant Java version, you can configure the compiler plugin for each execution. Assuming Maven is using a JDK at least as current as the highest version you specify. By using properties you can override that configuration on the commandline or in a child if needed: ``` <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>${compileSource}</source> <target>${compileSource}</target> </configuration> <executions> <execution> <id>test-compile</id> <phase>process-test-sources</phase> <goals> <goal>testCompile</goal> </goals> <configuration> <source>${testCompileSource}</source> <target>${testCompileSource}</target> </configuration> </execution> </executions> </plugin> ... <properties> <compileSource>1.4</compileSource> <testCompileSource>1.5</testCompileSource> </properties> ``` If you mean using different **compilers**, that's a bit more involved. as you need to specify the path to the JDK and what compiler version you're using. Again these can be defined in properties. Though you may want to define them in your settings.xml ``` <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>${compileSource}</source> <target>${compileSource}</target> <executable>${compileJdkPath}/bin/javac</executable> <compilerVersion>${compileSource}</compilerVersion> </configuration> <executions> <execution> <id>test-compile</id> <phase>process-test-sources</phase> <goals> <goal>testCompile</goal> </goals> <configuration> <source>${testCompileSource}</source> <target>${testCompileSource}</target> <executable>${testCompileJdkPath}/bin/javac</executable> <compilerVersion>${testCompileSource}</compilerVersion> </configuration> </execution> </executions> </plugin> ... <properties> <compileSource>1.4</compileSource> <testCompileSource>1.5</testCompileSource> <compileJdkPath>path/to/jdk</compileJdkPath> <testCompileJdkPath>path/to/test/jdk<testCompileJdkPath> </properties> ``` Note it might make sense to define the compiler configurations in profiles, one for each JDK you support, so that your normal builds don't rely on properties being set. Also, **in Maven 3.x, you need to include the `fork` parameter when specifying the executable,** e.g.: ``` <plugin> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <executions> <execution> <id>default-testCompile</id> <phase>test-compile</phase> <goals> <goal>testCompile</goal> </goals> <configuration> <fork>true</fork> <executable>${testCompileJdkPath}/bin/javac</executable> <source>1.8</source> <target>1.8</target> </configuration> </execution> </executions> </plugin> ```
I had no luck with the accepted answer compiling java 7 source and java 8 test sources using the `maven-compiler-plugin`, version 3.5.1. Because the compile plugin used the source / target parameter for both, main and test sources. But I found out, there are separate configuration parameters for the test source and target. So for me the solution that worked was ``` <build> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.5.1</version> <configuration> <source>1.7</source> <target>1.7</target> <testSource>1.8</testSource> <testTarget>1.8</testTarget> </configuration> </plugin> </plugins> </build> ```
Different maven compiler versions for test and main
[ "", "java", "maven", "compiler-construction", "maven-2", "maven-3", "" ]
> **Possible Duplicate:** > [Should I use static\_cast or reinterpret\_cast when casting a void\* to whatever](https://stackoverflow.com/questions/310451/should-i-use-static-cast-or-reinterpret-cast-when-casting-a-void-to-whatever) Often, especially in Win32 programming it is required to cast from one opaque type to another. For example: ``` HFONT font = cast_here<HFONT>( ::GetStockObject( SYSTEM_FONT ) ); ``` Both static\_cast and reinterpret\_cast are applicable here and have exactly the same effect since HFONT is a pointer to a dummy struct specifically introduced for defining HFONT and HGDIOBJ returned by GetStockObject() is a void\* pointer. Which one - static\_cast or reinterpret\_cast - is preferable?
Everybody has noted that reinterpret\_cast<> is more dangerous than static\_cast<>. This is because reinterpret\_cast<> ignores all type information and just assigns a new type without any real processing, as a result the processing done is implementation defined (though usually the bit patterns of the pointers are the same). The thing everybody fails to mention is that reinterpret\_cast<> is a means to document your program. It tells somebody reading the code that we had to compromise something and as a result we have ended up with a dangerous cast, and be careful when you mess with this code. Use the reinterpret\_cast<> to highlight these dangerous areas in the code. When casting from a void\* there is not type information for the cast to work with. So you are either doing an invalid cast or a casting back to the original type that was previously cast into a void\*. Any other type of casting is going to end up with some undefined behavior. This is the perfect situation to use reinterpret\_cast<> as the standard guarantees that casting a pointer to void\* and back to its original type using reinterpret\_cast<> will work. And by using reinterpret\_cast<> you are pointing out to the humans that come along afterwords that something bad is happening here.
It's not correct to state the the casts will have the same affect. The casts do two completely different things: * `static_cast<T>(x)` says convert expression `x` to type `T`. * `reinterpret_cast<T*>(&x)` says interpret the memory location '&x' as a T\* Consider the following: ``` struct A1 { int a1; }; struct A2 { int a2; }; struct B : public A1, public A2 {}; void foo (A1 * a1, A2 * a2) { B * b1_a1 = static_cast<B*> (a1); B * b2_a1 = reinterpret_cast<B*> (a1); B * b1_a2 = static_cast<B*> (a2); B * b2_a2 = reinterpret_cast<B*> (a2); std::cout << "b1_a1==b1_a2" << (b1_a1==b1_a2) << std::endl; std::cout << "b2_a1==b2_a2" << (b2_a1==b2_a2) << std::endl; } int main () { B b; foo (&b, &b); } ``` This program results in the following output: ``` g++ -o t t.cc ; ./t b1_a1==b1_a2: 1 b2_a1==b2_a2: 0 ``` This shows how the `static_cast` from `a2` to `b2` correctly adjusted the pointer so that it points to the beginning of `b`, but the `reinterpret_cast` did not.
Which one to use when static_cast and reinterpret_cast have the same effect?
[ "", "c++", "winapi", "casting", "" ]
I want to insert n records into a single table. There may be many concurrent users and they may insert/update/select data from this table. What is better way to insert in a such table say 1000 records: 1. Send a single sql query to a database with multiple inserts. This saves server to database calls, but (I not sure) locks the table until the insert is finished and all other queries to this table will wait. 2. Divide 1000 records in some chunks and send them in multiple sql queries. This lets the other queries to be executed on the table, but spend time on server to database calls. Is this depends on something, or there is a single way that is always the optimal one? Is this depends whether transactions are used or not, while inserting data? Is there other better ways to perform a such insert? The database I use is MS SQL, but it's interesting how it works in other DB like Oracle.
This totally depends on what `RDBMS` you are using. In `Oracle`, writes never block reads, that's why you can safely put your data all at once. Note, though, that this will degrade performance, since the concurrent queries will need to fetch the data out of `UNDO` tablespace that will require extra reads. In `SQL Server` writes do block reads on affected rows / pages / tables (depending on lock escalation issues), unless you set `TRANSACTION ISOLATION LEVEL` to `SNAPSHOT`. In all transactional engines that allow concurrent writing and reading, the engine needs to store both old and new data somewhere for it to be available at the same time. In `Oracle`, old data is copied into the `UNDO` tablespace. In `SQL Server`, it gets copied into `tempdb` (only when `SNAPSHOT` isolation is enabled, otherwise it's just locked). This always requires some resources (memory or disk), and you can run out of these resources if your `UPDATE` query affects lots of rows.
I blogged about this [a while ago](http://richardod.blogspot.com/2009/03/speeding-up-sql-server-inserts-by-using.html)- I think the post answers some of your questions. CK's advise is sound (and so is Quassnoi- he has some good points about Oracle) if you are worried about readers blocking writers.
Sql insert query performance
[ "", "sql", "database", "performance", "insert", "" ]
I have a line of code that looks like this: ``` if (obj is byte || obj is int || obj is long || obj is decimal || obj is double || obj is float) ``` Is it possible to write something more elegant than this? Something like: ``` if (obj is byte, int, long) ``` I know that my example isn't possible, but is there a way to make this look "cleaner"?
You could write an extension method on object to give you syntax like: ``` if (obj.Is<byte, int, long>()) { ... } ``` Something like this (use multiple versions for fewer or more generic arguments: ``` public static bool Is<T1, T2, T3>(this object o) { return o is T1 || o is T2 || o is T3; } ```
Only: ``` static readonly HashSet<Type> types = new HashSet<Type> { typeof(byte), typeof(int), typeof(long) etc }; ... if (types.Contains(obj.GetType()) { } ``` Or use `obj.GetType().GetTypeCode()`.
If statement simplification in C#
[ "", "c#", "if-statement", "" ]
Is there a way to do this at runtime?
The standard server variables associated with IIS (`INSTANCE_ID`, `INSTANCE_META_PATH`), and `SERVER_SOFTWARE` all appear to be empty when examined from apps running on the ASP.NET Development Server. I would suggest examining their contents via `Request.ServerVariables["SERVER_SOFTWARE"]` or similar.
a bit indirect: HttpContext.Current.Request.IsLocal
How do I tell if a site is being hosted in the ASP Development Server?
[ "", "c#", "asp.net-mvc", "" ]
I need to inform a so-called worker thread to stop work at the next available oppertunity. Currently I'm using something like this: ``` public void Run() { while (!StopRequested) DoWork(); } ``` The concern I have is that StopRequested is being set to True on a different thread. Is this safe? I know I can't lock a boolean. Perhaps there's a different way to inform a thread that a stop is required. For example I would be happy to check `Thread.CurrentThread.ThreadState == ThreadState.StopRequested` but it's not clear how I can set the thread state as such.
This is a better approach than trying to set the ThreadState. If you look at the docs for [ThreadState](http://msdn.microsoft.com/en-us/library/system.threading.threadstate.aspx), it specifically says that StopRequested is for internal use only. Setting a boolean from another thread is a safe operation. You shouldn't need to lock in this case.
You may want to look at using a [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) to do the work for you, using `RunWorkerAsync()` and handling the `worker.CancellationPending == true` case during your logic. ``` BackgroundWorker worker = new BackgroundWorker(); worker.WorkerSupportsCancellation = true; worker.DoWork += MyWorkFunction; worker.RunWorkerCompleted += MyWorkDoneSuccessfullyFunction; worker.RunWorkerAsync(); ``` Another solution would be to use a volatile bool to signal that you need to stop, which you could set anywhere within the class. ``` private volatile bool cancelWork = false; public void CancelWork() { cancelWork = true; } ```
Options for informing a Thread to stop
[ "", "c#", "multithreading", "" ]
I don't know how to explain this very well, but here's a shot at it. Don't hesitate to ask for clarification, please. Suppose I have a console that displays numbers that change with certain events. The best example would be a "plane" instrument that shows altitude, direction, wind, etc. Like so: ``` Altitude: 9876ft Direction: NE Wind: 5km, NE ... ``` I only have a Windows and Linux console and I want these values to refresh themselves **in place**. Is this simple? C or C# code and any pointers would definitely help. Thanks.
The curses library is the usual way to handle this, and it is reasonably portable.
I would use [Console.SetCursorPosition](http://msdn.microsoft.com/en-us/library/system.console.setcursorposition.aspx) method for this purpose.
Refreshing values in the console
[ "", "c#", "c", "console", "" ]
I want to create a script tag by jQuery. I use the following code: ``` $("<body>").append("<script></script>"); ``` It doesn't work. What will you do to achieve it?
You should do it like so ``` var script=document.createElement('script'); script.type='text/javascript'; script.src=url; $("body").append(script); ```
To load from a url: ``` $("body").append($("<script />", { src: url })) ``` To load from existing source code: ``` $("body").append($("<script />", { html: code })) ```
Can I create script tag by jQuery?
[ "", "javascript", "jquery", "" ]
Let's say that I need to generate variables to hold some input from the user (I don't know how many they are). Without using `Array`, `ArrayList` (and other kind of lists and maps) can my code generate (lets say) `String` variables X times with names like (`String var001`, `String var002`, `String var003`, etc)? If yes, please provide sample code.
Following is the way that i have implemented and helped me to fix my solution easily without much hurdles. // Creating the array List ``` List accountList = new ArrayList(); for(int k=0;k < counter;k++){ accountList.add(k, (String)flowCtx.getValueAt("transitId"+m)); } ``` Iterating the loop and adding the objects into the arraylist with the index. //Retrieving the object at run time with the help of the index ``` String a = accountList.get(i)); ```
If you *really* want to do something like that, you can do it through bytecode generation using [ASM](http://asm.ow2.org/) or some other library. Here is code that will generate a class named "foo.bar.ClassWithFields" that contains fields "var0" to "var99". Of course there is no way other than reflection to access those fields, because they don't exist at compile time and Java is a statically typed language. ``` import org.objectweb.asm.*; import static org.objectweb.asm.Opcodes.*; import java.lang.reflect.Field; public class GeneratedFieldsExperiment { public static byte[] generateClassWithFields(int fieldCount) throws Exception { ClassWriter cw = new ClassWriter(0); FieldVisitor fv; MethodVisitor mv; AnnotationVisitor av0; cw.visit(V1_6, ACC_PUBLIC + ACC_SUPER, "foo/bar/ClassWithFields", null, "java/lang/Object", null); for (int i = 0; i < fieldCount; i++) { fv = cw.visitField(ACC_PUBLIC, "var" + i, "Ljava/lang/String;", null, null); fv.visitEnd(); } { mv = cw.visitMethod(ACC_PUBLIC, "<init>", "()V", null, null); mv.visitCode(); mv.visitVarInsn(ALOAD, 0); mv.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "<init>", "()V"); mv.visitInsn(RETURN); mv.visitMaxs(1, 1); mv.visitEnd(); } cw.visitEnd(); return cw.toByteArray(); } public static void main(String[] args) throws Exception { MyClassLoader loader = new MyClassLoader(); Class<?> c = loader.defineClass("foo.bar.ClassWithFields", generateClassWithFields(100)); System.out.println(c); System.out.println("Fields:"); for (Field field : c.getFields()) { System.out.println(field); } } private static class MyClassLoader extends ClassLoader { public Class<?> defineClass(String name, byte[] b) { return defineClass(name, b, 0, b.length); } } } ```
Is there away to generate Variables' names dynamically in Java?
[ "", "java", "dynamic", "code-generation", "names", "" ]
I need to know how to go about implementing general security for a C# application. What options do I have in this regard? I would prefer to use an existing framework if it meets my needs - I don't want to re-invent the wheel. My requirements are as follows: * the usual username/password authentication * managing of users - assign permissions to users * managing of roles - assign users to roles, assign permissions to roles * authorization of users based on their username and role I am looking for a free / open-source framework/library that has been time-tesed and used by the .Net community. My application takes a client/server approach, with the server running as a windows service, connecting to a SQL Server database. Communication between client and server will be through WCF. One other thing that is important is that I need to be able to assign specific users or roles permissions to View/Update/Delete a specific entity, whether it be a Customer, or Product etc. For e.g. Jack can view a certain 3 of 10 customers, but only update the details of customers Microsoft, Yahoo and Google, and can only delete Yahoo.
For coarse-grained security, you might find the inbuilt principal code useful; the user object (and their roles) are controlled in .NET by the "principal", but usefully the runtime itself can enforce this. The implementation of a principal can be implementation-defined, and you can usually inject your own; [for example in WCF](http://www.leastprivilege.com/CustomPrincipalsAndWCF.aspx). To see the runtime enforcing coarse access (i.e. which *functionality* can be accessed, but not limited to which specific *data*): ``` static class Roles { public const string Administrator = "ADMIN"; } static class Program { static void Main() { Thread.CurrentPrincipal = new GenericPrincipal( new GenericIdentity("Fred"), new string[] { Roles.Administrator }); DeleteDatabase(); // fine Thread.CurrentPrincipal = new GenericPrincipal( new GenericIdentity("Barney"), new string[] { }); DeleteDatabase(); // boom } [PrincipalPermission(SecurityAction.Demand, Role = Roles.Administrator)] public static void DeleteDatabase() { Console.WriteLine( Thread.CurrentPrincipal.Identity.Name + " has deleted the database..."); } } ``` However, this doesn't help with the fine-grained access (i.e. "Fred can access customer A but not customer B"). --- Additional; Of course, for fine-grained, you can simply check the required roles at runtime, by checking `IsInRole` on the principal: ``` static void EnforceRole(string role) { if (string.IsNullOrEmpty(role)) { return; } // assume anon OK IPrincipal principal = Thread.CurrentPrincipal; if (principal == null || !principal.IsInRole(role)) { throw new SecurityException("Access denied to role: " + role); } } public static User GetUser(string id) { User user = Repository.GetUser(id); EnforceRole(user.AccessRole); return user; } ``` You can also write your own principal / identity objects that do lazy tests / caching of the roles, rather than having to know them all up-front: ``` class CustomPrincipal : IPrincipal, IIdentity { private string cn; public CustomPrincipal(string cn) { if (string.IsNullOrEmpty(cn)) throw new ArgumentNullException("cn"); this.cn = cn; } // perhaps not ideal, but serves as an example readonly Dictionary<string, bool> roleCache = new Dictionary<string, bool>(); public override string ToString() { return cn; } bool IIdentity.IsAuthenticated { get { return true; } } string IIdentity.AuthenticationType { get { return "iris scan"; } } string IIdentity.Name { get { return cn; } } IIdentity IPrincipal.Identity { get { return this; } } bool IPrincipal.IsInRole(string role) { if (string.IsNullOrEmpty(role)) return true; // assume anon OK lock (roleCache) { bool value; if (!roleCache.TryGetValue(role, out value)) { value = RoleHasAccess(cn, role); roleCache.Add(role, value); } return value; } } private static bool RoleHasAccess(string cn, string role) { //TODO: talk to your own security store } } ```
my answer is probably dependent upon the answer to this question: ***Is this an Enterprise application which lives within a network with Active Directory?*** IF the answer is yes, then these are the steps I would provide: 1) Create Global Groups for your application, in my case, I had a APPUSER group and an APPADMIN group. 2) Have your SQL Server be able to be accessed in MIXED AUTHENTICATION mode, and then assign your APPUSER group(s) as the SQL SERVER LOGIN to your database with the appropriate CRUD rights to your DB(s), and ensure that you access the SQL SERVER with **Trusted Connection = True** in your connection string. At this point, your AD store will be responsible for authentication. Since, you're accessing the application via a TRUSTED CONNECTION, it will pass the identity of whatever account is running the application to the SQL Server. Now, for AUTHORIZATION (i.e. telling your application what the logged in user is allowed to do) it's a simple matter of querying AD for a list of groups which the logged in user is a member of. Then check for the appropriate group names and build your UI based upon membership this way. The way my applications work are thus: 1. Launching the application, credentials are based upon the logged-in user, this is the primary aspect of authentication (i.e. they can log in therefore they exist) 2. I Get all Groups For the Windows Identity in question 3. I check for the Standard USER Group -- if this group does not exist for the Windows Identity in question, then that's an authentication FAIL 4. I check for ADMIN User Group -- With this existing in the user's groups, I modify the UI to allow access to administration components 5. Display the UI I then have either a PRINCIPLE object with the determined rights/etc on it, or I utilize GLOBAL variables that I can access to determine the appropriate UI while building my forms (i.e. if my user is not a member of the ADMIN group, then I'd hide all the DELETE buttons). Why do I suggest this? It's a matter of deployment. It has been my experience that most Enterprise Applications are deployed by Network Engineers rather than programmers--therefore, having Authentication/Authorization to be the responsibility of AD makes sense, as that is where the Network guys go when you discuss Authentication/Authorization. Additionally, during the creation of new users for the network, a Network Engineer (or whoever is responsible for creating new network users) is more apt to remember to perform group assignments while they are IN AD than the fact that they have to go into a dozen applications to parse out assignments of authorization. Doing this helps with the maze of permissions and rights that new hires need to be granted or those leaving the company need to be denied and it maintains authentication and authorization in the central repository where it belongs (i.e. in AD @ the Domain Controller level).
Authentication, Authorization, User and Role Management and general Security in .NET
[ "", "c#", "security", "authorization", "roles", "" ]
I have just noticed that Sql Profiler 2008 is not hiding trace outputs that include sp params called password. In 2005 it used to give me a message saying "The text has been replaced with this comment for security reasons". Has they removed this security feature?
There is a difference between trapping the string "password" and genuine security holes. Try this: ``` CREATE LOGIN foo WITH PASSWORD = 'bar' ``` In SQL 2005 profiler: ``` --*CREATE LOGIN----------------------- ``` Security is maintained. Now, if you're sending dynamic SQL to a password columns...
But if you pass your passwords as parameters, it should display it. The solution should be storing passwords encrypted at database. By this solution you'll need to pass your passwords encrypted.
SQL Profiler 2008 - Shows Passwords
[ "", "sql", "sql-server-2008", "sql-server-profiler", "" ]
I recently wrote a node-based stack class, per instructions (specs in the comments before the code, taken from the forum post). I was told to post it here for review by one of the friendlier members of the SO community, so here it is. For simplicity's sake: I put the definitions with the implementation. I understand when to use header files =) Mainly, I want to know if my use of delete is sound. I am still unsure of myself when it comes to using destructors; the specs made it sound like the ONLY time I should be deleting nodes should be during pop, and anything else is unsafe. I also don't understand the use of a copy constructor/assignment constructor here. Anyways, any bugs or comments about the code would be great. ``` /*stack class Background: the specs for this are, verbatim: "Write a node-based stack class smile.gif The stack is one of the most fundamental data structures used in computer science. A stack has three basic operations: push(value) - puts a value on the top of the stack pop() - removes and returns the value that's on the top of the stack peek() - return (but does not remove) the value off the top of the stack Before creating the stack, you first have to create a Node class, which is a very basic class with just two member variables: the value of the node, and a pointer to the previous node in the stack. Your stack should have only one member variable: the top node of the stack. When you push, you add a node with the new value, with it's previous pointer pointing towards the current stack top item. When you pop, you delete the top node and then set the top of the stack to whatever that node's previous node pointer was. push, pop, and peek must all run in constant time. You should write it so that it can only push (and pop/peek) ints." */ #include <string> #include <iostream> class Node { private: int value; Node* prev; public: int returnValue() { return value; } Node* returnPtr() { return prev; } /* constructors and destructors */ Node(int val, Node* ptrToLast) { value = val; prev = ptrToLast; } }; class Stack { private: Node* top; int size; public: Stack() { size = 0; top = NULL; } //added this after told the need for a destructor; not sure if it works ~Stack() { while (top != NULL) { Node* tempPtr = top.returnPtr(); delete top; top = tempPtr; } } Node* returnTopPtr() { return top; } void push(int); int pop(); int peek(); //bonus; figured it might be worth knowing how many //nodes are in a given stack int returnSize(); }; int Stack::returnSize() { return size; } void Stack::push(int value) { ++size; Node* tempPtr = top; top = new Node(value, tempPtr); } int Stack::peek() { return top->returnValue(); } int Stack::pop() { const std::string throwStr = "You are trying to access/delete a node that doesn't exist. Seriously. "; if (size == 0) { throw(throwStr); } --size; Node* tempPtr = top->returnPtr(); int tempVal = top->returnValue(); delete top; top = tempPtr; return tempVal; } ```
**First**, a few general comments which don't cause problems in this case, but some may do so in other situations: You should only throw exceptions derived from the class `std::exception`. C++ does allow you to throw any type (like a string, in your case), but it's a really bad idea. Class members should be initialized with initializer lists, as shown below: (this can cause errors in other cases. If you don't use the initializer list, the members are first default-constructed, and then the assignment operator is used in the body of the constructor to overwrite them. Not all types have an assigment operator, or the assignment operator may have undesirable side effects, so not using initializer lists can be problematic) ``` Node(int val, Node* ptrToLast) : value(val), prev(ptrToLast) {} Stack() : size(0), top(NULL) {} ``` Naming your functions `return*` us pretty pointless. Just call them `size()` and `topPtr()`, or perhaps `getSize()` and `getTopPtr()` **Second**, you didn't follow the rules. ;) Your stack class has two member variables, it was only allowed to have one. :) **Finally**, things that break the stack: This will crash, as you try to dereference a null pointer: ``` void test() { Stack s; s.peek(); // crashes } ``` This will leak memory, as the allocated node is never deleted (the Stack destructor should do that): ``` void test() { Stack s; s.push(1); } ``` The destructor should look something like this: ``` ~Stack() { while (top != NULL){ Node* next = top.returnPtr(); delete top; top = next; } } ``` This one should be fun too: ``` void test() { Stack s; s.push(1); Stack t(s); s.pop(); } ``` `t.returnSize()` will now return 1, but `t.top` points to the node in `s` that was just deleted. This should be fixed by defining a copy constructor and an assigment operator for the stack (and perhaps for the node class as well) The copy constructor would look like this: ``` Stack(const Stack& s); ``` and is called if you *initialize* one stack from another, like in the above. The assignment operator looks like this: ``` Stack& operator= (const Stack& s); ``` and is called if I assign one stack to another, after both are initialized: ``` Stack s; Stack t; t = s; // now both are already initialized, so the assigment operator is used, not the copy constructor ``` The role of these functions is to ensure that t becomes a *copy* of `s`. So each node in `s` should be copied, and assigned to `t`, to avoid them pointing to the same nodes. (Which is a wonderful example of your question about ownership earlier, btw. The nodes should belong to exactly one Stack object. If it becomes shared between multiple, you have a problem, and it's just a matter of time before it turns into a crash) And finally, if we want to get a bit nastier: ``` void test() { Stack s; s.push(1); s.push(2); } ``` What happens if the memory allocation for the second node fails (perhaps we ran out of memory. Unlikely, but it can happen). An exception is thrown *after* you incrmented size. The size of s will now be 2, even though `top` still points to the first node If you think this is too unlikely a problem to be taken seriously, imagine a small extension to your class. Let's say it was a template, so that it could store other types than an int. That means that every time we create a node, we have to call the value type's copy constructor. That could throw an exception too. We don't know, because we have no clue which type the user might try to store in the stack. The notion of "Exception safety" is important and really really difficult to get right. Basically, which state is your class in if an exception is thrown? Is it still in a valid state? (it should always be). Has it lost any data (for some cases that might be unavoidable, for others it can be avoided with care), and if it has lost data, has it been deleted correctly? Destructors called, memory released? (again, this should always be the case) The last point here is why I was so sure you'd have at least one bug. Everyone gets exception safety wrong, including me most of the time. Writing a *correct* implementation of sometihng as simple as a stack is surprisingly difficult in C++. :) **Bonus:** In response to comments asking about copy constructors, destructors and RAII, let's just do the whole thing: First, let me say that there is probably one or two bugs left I haven't spotted. Second, here's the code I tested against, and all the following passes it. Feel free to run your own code through it as well. (it should work as is, except you'll have to rename the `getSize` function): (the `live` variable is one I added for debugging. I've modified my Stack implementations so that constructors increment it, and destructors decrement it, just to verify that the number of constructions and destructions are equal. This should obviously be removed from the Stack class once you're sure it works ## Test code ``` static int live; // debugging - keeps track of how many nodes have been allocated. Constructors add 1, destructors subtract. It should end in 0 #include "stack.h" #include <iostream> #include <cassert> int main(){ { // test stack creation + push Stack s; s.push(1); s.push(2); s.push(3); assert(s.getSize() == 3); Stack t; t.push(4); t.push(5); t.push(6); assert(t.getSize() == 3); // test assigment operator when both stacks contain data s = t; assert(s.getSize() == 3); assert(s.peek() == 6); assert(t.peek() == 6); Stack u(s); // test self assigment when stack contains data u = u; assert(u.getSize() == 3); assert(u.peek() == 6); Stack v; // test copy construction from stack with data Stack w(t); assert(w.getSize() == 3); assert(w.peek() == 6); assert(t.getSize() == 3); assert(t.peek() == 6); // test assignment operator when source is empty, destination contains data w = v; assert(w.getSize() == 0); assert(v.getSize() == 0); // test copy construction from empty stack Stack x(v); assert(x.getSize() == 0); assert(v.getSize() == 0); // test pop assert(t.pop() == 6); assert(t.pop() == 5); assert(t.pop() == 4); assert(s.pop() == 6); assert(s.pop() == 5); assert(s.pop() == 4); } // at this point, all allocated stacks go out of scope, so their destructors are called, so now is a good time to check for memory leaks: assert(live == 0); } ``` --- ## Fixed implementation Now, first the straightforward fix. Copy constructor, assignment operator and destructor have been added on the Stack class. The Node class is still problematic if used in isolation, but as long as it is only used through the Stack, we can make sure nodes get copied and deleted properly. Unfortunately, `Stack` now needs access to `Node.tail_` in order for copying to work, so I made it a friend. So it works, but it's not elegant. ``` #include <stdexcept> // for std::exception class Stack; class Node { private: // changed naming to head/tail, which are commonly used in implementations of linked lists like this. The head is the current element, tail is a pointer to the remainder int head_; Node* tail_; public: friend class Stack; // this is necessary for the Stack copy constructor in order to modify the tail pointer after the node is created. // the elegant solution had been to define a copy constructor on the Node class as well, but we'll get to that int head() const { return head_; } Node* tail() const { return tail_; } Node(int val, Node* prev) : head_(val), tail_(prev) { ++live; } // use initializer list ~Node() { --live; } Node(const Node& other) : head_(other.head_), tail_(other.tail_){ ++live; }; // this could be omitted, but I use it to update 'live' for debugging purposes }; class Stack { private: Node* top; // int size; // we don't actually need the size at all, according to spec, so I removed it to keep things simple bool empty() const { return top == NULL;} void freeNodes() { // helper function to avoid duplicate code while (!empty()){ pop(); } } public: Stack() : top() {} // use initializer list ~Stack() { // destructor - the stack is being deleted, make sure to clean up all nodes freeNodes(); } Stack(const Stack& other) : top() { // copy constuctor - we're being initialized as a copy of another stack, so make a copy of its contents if (other.empty()){ return; } top = new Node(*other.top); // copy the first node, to get us started Node* otherNext = other.top->tail(); Node* current = top; while (otherNext != NULL){ current->tail_ = new Node(*otherNext); // copy the current node current = current->tail(); // move to the next node otherNext = otherNext->tail(); } } Stack& operator= (const Stack& other) { if (this == &other){ // If we assign this stack to itself (s = s), bail out early before we screw anything up return *this; } //now create the copy try { if (other.empty()){ freeNodes(); top = NULL; return *this; } // naively, we'd first free our own stack's data before constructing the copy // but what happens then if an exception is thrown while creating the copy? We've lost all the current data, so we can't even roll back to a previous state // so instead, let's simply construct the copy elsewhere // this is almost straight copy/paste from the copy constructor. Should be factored out into a helper function to avoid duplicate code Node* newTop = new Node(*other.top); // copy the first node, to get us started Node* otherNext = other.top->tail(); Node* current = newTop; while (otherNext != NULL){ current->tail_ = new Node(*otherNext); // copy the current node current = current->tail(); // move to the next node otherNext = otherNext->tail(); } // once we're sure that we're able to create the copy of the other stack, we're ready to free the current one // this is a bit of duplicate code freeNodes(); top = newTop; return *this; } catch (...){ // if an exception was thrown throw; // and rethrow the exception so the application can deal with it } } // Node* returnTopPtr() { return top; } // not necessary. It's not a required part of the public interface, and class members can just access the top variable directly void push(int); int pop(); int peek() const; int getSize() const{ if (empty()){ return 0; } int i = 0; for (Node* cur = top; cur != NULL; cur = cur->tail_, ++i){} return i; } }; void Stack::push(int value) { Node* currentTop = top; top = new Node(value, currentTop); // this could throw an exception, but if it does, our stack will simply be left unchanged, so that's ok } int Stack::peek() const { if (empty()){ throw std::exception("Stack is empty"); } return top->head(); } int Stack::pop() { if (empty()){ throw std::exception("Stack is empty"); } Node* tail = top->tail(); int result = top->head(); delete top; top = tail; return result; } ``` --- ## RAII v. 1 [RAII](http://en.wikipedia.org/wiki/RAII) is a lousy name for a vital technique. The basic idea is that every resource allocation (including, but not limited to, memory allocations with `new`.) should be wrapped in a class which takes care of copying or deleting the resource as necessary. In our case, rather than having `Stack` keep track of all the nodes, we could simplify things a bit by making the `Node` class itself do most of that work. Now `Node` has been given copy constructor, assignment operator and destructor too. The stack now just has to keep track of the `top` node... almost. It is still a bit iffy because `Stack.push` allocates new nodes, but `Node` is now responsible for most of the deletions. . However, it does allow us to get rid of the loops we needed before to delete or copy the node list. `Stack still needs to access the`tail\_`member of`Node`, but this time, I made an accessor function instead of making the class a member. Overall, better, but I'm still not happy with it. ``` #include <stdexcept> class Node { private: int head_; Node* tail_; public: int head() const { return head_; } Node* tail() const { return tail_; } Node*& tail() { return tail_; } // Another way to allow Stack to modify the tail. Needed for pop() Node(int val, Node* prev = NULL) : head_(val), tail_(prev) { ++live; } ~Node(){ --live; delete tail_; } // it is safe to call delete on a NULL pointer Node(const Node& other) : head_(other.head()), tail_(NULL) { ++live; if (other.tail() == NULL){ return; } tail_ = new Node(*other.tail()); } Node& operator= (const Node& other){ if (this == &other){ return *this; } head_ = other.head(); if (other.tail() != NULL){ return *this; } Node* oldTail = tail_; try { tail_ = new Node(*other.tail()); } catch(...){ tail_ = oldTail; throw; } } }; class Stack { private: Node* top; bool empty() const { return top == NULL;} public: Stack() : top() {} ~Stack() { delete top; } Stack(const Stack& other) : top(){ if (other.empty()){ return; } top = new Node(*other.top); } Stack& operator= (const Stack& other) { if (this == &other){ return *this; } Node* oldTop = top; try { top = NULL; if (other.top != NULL){ top = new Node(*other.top); } delete oldTop; return *this; } catch (...){ delete top; top = oldTop; throw; } } void push(int); int pop(); int peek() const; int getSize() const{ if (empty()){ return 0; } int i = 0; for (Node* cur = top; cur != NULL; cur = cur->tail(), ++i){} return i; } }; void Stack::push(int value) { Node* currentTop = top; top = new Node(value, currentTop); } int Stack::peek() const { if (empty()){ throw std::exception("Stack is empty"); } return top->head(); } int Stack::pop() { if (empty()){ throw std::exception("Stack is empty"); } Node* tail = top->tail(); int result = top->head(); if (top != NULL){ top->tail() = NULL; // detach top from the rest of the list delete top; } top = tail; return result; } ``` --- ## RAII v.2 To solve the problems mentioned above, I decided to change my strategy a bit. `Node` now does all the heavy lifting, *including* the push/pop/peek operations. `Stack` is simply a thin wrapper around these. This turned out to solve most of the problems. `Stack` no longer needs to mess around with private members of `Node`, and we have some clearer rules for ownership. The stack owns the top node, and every non-top node is owned by its parent -- and this time, the owner *both* creates, copies and destroys the node. Much more consistent. To implement this, I had to add an `isLast` function on the Node class because otherwise, `Stack.pop` had no way of knowing whether or not it was time to delete `top`. I'm not 100% happy with this solution either (and if I hadn't removed the size member from the stack, I could have used that to solve the problem) But overall, this one is both cleaner and simpler than the above attempts. (It's the only one I spent less than an hour debugging, for one thing. ;)) ``` #include <stdexcept> class Node { public: Node(int value, Node* prev = 0) : head(value), tail(prev) { ++live;} ~Node() { --live; delete tail; } Node(const Node& other) : head(other.head), tail(0) { ++live; if (other.tail != 0){ tail = new Node(*other.tail); } } Node& operator= (const Node& other){ if (this == &other){ return *this; } Node* oldTail = tail; tail = new Node(*other.tail); delete oldTail; head = other.head; return *this; } void push(int val){ tail = new Node(head, tail); head = val; } int peek(){ return head; } void pop(){ Node* oldTail = tail; head = tail->head; tail = tail->tail; // lol oldTail->tail = 0; delete oldTail; } bool isLast() { return tail == NULL; } int getSize() const{ int i = 0; for (const Node* cur = this; cur != NULL; cur = cur->tail, ++i){} return i; } private: Node* tail; int head; }; class Stack { public: Stack() : top(){} ~Stack() { delete top; } Stack(const Stack& other) : top() { if (other.empty()){ return; } top = new Node(*other.top); } Stack& operator= (const Stack& other){ if (this == &other){ return *this; } Node* newTop = NULL; if (!other.empty()){ newTop = new Node(*other.top); } delete top; top = newTop; return *this; } void push(int val){ if (empty()) { top = new Node(val); } else { top->push(val); } } int peek(){ if (empty()){ throw std::exception("Empty stack"); } return top->peek(); } int pop(){ int result = peek(); if (top->isLast()){ delete top; top = NULL; } else { top->pop(); } return result; } int getSize() const{ if (empty()){ return 0; } return top->getSize(); } private: bool empty() const { return top == NULL; } Node* top; }; ``` Since all this started as an attempt to show you why C++ isn't a very nice beginners language, I think I can safely say **mission accomplished!** :)
Alright - so here's a quick review. Keep in mind that somethings will be my personal opinion (just like the comment I wrote.) 1 - whenever accessing a value or method that you have a pointer into, check if the pointer is valid first! This will cause you to seg-fault otherwise. For example, if you peek before pushing a node in, you call NULL->returnValue(). This is no good. 2 - you don't need the temp pointer you are using in the push & you should check if you are being able to successfully allocate memory. 3 - you need a copy constructor / destructor because your object manages dynamically allocated data. So what happens is that by default, c++ only copies your static values when copying an object & only dealocates memory for static variables when destructing the object. A copy constructor & a destructor makes sure you go through your dynamic memory & take care of it. (IE: for the destructor you want to delete each node.) 4 - returnTopPointer is a horrible idea - it gives people access to your internal data & lets them do whatever they want. If you need help with the copy constructor & destructor just let us know.
Node-based stack class (need peer review)
[ "", "c++", "stack", "" ]
Is there a simple and quick way to use sum() with non-integer values? So I can use it like this: ``` class Foo(object): def __init__(self,bar) self.bar=bar mylist=[Foo(3),Foo(34),Foo(63),200] result=sum(mylist) # result should be 300 ``` I tried overriding `__add__` and `__int__` etc, but I don't have found a solution yet **EDIT:** The solution is to implement: ``` def __radd__(self, other): return other + self.bar ``` as Will suggested in his post. But as always, all roads lead to Rome, but I think this is the best solution since I don't need `__add__` in my class
Its a bit tricky - the sum() function takes the start and adds it to the next and so on You need to implement the `__radd__` method: ``` class T: def __init__(self,x): self.x = x def __radd__(self, other): return other + self.x test = (T(1),T(2),T(3),200) print sum(test) ```
You may also need to implement the `__radd__` function, which represents "reverse add" and is called when the arguments can't be resolved in the "forward" direction. For example, `x + y` is evaluated as `x.__add__(y)` if possible, but if that doesn't exist then Python tries `y.__radd__(x)`. Since the `sum()` function starts with the integer `0`, the first thing it does is try to evaluate: ``` 0 + Foo(3) ``` which will require that you implement `Foo.__radd__`.
python's sum() and non-integer values
[ "", "python", "list", "sum", "" ]
I'm developing a service that needs to be scalable in Windows platform. Initially it will receive aproximately 50 connections by second (each connection will send proximately 5kb data), but it needs to be scalable to receive more than 500 future. It's impracticable (I guess) to save the received data to a common database like Microsoft SQL Server. Is there another solution to save the data? Considering that it will receive more than 6 millions "records" per day. There are 5 steps: 1. Receive the data via http handler (c#); 2. Save the received data; **<- HERE** 3. Request the saved data to be processed; 4. Process the requested data; 5. Save the processed data. **<- HERE** My pre-solution is: 1. Receive the data via http handler (c#); 2. Save the received data to **Message Queue**; 3. Request from **MSQ** the saved data to be processed using a windows services; 4. Process the requested data; 5. Save the processed data to **Microsoft SQL Server** (here's the bottleneck);
6 million records per day doesn't sound particularly huge. In particular, that's *not* 500 per second for 24 hours a day - do you expect traffic to be "bursty"? I wouldn't *personally* use message queue - I've been bitten by instability and general difficulties before now. I'd probably just write straight to disk. In memory, use a producer/consumer queue with a single thread writing to disk. Producers will just dump records to be written into the queue. Have a separate batch task which will insert a bunch of records into the database at a time. Benchmark the optimal (or at least a "good" number of records to batch upload) at a time. You may well want to have one thread reading from disk and a separate one writing to the database (with the file thread blocking if the database thread has a big backlog) so that you don't wait for both file access and the database at the same time. I suggest that you do some tests nice and early, to see what the database can cope with (and letting you test various different configurations). Work out where the bottlenecks are, and how much they're going to hurt you.
I think that you're prematurely optimizing. If you need to send everything into a database, then see if the database can handle it before assuming that the database is the bottleneck. If the database can't handle it, then maybe turn to a disk-based queue like Jon Skeet is describing.
Is there a fast and scalable solution to save data?
[ "", "c#", "asp.net", "scalability", "" ]
I was pleasantly surprised a few months ago to learn that I could use many C# 3.x constructs (anonymous types, lambdas, automatic properties) in .NET 2.0, due to the fact that they all compile to the same IL...in effect, syntactic sugar. Is this also the case of LINQ and XLINQ? Can i use these constructs while still targeting .NET 2.0 runtimes?
For info, much of the core of LINQ is available in .NET 2.0 (with C# 3.0) via (for example) [LINQBridge](http://www.albahari.com/nutshell/linqbridge.aspx). This gives you most of LINQ-to-Objects (allowing query syntax against in-memory collections/iterators), but it **doesn't** provide the new assemblies required for LINQ-to-XML or LINQ-to-SQL etc. So no; you can't use `XDocument` without the new assemblies from .NET 3.5; but you can do *many* LINQ things.
LINQ is a set of extension methods defined in the System.Core assembly which is part of .NET Framework 3.5. So in order to use LINQ and LINQ to XML you will need to have .NET Framework 3.5 installed on the target machine because your application will have a static dependency on this assembly. There's a nice [diagram](http://www.hanselman.com/blog/content/binary/WindowsLiveWriter/HowtosetanIISApplicationtouseASP.NET3.5_9C2E/image_6.png) showing what's included in different versions of the framework.
Is XLINQ available with .NET 2.0SP1
[ "", "c#", "linq", "linq-to-xml", "" ]