Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I am learning Java, theres one thing I do not understand..
in the main routine:
```
public static void main(String[] args) {
```
I think I pretty much understand this, in the language I know, I think it would be like this:
```
public static function main(args:String):void {
```
The first thing I do not understand is what are the 2 brackets [] for in String[]? Also the second thing I am wondering, is if this is the first function that will be called (and called by something outside the program), will there ever actually be a parameter passed?
Thanks. | The arguments to main are the options you pass into Java from the command line, passed in as an array. So for example :
```
java MyProgram foo bar zoo
```
takes three arguments, namely, foo, bar, and zoo
foo is args[0], bar is args[1], and zoo is args[2]. | Brackets mean [array](http://en.wikipedia.org/wiki/Array_data_type). E.g. `String[]` is an array of strings. The `main()`-function is the first function called in your program. It gets called by the [JVM](http://en.wikipedia.org/wiki/JVM).
The values in `String[] args` are the parameters passed on the command line.
If you call a Java program (main class: `FooBar` in package `foo.bar`) like that:
```
java foo.bar.FooBar foo bar buz
```
then, `args` will like if you built it like that:
```
String[] args = new String[3];
args[0] = "foo";
args[1] = "bar";
args[2] = "buz";
```
That is possibly worth reading: [A Closer Look at the "Hello World" Application](http://java.sun.com/docs/books/tutorial/getStarted/application/index.html) | Java public static main() | [
"",
"java",
""
] |
I am trying to get the ID field name (property name) of an entity, is it possible?
User user= new User(); //User is an Entity
string idField = ??????? //user.UserId | If you can get the EntitySet, or the EntityType, for the entity, then you can use the KeyMembers property:
```
public IEnumerable<string> GetIdProperties(EntitySetBase entitySet)
{
return GetIdProperties(entitySet.ElementType);
}
public IEnumerable<string> GetIdProperties(EntityTypeBase entityType)
{
return from keyMember in entityType.KeyMembers
select keyMember.Name
}
```
You can obtain a generic object set from the context:
```
public ObjectSet<TEntity> GetEntitySet<TEntity>(ObjectContext context)
{
return context.CreateObjectSet<TEntity>();
}
``` | ```
public static IEnumerable<string> GetIdFields<TEntity>() where TEntity
: EntityObject
{
var ids = from p in typeof(TEntity).GetProperties()
where (from a in p.GetCustomAttributes(false)
where a is EdmScalarPropertyAttribute &&
((EdmScalarPropertyAttribute)a).EntityKeyProperty
select true).FirstOrDefault()
select p.Name;
return ids;
}
public static string GetIdField<TEntity>() where TEntity : EntityObject
{
IEnumerable<string> ids = GetIdFields<TEntity>();
string id = ids.Where(s => s.Trim().StartsWith(typeof(TEntity).Name.
Trim())).FirstOrDefault();
if (string.IsNullOrEmpty(id)) id = ids.First();
return id;
}
```
You could merge both funcs into one or set your search conditions. | Is there a way to get entity id-field's name by reflection or whatever? | [
"",
"c#",
".net",
"entity-framework",
"reflection",
"propertyinfo",
""
] |
I'm having some trouble with finding the visibility param for JQuery.
Basically... the code below does nothing.
```
$('ul.load_details').animate({
visibility: "visible"
},1000);
```
There's nothing wrong with the animate code (I replaced visibility with fontSize and it was fine. I just can't seem to find the correct param name equivalent for "visibility" in css. | You could set the opacity to 0.0 (i.e. "invisible") and visibility to visible (to make the opacity relevant), then animate the opacity from 0.0 to 1.0 (to fade it in):
```
$('ul.load_details').css({opacity: 0.0, visibility: "visible"}).animate({opacity: 1.0});
```
Because you set the opacity to 0.0, it's invisible despite being set to "visible". The opacity animation should give you the fade-in you're looking for.
Or, of course, you could use the `.show()` or `.fadeTo()` animations.
EDIT: *Volomike* is correct. CSS of course specifies that `opacity` takes a value between 0.0 and 1.0, not between 0 and 100. Fixed. | Maybe you are just looking to show or hide an element:
```
$('ul.load_details').show();
$('ul.load_details').hide();
```
Or do you want to show/hide element using animation (this doesn't make sense of course as it will not fade):
```
$('ul.load_details').animate({opacity:"show"});
$('ul.load_details').animate({opacity:"hide"});
```
Or do you want to really fade-in the element like this:
```
$('ul.load_details').animate({opacity:1});
$('ul.load_details').animate({opacity:0});
```
Maybe a nice tutorial will help you get up to speed with jQuery:
<http://www.webdesignerwall.com/tutorials/jquery-tutorials-for-designers/> | Fading visibility of element using jQuery | [
"",
"javascript",
"jquery",
"css",
""
] |
I have a set of source folders. I use a Java class to build the distribution file out of these folders. I'd like to write another little class in Java which runs every half a second, checks if any of the files in the folders have changed, and if yes, run the building class.
So, how do I detect easily that a folder has been modified ? | I think you will need to check the directory and subdirectory modfication times (for files being added/removed) and the file modification times (for the changes in each file).
Write a recursive routine that checks a directory for it's modification time and if it's changed, plus each files. Then checks the directory contents, and call recursively for any subdirectories. You should just be able to check for any modification times greater than when you last ran the check.
See [File.lastModified()](http://java.sun.com/javase/6/docs/api/java/io/File.html#lastModified%28%29)
EDIT: Since I wrote the above, Java 7 came out with its [directory watching capability](http://docs.oracle.com/javase/tutorial/essential/io/notification.html). | If you can are allowed to use Java 7, it has support for platform independent directory/file change notifications.
JNA has a sample for cross platform change notification [here](https://jna.dev.java.net/source/browse/jna/trunk/jnalib/src/com/sun/jna/examples/FileMonitor.java?rev=HEAD&view=markup). Not sure how easy you might find it. | What is the easiest way to track a change in a folder in Java? | [
"",
"java",
"directory",
""
] |
Background: I am writing a C++ program working with large amounts of geodata, and wish to load large chunks to process at a single go. I am constrained to working with an app compiled for 32 bit machines. The machine I am testing on is running a 64 bit OS (Windows 7) and has 6 gig of ram. Using MS VS 2008.
I have the following code:
```
byte* pTempBuffer2[3];
try
{
//size_t nBufSize = nBandBytes*m_nBandCount;
pTempBuffer2[0] = new byte[nBandBytes];
pTempBuffer2[1] = new byte[nBandBytes];
pTempBuffer2[2] = new byte[nBandBytes];
}
catch (std::bad_alloc)
{
// If we didn't get the memory just don't buffer and we will get data one
// piece at a time.
return;
}
```
I was hoping that I would be able to allocate memory until the app reached the 4 gigabyte limit of 32 bit addressing. However, when nBandBytes is 466,560,000 the new throws std::bad\_alloc on the second try. At this stage, the working set (memory) value for the process is 665,232 K So, it I don't seem to be able to get even a gig of memory allocated.
There has been some mention of a 2 gig limit for applications in 32 bit Windows which may be extended to 3 gig with the /3GB switch for win32. This is good advice under that environment, but not relevant to this case.
How much memory should you be able to allocate under the 64 bit OS with a 32 bit application? | As much as the OS wants to give you. By default, Windows lets a 32-bit process have 2GB of address space. And this is split into several chunks. One area is set aside for the stack, others for each executable and dll that is loaded. Whatever is left can be dynamically allocated, but there's no guarantee that it'll be one big contiguous chunk. It might be several smaller chunks of a couple of hundred MB each.
If you compile with the LargeAddressAware flag, 64-bit Windows will let you use the full 4GB address space, which should help a bit, but in general,
* you shouldn't assume that the available memory is contiguous. You should be able to work with multiple smaller allocations rather than a few big ones, and
* You should compile it as a 64-bit application if you need a lot of memory. | on windows 32 bit, the normal process can take 2 GB at maximum, but with [/3GB](http://technet.microsoft.com/en-us/library/bb124810.aspx) switch it can reach to 3 GB (for windows 2003).
but in your case I think you are allocating contiguous memory, and so the exception occured. | How much memory should you be able to allocate? | [
"",
"c++",
"new-operator",
"dynamic-memory-allocation",
""
] |
I am serving images through php and having some problems setting it up to respond with 304 headers to save on load time.
Most of the code below I found on php.net. It works, however ALWAYS responds with 200. **For some reason the If-Modified-Since header is not being received on any requests even though I am sending the Last-Modified header initially.** This is being done on an apache server. Any idea what might be wrong?
[Example here.](http://louiswalch.com/beta/304_test/)
This page will load the image from disk and display it to browser, along with sending a Last-Modified header. If you refresh the page, the browser doesn't send a If-Modified-Since header like it should.
```
define('SITEPATH', (dirname($_SERVER['SCRIPT_NAME']) == '/') ? '/' : dirname($_SERVER['SCRIPT_NAME']).'/');
$load_path = $_SERVER['DOCUMENT_ROOT'] . SITEPATH . 'fpo_image.jpg';
// Get headers sent by the client.
$headers = apache_request_headers();
$file_time = filemtime($load_path);
header('Cache-Control: must-revalidate');
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $file_time).' GMT');
if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) == $file_time)) {
header('HTTP/1.1 304 Not Modified');
header('Connection: close');
} else {
header('HTTP/1.1 200 OK');
header('Content-Length: '. filesize($load_path));
header('Content-type: image/jpeg');
readfile($load_path);
}
``` | I believe it should be
```
if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) >= $file_time)) {
```
Checking if the modified time is greater than or equal rather than just equal. Although I do understand the two values *should* be the same. | **mandor at mandor dot net** [posted a solution](http://us.php.net/manual/en/function.header.php#61903) at the PHP.net documentation for the header function which worked for me:
```
<?php
// Test image.
$fn = '/test/foo.png';
// Getting headers sent by the client.
$headers = apache_request_headers();
// Checking if the client is validating his cache and if it is current.
if (isset($headers['If-Modified-Since']) && (strtotime($headers['If-Modified-Since']) == filemtime($fn))) {
// Client's cache IS current, so we just respond '304 Not Modified'.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 304);
} else {
// Image not cached or cache outdated, we respond '200 OK' and output the image.
header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($fn)).' GMT', true, 200);
header('Content-Length: '.filesize($fn));
header('Content-Type: image/png');
print file_get_contents($fn);
}
?>
``` | Caching image requests through PHP - If-Modified-Since not being sent | [
"",
"php",
"apache",
"caching",
"header",
""
] |
**How do I programatically get my own Firefox extension's version number with Javascript?**
My extension has an install.rdf file containing the version number similar to below. I want to extract the contents of the `<em:version>` tag.
```
<?xml version="1.0" encoding="UTF-8"?>
<RDF xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#"
xmlns:em="http://www.mozilla.org/2004/em-rdf#">
<Description about="urn:mozilla:install-manifest">
...
<em:version>1.0</em:version>
...
</Description>
</RDF>
``` | I've not got the full answer, but I found [the Extended extension](http://extended.spanglerco.com/) and had a look at the source code as it seemed like a good starting point, and from Googling some of the methods in that I found [this snippet on MDC](https://developer.mozilla.org/En/Code_snippets/On_page_load#Running_code_on_an_extension%27s_first_run_or_after_an_extension%27s_update). The key bit of code would seem to be this:
```
var gExtensionManager = Components.classes["@mozilla.org/extensions/manager;1"]
.getService(Components.interfaces.nsIExtensionManager);
var current = gExtensionManager.getItemForID("extension@guid.net").version;
```
You would have to replace `extension@guid.net` with the appropriate ID for your extension.
Firefox 4 requires different code, see the other answer. | In Firefox 4 (Gecko 2) the API has changed, so if you need to port to Firefox 4, this is the code (from [here](https://developer.mozilla.org/en-US/docs/Code_snippets/Miscellaneous#Retrieving_the_version_of_an_extension_as_specified_in_the_extension%27s_install.rdf)):
```
try {
// Firefox 4 and later; Mozilla 2 and later
Components.utils.import("resource://gre/modules/AddonManager.jsm");
AddonManager.getAddonByID("extension-guid@example.org", function(addon) {
alert("My extension's version is " + addon.version);
});
}
catch (ex) {
// Firefox 3.6 and before; Mozilla 1.9.2 and before
var em = Components.classes["@mozilla.org/extensions/manager;1"]
.getService(Components.interfaces.nsIExtensionManager);
var addon = em.getItemForID("extension-guid@example.org");
alert("My extension's version is " + addon.version);
}
``` | How can a Firefox extension get its own version number programmatically? | [
"",
"javascript",
"firefox",
"firefox-addon",
""
] |
Suppose the following object structure:
```
class Super {}
class SubA extends Super {}
class SubB extends Super {}
```
I want to be able to have a variable that will hold the class object for either of my subclasses. I feel like this should do it:
```
Class<Super> classObj;
```
Then, I want to be able to something like this:
```
classObj = SubA.class;
```
or:
```
classObj = SubB.class;
```
This doesn't work though. I get the following error:
```
Type mismatch: cannot convert from Class<SubA> to Class<Super>
```
Any ideas why? What do I need to fix? | You need a *bounded wildcard*:
```
Class<? extends Super> classObj;
```
See the lesson on [wildcards](http://java.sun.com/docs/books/tutorial/extra/generics/wildcards.html) from the Java tutorials. | As mmyers pointed out you could use wildcarding.
As an alternative, you could have the classes implement a common interface and then access them through that interface. | Class object type parameterization in Java | [
"",
"java",
"generics",
"reflection",
""
] |
Recently, I was challenged in a recent interview with a string manipulation problem and asked to optimize for performance. I had to use an iterator to move back and forth between TCHAR characters (with UNICODE support - 2bytes each).
Not really thinking of the array length, I made a curial mistake with not using size\_t but an int to iterate through. I understand it is not compliant and not secure.
```
int i, size = _tcslen(str);
for(i=0; i<size; i++){
// code here
}
```
But, the maximum memory we can allocate is limited. And if there is a relation between int and register sizes, it may be safe to use an integer.
E.g.: Without any virtual mapping tools, we can only map 2^register-size bytes. Since TCHAR is 2 bytes long, half of that number. For any system that has int as 32-bits, this is not going to be a problem even if you dont use an unsigned version of int. People with embedded background used to think of int as 16-bits, but memory size will be restricted on such a device. So I wonder if there is a architectural fine-tuning decision between integer and register sizes. | The C++ standard doesn't specify the size of an int. (It says that `sizeof(char) == 1`, and `sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long)`.
So there doesn't **have** to be a relation to register size. A fully conforming C++ implementation could give you 256 byte integers on your PC with 32-bit registers. But it'd be inefficient.
So yes, in practice, the size of the `int` datatype is generally equal to the size of the CPU's general-purpose registers, since that is by far the most efficient option.
If an `int` was bigger than a register, then simple arithmetic operations would require more than one instruction, which would be costly. If they were smaller than a register, then loading and storing the values of a register would require the program to mask out the unused bits, to avoid overwriting other data. (That is why the `int` datatype is typically more efficient than `short`.)
(Some languages simply require an `int` to be 32-bit, in which case there is obviously no relation to register size --- other than that 32-bit is chosen because it is a common register size) | Going strictly by the standard, there is no guarantee as to how big/small an int is, much less any relation to the register size. Also, some architectures have different sizes of registers (i.e: not all registers on the CPU are the same size) and memory isn't always accessed using just one register (like DOS with its Segment:Offset addressing).
With all that said, however, in most cases int is the same size as the "regular" registers since it's supposed to be the most commonly used basic type and that's what CPUs are optimized to operate on. | Is there a relation between integer and register sizes? | [
"",
"c++",
"memory",
"integer",
"cpu",
"cpu-registers",
""
] |
Are public events asynchronous? Do they execute on a separate thread? | They are executed in whatever thread the event is triggered by.
This means, if the event is raised by the GUI thread, the event handler's for that event are executed in the GUI's thread. If the event is raise by some background thread, the event handlers are executed in that background thread. Within whatever thread the handler is executing, the method is executed synchronously.
As an additional note, if you have an event handler in a form, for an event that raised by a class that is working in the background, when that event is trigger, the event handler will be called in the background thread. Which means, you will need to use Control.Invoke or some other mechanism to properly pass data into the GUI thread, so that the form can be modified. | No.
Events are executed in the thread that raises them. | Are public events asynchronous? Do they execute on a separate thread? | [
"",
"c#",
""
] |
I work on a code base written in php 4. I'd like to go through the process of upgrading the code to php 5 (the latest version my host provides). I'm wondering if anyone else has gone through a similar upgrade experience and can share what gotchas/pitfalls there are, what has to change in my code, what is not backwards compatible between the two versions? | Take a look at the [guide for migrating from PHP 4 to 5](http://www.php.net/manual/en/migration5.php). Your existing PHP 4 code should mostly still work, though there are some [backward-incompatible changes](http://www.php.net/manual/en/migration5.incompatible.php). | Check out the [Migrating from PHP 4 to PHP 5.0.x](https://www.php.net/manual/en/migration5.php) documentation page.
The most important section is [Backward Incompatible Changes](https://www.php.net/manual/en/migration5.incompatible.php).
AS long as you didn't use classes and objects in your previous application, array\_merge is probably the only major problem you can encounter.
DO NOT enable the `zend.ze1_compatibility_mode` configuration variable. | How backwards compatible is php 5 with php 4? | [
"",
"php",
"backwards-compatibility",
"php4",
""
] |
I would like to see if a value equals any of the values in an array.
like this
```
Beginning of function(here I give Val differnt values with for loops...)
for (i=0;i<array_size;i++)
if (Val==array[i])
do something
else
do something else if non of the above values matched val...
```
If none of the Arrayvalues matches my val I would like to do something else, but only once... And if it matches then I would like to go back to the beginning of the function that will give me a different value to val...
Where should I put in this code
Thx, for a great forum
/Buxley | Use a flag to indicate whether the condition was satisfied at least once:
```
bool hasMatch = false;
for (i=0;i< array_size;i++) {
if (Val==array[i]) {
// do something
hasMatch = true;
}
}
if( !hasMatch ) {
// do whatever else
}
```
This will invoke the "do something" for every matching element. If you want to invoke it for the first matching element only use `break;` after "do something". | you can use a find function
```
int find(int value, int* array, int size) {
int i;
for (i=0; i<size; i++) {
if (array[i]==value) {
return i;
}
}
return -1;
}
```
Now you can do
```
if (find(value, array, array_size)>=0)) {
do_something_when_found();
} else {
do_something_when_not_found();
}
``` | c++ array value matching variable | [
"",
"c++",
""
] |
Say I have a rewrite that needs to pass the url to a PHP function and retrieve a value in order to tell what the new destination should be? is there a way to do that?
Thanks.
**UPDATE:**
Thanks so far guys..I am still having trouble but i'll show you my code:
.htaccess
```
#I got the file path by echoing DOCUMENT_ROOT and added the rest.
RewriteMap fixurl prg:/var/www/vhosts/mydomain.com/httpsdocs/domain_prototype/code_base/url_handler.php
RewriteEngine On
RewriteRule (.*) ${fixurl:$1} [PT]
```
PHP:
```
set_time_limit(0); # forever program!
$keyboard = fopen("php://stdin","r");
while (1) {
$line = trim(fgets($keyboard));
print "www.google.com\n"; # <-- just test to see if working.
}
```
However I am getting a **500 Internal Server Error** I am not sure if there is an error in my .htaccess or in my PHP? | There is something called a RewriteMap.
You can call an executable script that will return the URL to rewrite to.
Check this article for more information and examples (in Perl, but are totally applicable to any other language):
<http://www.onlamp.com/pub/a/apache/2005/04/28/apacheckbk.html>
Summary of caveats:
* Must run a read STDIN loop (ie, don't exit after receiving an URL)
* Must print the URL to rewrite to WITH a trailing newline
* Must be readable and executable by the user Apache runs as
This is the way to create the map
```
RewriteMap fixurl prg:/usr/local/scripts/fixit.php
```
And now we can use it in a RewriteRule:
```
RewriteEngine On
RewriteRule (.*) ${fixurl:$1}
```
EDIT: About the Internal Server Error. The most probable cause is what Gumbo mentions, RewriteMap cannot be used in .htaccess, sadly. You can use it in a RewriteRule in .htaccess, but can only create it in server config or virtual host config. To be certain, check the error log.
So, the only PHP / .htaccess only solution would be to rewrite everything to a certain PHP program which does the checking and redirects using the Location header. Something like:
```
RewriteRule (.*) proxy.php?args=$1 [QSA]
```
Then, in proxy.php
```
<?php
$url = get_proper_destination($QUERY_STRING); #args will have the URI path,
#and, via QSA you will have
#the original query string
header("Location: $url");
?>
``` | Yes; you need a [RewriteMap](http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html#RewriteMap), of the External Rewriting Program variety. | Run PHP code from .htaccess? | [
"",
"php",
"apache",
".htaccess",
""
] |
I want a Servlet to handle requests to files depending on prefix and extension, e.g.
prefix\_\*.xml
Since mapping on beginning AND end of request path is not possible, I have mapped all \*.xml requests to my Servlet.
The question now is: how can I drop out of my servlet for XML files not starting with "prefix\_", so that the request is handled like a "normal" request to an xml file?
This is probably quite simple but I do not seem to be able to find this out... :-/
Thanks a lot in advance | I would strongly suggest using a proper MVC framework for this. As you've discovered, the flexibility of the standard servlet API is very limited when it comes to request dispatching.
Ideally, you would be able to use your existing servlet code in combination with an MVC framework, with the framework doing the diapcthing based on path pattern, and your servlets doing the business logic. Luckily, Spring MVC allows you to do just that, using the ServletForwardingController. It'd be a very lightweight spring config.
So you'd have something like this in your web.xml:
```
<servlet>
<servlet-name>myServlet</servlet-name>
<servlet-class>foo.MyServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
</servlet>
<url-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*</url-pattern>
</url-mapping>
```
You would then have a WEB-INF/spring-servlet.xml file like this:
```
<beans>
<bean name="/prefix*.xml" class="org.springframework.web.servlet.mvc.ServletForwardingController">
<property name="servletName" value="myServlet"/>
</bean>
</beans>
```
And that would be pretty much it. All requests for /prefix\*.xml would go to myServlet, and all others would fall through to the container. | another solution (maybe fits for you) is if you are using/plan to use an Apache in front of that web container instance you could use the rewrite module of apache. Rewriting the url to something more easy to handle for the Webapp container.
Hope this helps.
David. | Java Servlet: pass a request back to default processing | [
"",
"java",
"servlets",
"request",
"response",
"servlet-filters",
""
] |
I try to measure the clock cyles needed to execute a piece of code on the TMS32064x+ DSP that comes with the OMAP ZOOM 3430 MDK. I look at the "Programmer's Guide" of the DSP chip and it says that the DSP supports the clock() function.
What I do is really simple, I just do
```
start = clock();
for (i=0;i<100;i++){
/* do something here */
}
stop = clock();
total = stop - start;
```
and then put the values of "start","stop" and "total" to a previously allocated shared memory with the ARM processor. Then I simply print it to the screen at the ARM side.
The problem is, in my first executes, I always get the same "total" value, and then in my next runs I always get 0! The "start" and "stop" values go along with the "total" value.
The strangest thing is that they seem to follow a bit pattern! I put the output below:
```
# ./sampleapp
Total = 63744
Start clock() value = 0x000000f9
Stop clock() value = 0x0000f9f9
# ./sampleapp
Total = 4177526784
Start clock() value = 0x00f9f9f9
Stop clock() value = 0xf9f9f9f9
# ./sampleapp
Total clock cyles = 0
Start clock() value = 0xf9f9f9f9
Stop clock() value = 0xf9f9f9f9
```
Apparantly, clock() is not functioning well, but I'm not sure if this is because of something I do wrong or because this type of thing is not supported with the hardware I have. Any ideas why this might be happening? | From reading the questions so far, I'd say the Original Poster has substantially more knowledge of this matter than the contributors so far, and that the suspicion that the clock() is broken (or not supported, and returns an undefined result) on the DSP seems quite likely. | Assuming the start and end variable are of type 'clock\_t', and your shared memory assumes the same on the other end's interpretation of the numbers passed, then your problem is not with the call to clock, and your handleing of the difference between the start end end times.
I believe your problem is in the shared memory between the two. Can you please post code to show how you're sharing memory between two separate processors? | Is time.h clock() broken on my hardware? | [
"",
"c++",
"c",
"embedded",
"clock",
"omap",
""
] |
I am trying to add a new menu item to Eclipse's popupmenus. It really seemed straightforward enough in the examples and tutorials but the menu item itself is never visible. I expect this to work in all views and for basically anything that is a file. I am using Eclipse 3.4. This is the my plugin.xml configuration:
```
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.2"?>
<plugin>
<extension
point="org.eclipse.ui.popupMenus">
<objectContribution
objectClass="org.eclipse.core.resources.IFile"
id="com.willcodejavaforfood.ExploreHere.contribution1">
<action
label="Explore Here"
class="com.willcodejavaforfood.explorehere.popup.actions.ExploreHereAction"
menubarPath="additions"
enablesFor="1"
id="com.willcodejavaforfood.ExploreHere.newAction">
</action>
</objectContribution>
</extension>
</plugin>
```
Any idea why it is never visible?
**----edit----**
Turns out my plugin works just fine in version 3.4.2 of Ganymede, but not in the older version 3.4.0 that I previously used. | I tried your code in my Eclipse's installation and I am able to see the action in the contextual menu when I right click one of my .c file in the Project explorer's view of the C perspective.
Take care that a Project or a project's sub folder is not a file. | May be you can try the PDE templates:
File -> New plugin project -> On the last page select create from template and try the **Plugin with popup menu** which description is exactly what you want:
"This template adds a submenu and a new action to a target object's popup menu. This contribution will appear in all viewers where an object of the specified type is selected."
Hope this can help
Manu | Eclipse Plugin - Popup Menu Extension | [
"",
"java",
"eclipse-plugin",
"popup",
"swt",
""
] |
Is there any way to upload an entire folder using PHP? | No. Its not a limitation of PHP, but a limitation of the browser itself. There is no way to select a folder for upload (and pass the data through).
You could however upload an archive, and then use php to unzip it. | That's not a limitation of PHP, but of the browsers themselves. They don't allow you to select a "folder" to upload. You can only do a file; one file per input tag.
Your best bet is to zip a folder, upload it and use PHP to unzip it on the local file system.
or
You could use (Java Applet): <http://jupload.biz/>
or
(Flash) <http://swfupload.org/> | Is folder uploading possible in PHP? | [
"",
"php",
"http",
""
] |
I'm writing a mixin which will allow my Models to be easily translated into a deep dict of values (kind of like .values(), but traversing relationships). The cleanest place to do the definitions of these seems to be in the models themselves, a la:
```
class Person(models.Model, DeepValues):
name = models.CharField(blank=True, max_length=100)
tribe = models.ForeignKey('Tribes')
class Meta:
schema = {
'name' : str,
'tribe' : {
'name' : str
}
}
Person.objects.all().deep_values() => {
'name' : 'Andrey Fedorov',
'tribe' : {
'name' : 'Mohicans'
}
}
```
However, Django complains about my including this in `class Meta` with:
```
TypeError: 'class Meta' got invalid attribute(s): schema
```
(entire stack trace [here](http://gist.github.com/76cef1f8aea0ce92cb24))
Now, I suppose I could elaborately override this in my mixin, but is there a more elegant way of storing this information? | I don't know about elegant, but one pragmatic way is:
```
import django.db.models.options as options
options.DEFAULT_NAMES = options.DEFAULT_NAMES + ('schema',)
```
Obviously, this would break if Django ever added a 'schema' attribute of its own. But hey, it's a thought...you could always pick an attribute name which is less likely to clash. | Not a direct answer, but I did not like the idea of adding it in every model where I need it to the options, so I did:
```
class MyModel(models.Model):
class Meta:
ordering = ["myfield"]
class MyPrefixMeta:
my_value = "Abc"
```
You could even put this to a abstract model and validate the set class properties in `__init__` function or do things like adding a `_myprefix_meta` property to the model. So you had your own meta class. | Adding attributes into Django Model's Meta class | [
"",
"python",
"django",
"django-models",
"metadata",
""
] |
Out of curiosity, why are sometimes multiple Java .class files generated for a class after compilation? For example, my application has six classes. For one class, a total of 10 .class files has been generated, starting from MyClass#1 up to MyClass#10. | These are for [inner classes](http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html) and [static nested classes](http://java.sun.com/docs/books/tutorial/java/javaOO/nested.html). The ones with numbers are anonymous inner classes.
For example:
```
class Foo {
class Bar { }
static class Baz { }
void run() {
Helper t = new Helper() {
int helpMethod() {
return 2;
}
};
}
}
```
This will produce class files `Foo.class`, `Foo$Bar.class`, `Foo$Baz.class` and `Foo$1.class` (for the implementation of the `Helper` interface) | You get more .class fils from a single source file if
* the class contains inner classes or static inner classes. Inner classes can nest. Their names are `<outer class name>$<inner class name>`.
* inner interfaces which are always static.
* anonymous inner classes (which in fact are plain inner classes without a name)
* package access interfaces and classes before and after your main class. You can have an arbitrary number of package access classes and interfaces in a single Java source file. Usually small helper objects that are only used by the class are just put into the same file. | Multiple .class files generated for a class? | [
"",
"java",
"class",
"javac",
""
] |
I have a datagridview made up of multiple rows and columns.
I want to iterate through each row and check the contents of a specific column.
If that column contains the word "NO", I want to change the forecolor of the entire row to Red.
Here is an attempt at some code so far but It's certainly not working, starting to wonder If I need to iterate over every cell?
CODE:
```
foreach (DataGridViewRow dgvr in dataGridView1.Rows)
{
if (dgvr.Cells["FollowedUp"].Value.ToString() == ("No"))
{
dgvr.DefaultCellStyle.ForeColor = Color.Red;
}
}
``` | ```
public void ColourChange()
{
DataGridViewCellStyle RedCellStyle = null;
RedCellStyle = new DataGridViewCellStyle();
RedCellStyle.ForeColor = Color.Red;
DataGridViewCellStyle GreenCellStyle = null;
GreenCellStyle = new DataGridViewCellStyle();
GreenCellStyle.ForeColor = Color.Green;
foreach (DataGridViewRow dgvr in dataGridView1.Rows)
{
if (dgvr.Cells["FollowedUp"].Value.ToString().Contains("No"))
{
dgvr.DefaultCellStyle = RedCellStyle;
}
if (dgvr.Cells["FollowedUp"].Value.ToString().Contains("Yes"))
{
dgvr.DefaultCellStyle = GreenCellStyle;
}
}
}
``` | hook up **OnRowDataBound** event then do stuff
ASPX (Grid):
```
<asp:.... OnRowDataBound="RowDataBound"..../>
```
Code Behind:
```
protected void RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex == -1)
{
return;
}
if(e.Row.Cells[YOUR_COLUMN_INDEX].Text=="NO"){
e.Row.BackColor=Color.Red;
}
}
```
FOR WinForms:
```
hook the **DataBindingComplete** event and do stuff in it:
private void dataGridView1_DataBindingComplete(object sender,
DataGridViewBindingCompleteEventArgs e)
{
if (e.ListChangedType != ListChangedType.ItemDeleted)
{
DataGridViewCellStyle red = dataGridView1.DefaultCellStyle.Clone();
red.BackColor=Color.Red;
foreach (DataGridViewRow r in dataGridView1.Rows)
{
if (r.Cells["FollowedUp"].Value.ToString()
.ToUpper().Contains("NO"))
{
r.DefaultCellStyle = red;
}
}
}
}
``` | C# Iterate Over DataGridView & Change Row Color | [
"",
"c#",
"winforms",
"datagridview",
"row",
"loops",
""
] |
For our company I'd like to have a Python based IRC bot which checks whether the websites of our clients are still up and running. More specific: I want to list a number of URL which should be visited every, say, 15 minutes. If it fails, the URL should be checked again after 5 minutes. If retrieving the URL still doesn't result in an HTTP status code 200, it should echo the failing URL in the channel so we can investigate it.
I've written a plugin for [Supybot](http://sourceforge.net/projects/supybot/) some time ago that basically does some of the above in a crude but effective way. If I want to expand the functionality of the current code to the above 'specs' I need to do some major refactoring; basically it would mean starting from scratch.
Which raises the question: should I write a better plugin for Supybot, matching the new requirements, or go for something else altogether? Should I start from scratch (learning the most, implementing the [relevant RFCs](https://stackoverflow.com/questions/24310/programming-a-simple-irc-internet-relay-chat-client/844821#844821) myself, spending more time than planned) or is there a suitable framework which handles the basic IRC stuff? | I vote for a completely new plugin for Supybot. Learn more ;)
If you won't do so much, try **python [irclib](http://sourceforge.net/project/showfiles.php?group_id=38297)**. It's a (still maintained) python lib for IRC.
[Twisted](http://twistedmatrix.com/trac/) may also be ok, but it's a little but too much... | To me it sounds like a case of your application wanting to talk IRC, and my gut reaction would be to use Twisted, which has IRC clients. This may or may not be the right solution for you, but at least it's worth investigating. | Python IRC client: write from scratch or write plugin for existing framework? | [
"",
"python",
"irc",
""
] |
In performance point of view what should you use "Nested foreach's" or "lambda/linq queries"? | Write the clearest code you can, and then benchmark and profile to discover any performance problems. If you *do* have performance problems, you can experiment with different code to work out whether it's faster or not (measuring all the time with as realistic data as possible) and then make a judgement call as to whether the improvement in performance is worth the readability hit.
A direct `foreach` approach *will* be faster than LINQ in many cases. For example, consider:
```
var query = from element in list
where element.X > 2
where element.Y < 2
select element.X + element.Y;
foreach (var value in query)
{
Console.WriteLine(value);
}
```
Now there are two `where` clauses and a `select` clause, so every eventual item has to pass through three iterators. (Obviously the two where clauses could be combined in this case, but I'm making a general point.)
Now compare it with the direct code:
```
foreach (var element in list)
{
if (element.X > 2 && element.Y < 2)
{
Console.WriteLine(element.X + element.Y);
}
}
```
That will run faster, because it has fewer hoops to run through. Chances are that the console output will dwarf the iterator cost though, and I'd certainly prefer the LINQ query.
EDIT: To answer about "nested foreach" loops... typically those are represented with `SelectMany` or a second `from` clause:
```
var query = from item in firstSequence
from nestedItem in item.NestedItems
select item.BaseCount + nestedItem.NestedCount;
```
Here we're only adding a single extra iterator, because we'd already be using an extra iterator per item in the first sequence due to the nested `foreach` loop. There's still a bit of overhead, including the overhead of doing the projection in a delegate instead of "inline" (something I didn't mention before) but it still won't be very different to the nested-foreach performance.
This is not to say you can't shoot yourself in the foot with LINQ, of course. You can write stupendously inefficient queries if you don't engage your brain first - but that's far from unique to LINQ... | If you do
```
foreach(Customer c in Customer)
{
foreach(Order o in Orders)
{
//do something with c and o
}
}
```
You will perform Customer.Count \* Order.Count iterations
---
If you do
```
var query =
from c in Customer
join o in Orders on c.CustomerID equals o.CustomerID
select new {c, o}
foreach(var x in query)
{
//do something with x.c and x.o
}
```
You will perform Customer.Count + Order.Count iterations, because Enumerable.Join is implemented as a HashJoin. | "Nested foreach" vs "lambda/linq query" performance(LINQ-to-Objects) | [
"",
"c#",
"lambda",
"foreach",
"linq-to-objects",
""
] |
I am currently building an making my new website. It uses one page and uses a jQuery accordian menu to load the content. The content it split up in six different div's and all load as soon as the page is accessed. I want it to load each div when the link to it is clicked on. To decrease the page loading time.
You can see this in action on my work in progress site here: [<http://is.gd/1p1Ys>](http://is.gd/1p1Ys%0A)
Since I didn't make the jQuery script and I am really bad at JavaScript/jQuery I don't have a clue what to do. So I am wondering if anybody here can help me out.
Thanks a ton,
Ryan | I agree with the other answers that jquery-ui tabs does this exact thing, but you can hack your accordian.js file pretty easily... just change the hrefs in your navigation to point to external html files containing the content you want, i.e. href="#lifestream" => href="lifestream.html",
and then in accordian.js:
```
$links.click(function () {
var link = this,
if(!link.href.match(/^#.*/)) { //if the href doesn't start with '#'
loadDiv(link.href);
} else {
doRestOfFunction(); //everything your script is currently doing.
}
});
function loadDiv(href) {
$.get(href, function(html) {
var newDiv = $(html)
$(".panels").append(newDiv);
newDiv.hide();
doRestOfFunction(); //same as above
}
}
``` | From your description, it sounds like these divs are not displayed until the top-level menu item is clicked. If this is the case, you can use jquery to insert the sub-menu divs into the DOM when it is opened.
You can find a decent tutorial on Javascript/DOM Manipulation at [w3schools](http://w3schools.com/htmldom/default.asp). | How to get div's to load on click not when page loads? | [
"",
"javascript",
"jquery",
"html",
"css",
"accordion",
""
] |
I know that C# has the `using` keyword, but `using` disposes of the object automatically.
Is there the equivalence of `With...End With` in [Visual Basic 6.0](http://en.wikipedia.org/wiki/Visual_Basic#Timeline)? | C# doesn't have an equivalent language construct for that. | It's not equivalent, but would this syntax work for you?
```
Animal a = new Animal()
{
SpeciesName = "Lion",
IsHairy = true,
NumberOfLegs = 4
};
``` | Equivalence of "With...End With" in C#? | [
"",
"c#",
"vb.net",
"with-statement",
""
] |
I have a `map` declared as follows:
```
map < string , list < string > > mapex ; list< string > li;
```
How can I display the items stored in the above map on the console? | Well it depends on how you want to display them, but you can always iterate them easily:
```
typedef map<string, list<string>>::const_iterator MapIterator;
for (MapIterator iter = mapex.begin(); iter != mapex.end(); iter++)
{
cout << "Key: " << iter->first << endl << "Values:" << endl;
typedef list<string>::const_iterator ListIterator;
for (ListIterator list_iter = iter->second.begin(); list_iter != iter->second.end(); list_iter++)
cout << " " << *list_iter << endl;
}
``` | Update (Back to the future): with C++11 range-based for loops –
```
std::map<Key, Value> m { ... /* initialize it */ ... };
for (const auto &p : m) {
std::cout << "m[" << p.first << "] = " << p.second << '\n';
}
``` | How can I display the content of a map on the console? | [
"",
"c++",
"dictionary",
"stl",
"stdmap",
""
] |
I have spent some time now to solve a problem for which i have no solution till now. I have a predefined very huge database, whose structure is fixed. I use the repository pattern to create a abstraction layer between service code and database logic. The problem is, that i need to apply some processing to the database object before passing them out of the repository. Thus i can't use the Linq Entities directly.
Basically a repository method looks like this:
```
public IList<Bookingcode> FindBookingcode(int id) {
return (from b in _db.BOOKINGCODE
where b.ID == id
select new Bookingcode {
Id = b.ID,
Name = b.NAME.Trim()
}).ToList();
}
```
This works good so far. But i have a lot of objects which should be individually composed.
FindBookingcode() should return a nearly complete object with other objects like catalogs and so on. My Problem now is that i have to rewrite the mapping a lot of times like in this example:
```
public IList<Bookingcode> FindBookingcode(int id) {
return (from b in _db.BOOKINGCODE
join c1 in _db.CATALOG on b.CATALOGID equals c1.ID
where b.ID == id
let refs = (
from bc1 in _db.BOOKINGCODE
join p in _db.PACKAGE on bc1.ID equals p.BOOKINGCODE
join bc2 in _db.BOOKINGCODE on p.PACKAGEREF equals bc2.ID
join c in _db.CATALOG on bc.CATALOGID on bc2.CATALOGID equals c.ID
where bc1.ID == b.ID
select new PackageInfo {
ID = p.ID
BookingcodeRef = new Bookingcode {
ID = bc2.ID,
Catalog = new Catalog { ID = c.ID }
}
})
select new Bookingcode {
ID = b.ID,
PackageInfo = refs.ToList()
}).ToList();
}
```
I also have some L2O processing within the repository which assembles the returned objects. Another thing i have no cool solution for, is a way to tell the repository what it should fetch, like FindBookingcode(id, includePackageInfo, includeCatalog).
So here are the questions:
1) Is this approach totally stupid?
2) Can you guide me to a solution which makes the remapping simpler?
3) How to implement the DDD's criteria mechanism | Are you using Linq to SQL or Entity Framework?
**I've assumed here that you're using Entity Framework as you referred to "LINQ Entity" in your question.**
You should be able to do this sort of mapping using the Entity Framework **navigation
properties**. You'll need to add navigation properties to each entity that you'd like to map in this way. It's as easy as telling the visual designer which attribute maps to a corresponding attribute in another entity.
Take a look at the [How do I Entity Framework video series](http://msdn.microsoft.com/en-us/data/aa937723.aspx) for a very quick starter guide. I'd recommend watching the whole series as they are very informative. | In my repositories I have a separate build method that takes in a LINQ to SQL entity and returns a business object.
The build method looks something like (this.Container is a Unity IoC container and not important for the example):
```
private IGroup BuildGroup(Entities.Group group)
{
IGroup result = this.Container.Resolve<IGroup>();
result.ID = group.GroupID;
result.Name = group.Name;
return result;
}
```
Then each method uses the build method to return a business object:
```
public override IGroup GetByID(int id)
{
try
{
return (from g in this.Context.Groups
where g.GroupID == id && g.ActiveFlag
select this.BuildGroup(g)).Single();
}
catch (InvalidOperationException)
{
return null;
}
}
```
This works by getting back each LINQ to SQL entity from the database and running it through the build method so your result in this case would be an enumerable of your business objects instead of LINQ to SQL entities. | LINQ, Repository Pattern and Database Abstraction | [
"",
"c#",
"asp.net-mvc",
"linq",
"repository-pattern",
""
] |
I am having issues with trying to convert an UTF-8 string to unicode. I get the error.
```
UnicodeEncodeError: 'ascii' codec can't encode characters in position 73-75: ordinal not in range(128)
```
I tried wrapping this in a `try`/`except` block but then google was giving me a system administrator error which was one line.
Can someone suggest how to catch this error and continue.
Cheers, John.
**-- FULL ERROR --**
```
Traceback (most recent call last):
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 501, in __call__
handler.get(*groups)
File "/Users/johnb/Sites/hurl/hurl.py", line 153, in get
self.redirect(url.long_url)
File "/Applications/GoogleAppEngineLauncher.app/Contents/Resources/GoogleAppEngine-default.bundle/Contents/Resources/google_appengine/google/appengine/ext/webapp/__init__.py", line 371, in redirect
self.response.headers['Location'] = str(absolute_url)
UnicodeEncodeError: 'ascii' codec can't encode characters in position 73-75: ordinal not in range(128)
``` | The correct [solution](http://www.nabble.com/Re:-Problem:-neither-urllib2.quote-nor-urllib.quote-encode-the--unicode-strings-arguments-p19823144.html) is to do the following:
```
self.response.headers['Location'] = urllib.quote(absolute_url.encode("utf-8"))
``` | The location header you are trying to set needs to be an Url, and an Url needs to be in Ascii. Since your Url is not an Ascii string you get the error. Just catching the error won't help since the Location header won't work with an invalid Url.
When you create `absolute_url` you need to make sure it is encoded properly, best by using [`urllib.quote`](http://docs.python.org/library/urllib.html#urllib.quote) and the strings [`encode()`](http://docs.python.org/library/stdtypes.html#str.encode) method. You can try this:
```
self.response.headers['Location'] = urllib.quote(absolute_url.encode('utf-8'))
``` | Python Unicode UnicodeEncodeError | [
"",
"python",
"google-app-engine",
"unicode",
"utf-8",
""
] |
I have a `PictureBox` on my Windows Forms application.
I load a picture in it and I have enabled the `Paint` event in my code. It draws a rectangle.
Like this:
```
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
Graphics gr = e.Graphics;
Pen p = new Pen(Color.Red);
p.Width = 5.0f;
gr.DrawRectangle(p, 1, 2, 30, 40);
}
```
And I click the "save" button:
```
private void button2_Click(object sender, EventArgs e)
{
pictureBox1.Image.Save(@"C:\Documents and Settings\tr1g3800\Desktop\WALKING\30P\100000test.jpg",ImageFormat.Jpeg);
}
```
But the saved file never contains the rectangle that I drew.
Does anyone have any idea? | You probably shouldn't draw directly on the PictureBox.
You need to use a Bitmap instead. Try putting the bitmap in the PictureBox.Image and then call Save().
Check [this](http://bytes.com/groups/net-c/266074-how-save-picturebox-image-into-jpg-file) for more details | Thanks.Your anwers all helped.
This worked
```
private void button1_Click(object sender, EventArgs e)
{
pictureBox1.ImageLocation=@"C:\Documents and Settings\tr1g3800\Desktop\WALKING\30P\100000.jpg" ;
}
private void button2_Click(object sender, EventArgs e)
{
pictureBox1.Image.Save(@"C:\Documents and Settings\tr1g3800\Desktop\WALKING\30P\100000test.jpg",ImageFormat.Jpeg);
}
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
}
private void button3_Click(object sender, EventArgs e)
{
Bitmap bmp = new Bitmap(pictureBox1.Image);
Graphics gr = Graphics.FromImage(bmp);
Pen p = new Pen(Color.Red);
p.Width = 5.0f;
gr.DrawRectangle(p, 1, 2, 30, 40);
pictureBox1.Image = bmp;
}
``` | How to save a picturebox control as a jpeg file after it's edited | [
"",
"c#",
".net",
"picturebox",
""
] |
All of the examples I've seen of using `yield return x;` inside a C# method could be done in the same way by just returning the whole list. In those cases, is there any benefit or advantage in using the `yield return` syntax vs. returning the list?
Also, in what types of scenarios would `yield return` be used that you couldn't just return the complete list? | But what if you were building a collection yourself?
In general, iterators can be used to **lazily generate a sequence of objects**. For example `Enumerable.Range` method does not have any kind of collection internally. It just generates the next number **on demand**. There are many uses to this lazy sequence generation using a state machine. Most of them are covered under **functional programming concepts**.
In my opinion, if you are looking at iterators just as a way to enumerate through a collection (it's just one of the simplest use cases), you're going the wrong way. As I said, iterators are means for returning sequences. The sequence might even be **infinite**. There would be no way to return a list with infinite length and use the first 100 items. It **has** to be lazy sometimes. **Returning a collection is considerably different from returning a collection generator** (which is what an iterator is). It's comparing apples to oranges.
Hypothetical example:
```
static IEnumerable<int> GetPrimeNumbers() {
for (int num = 2; ; ++num)
if (IsPrime(num))
yield return num;
}
static void Main() {
foreach (var i in GetPrimeNumbers())
if (i < 10000)
Console.WriteLine(i);
else
break;
}
```
This example prints prime numbers less than 10000. You can easily change it to print numbers less than a million without touching the prime number generation algorithm at all. In this example, you can't return a list of all prime numbers because the sequence is infinite and the consumer doesn't even know how many items it wants from the start. | The fine answers here suggest that a benefit of `yield return` is that ***you don't need to create a list***; Lists can be expensive. (Also, after a while, you'll find them bulky and inelegant.)
But what if you don't have a List?
`yield return` allows you to traverse **data structures** (not necessarily Lists) in a number of ways. For example, if your object is a Tree, you can traverse the nodes in pre- or post- order without creating other lists or changing the underlying data structure.
```
public IEnumerable<T> InOrder()
{
foreach (T k in kids)
foreach (T n in k.InOrder())
yield return n;
yield return (T) this;
}
public IEnumerable<T> PreOrder()
{
yield return (T) this;
foreach (T k in kids)
foreach (T n in k.PreOrder())
yield return n;
}
``` | What is the purpose/advantage of using yield return iterators in C#? | [
"",
"c#",
"iterator",
"yield-return",
""
] |
I have a string = "google.com 220 USD 3d 19h".
I want to extract just the ".com" part.......
whats the easiest way to manipulate the split string method to get this result? | I'm guessing you either want to extract the domain name or the [TLD](http://en.wikipedia.org/wiki/TLD) part of the string. This should do the job:
```
var str = "google.com 220 USD 3d 19h";
var domain = str.Split(' ')[0]; // google.com
var tld = domain.Substring(domain.IndexOf('.')) // .com
``` | Alternate idea
```
string str = "google.com 220 USD 3d 19h";
string match = ".com";
string dotcomportion = str.Substring(str.IndexOf(match), match.Length);
``` | C# string split | [
"",
"c#",
"string",
"split",
""
] |
I want to check to see if an XML document contains a 'person' element anywhere inside. I can check all the first-generation elements very simply:
```
NodeList nodeList = root.getChildNodes();
for(int i=0; i<nodeList.getLength(); i++){
Node childNode = nodeList.item(i);
if (childNode.getNodeName() == "person") {
//do something with it
}
}
```
And and I can add more loops to go into subelements, but I would have to know how many nested loops to put in to determine how far into the document to drill. I could nest 10 loops, and end up with a person element nested 12 elements deep in a given document. I need to be able to pull out the element not matter how deeply nested it is.
Is there way to harvest elements from an entire document? Like return the text values of all tags as an array or iterate over it?
Something akin to python's elementtree 'findall' method perhaps:
```
for person in tree.findall('//person'):
personlist.append(person)
``` | As mmyers states, you could use recursion for this problem.
```
doSomethingWithAll(root.getChildNodes());
void doSomethingWithAll(NodeList nodeList)
{
for (int i = 0; i < nodeList.getLength(); i++) {
Node childNode = nodeList.item(i);
if (childNode.getNodeName().equals("person")) {
//do something with it
}
NodeList children = childNode.getChildNodes();
if (children != null)
{
doSomethingWithAll(children);
}
}
}
``` | I see three possiblities (two of which others have answered):
1. Use recursion.
2. Use XPath (might be a bit overkill
for this problem, but if you have a
lot of queries like this it is
definitely something to explore).
Use kdgregory's help on that; a
quick look at the api indicated that
it is a bit painful to use
directly.
3. **If** what you have is in fact a `Document` (that is if `root` is a
`Document`), you can use
`Document.getElementsByTagName` | Iterate all XML node generations in java DOM | [
"",
"java",
"xml",
"dom",
""
] |
In Actionscript, the Unix timestamp in milliseconds is obtainable like this:
```
public static function getTimeStamp():uint
{
var now:Date = new Date();
return now.getTime();
}
```
The doc clearly states the following:
> getTime():Number Returns the number of
> milliseconds since midnight January 1,
> 1970, universal time, for a Date
> object.
When I trace it, it returns the following:
```
824655597
```
So, 824655597 / 1000 / 60 / 60 / 24 / 365 = 0.02 years.
This is obviously not correct, as it should be around 39 years.
Question #1: What's wrong here?
Now, onto the PHP part: I'm trying to get the timestamp in milliseconds there as well. The `microtime()` function returns either a string (0.29207800 1246365903) or a float (1246365134.01), depending on the given argument. Because I thought timestamps were easy, I was going to do this myself. But now that I have tried and noticed this float, and combine that with my problems in Actionscript I really have no clue.
Question #2: how should I make it returns the amount of milliseconds in a Unix timestamp?
Timestamps should be so easy, I'm probably missing something.. sorry about that. Thanks in advance.
**EDIT1:** Answered the first question by myself. See below.
**EDIT2:** Answered second question by myself as well. See below. Can't accept answer within 48 hours. | For actionscript3, `new Date().getTime()` should work.
---
In PHP you can simply call [time()](http://www.php.net/time) to get the time passed since January 1 1970 00:00:00 GMT in seconds. If you want milliseconds just do `(time()*1000)`.
If you use [microtime()](http://www.php.net/manual/en/function.microtime.php) multiply the second part with 1000 to get milliseconds. Multiply the first part with 1000 to get the milliseconds and round that. Then add the two numbers together. Voilá. | I used unsigned integer as the return type of the function. This should be Number.
```
public static function getTimeStamp():Number
{
var now:Date = new Date();
return now.getTime();
}
```
Think I got the function for getting milliseconds in PHP5 now.
```
function msTimeStamp() {
return round(microtime(1) * 1000);
}
``` | Getting unix timestamp in milliseconds in PHP5 and Actionscript3 | [
"",
"php",
"actionscript-3",
"unix",
"timestamp",
""
] |
Did some searches here & on the 'net and haven't found a good answer yet. What I'm trying to do is call a button twice within the same class in C#.
Here's my scenario -
I have a form with a button that says "Go". When I click it the 1st time, it runs through some 'for' loops (non-stop) to display a color range. At the same time I set the button1.Text properties to "Stop". I would like to be able to click the button a 2nd time and when that happens I would like the program to stop. Basically a stop-and-go button. I know how to do it with 2 button events, but would like to utilize 1 button.
Right now the only way to end the program is the X button on the form.
I've tried different things and haven't had much luck so far so wanted to ask the gurus here how to do it.
BTW, this is a modification of a *Head First Labs C#* book exercise.
Thanks!
~Allen | You would need to use Multithreading (launch the process intensive code asynchronously in a separate thread), for instance, using the `BackgroundWorker` object in .NET 2+. This would be necessary because your UI will not respond to the user's click until the loop running in the Start method is completed. It is quite irrelevant if you use the same button or another one to toggle the process, because the processor is busy processing the loop.
The `BackgroundWorker` has a property called `WorkerSupportsCancellation` which needs to be true in this scenario. When the user clicks Stop you would invoke the `CancelAsync` method of the `BackgroundWorker`.
See [MSDN](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) for a good example. Also [DreamInCode](http://www.dreamincode.net/forums/showtopic88605.htm) has a good tutorial which seems quite similar to your requirement. | Why not create two buttons, hide one when the other is visible? That should be a lot of easier to handle.
Or you can add a bool field to indicate which operation branch to execute. | C# How To: Trying to call button twice in same class? | [
"",
"c#",
"winforms",
""
] |
I have the following code which reads in the follow file, append a \r\n to the end of each line and puts the result in a string buffer:
```
public InputStream getInputStream() throws Exception {
StringBuffer holder = new StringBuffer();
try{
FileInputStream reader = new FileInputStream(inputPath);
BufferedReader br = new BufferedReader(new InputStreamReader(reader));
String strLine;
//Read File Line By Line
boolean start = true;
while ((strLine = br.readLine()) != null) {
if( !start )
holder.append("\r\n");
holder.append(strLine);
start = false;
}
//Close the input stream
reader.close();
}catch (Throwable e){//this is where the heap error is caught up to 2Gb
System.err.println("Error: " + e.getMessage());
}
return new StringBufferInputStream(holder.toString());
}
```
I tried reading in a 400Mb file, and I changed the max heap space to 2Gb and yet it still gives the out of memory heap exception. Any ideas? | It's an interesting question, but rather than stress over why Java is using so much memory, why not try a design that doesn't require your program to load the entire file into memory? | It may be to do with how the `StringBuffer` resizes when it reaches capacity - This involves creating a new `char[]` double the size of the previous one and then copying the contents across into the new array. Together with the points already made about characters in Java being stored as 2 bytes this will definitely add to your memory usage.
To resolve this you could create a `StringBuffer` with sufficient capacity to begin with, given that you know the file size (and hence approximate number of characters to read in). However, be warned that the array allocation will also occur if you then attempt to convert this large `StringBuffer` into a `String`.
Another point: You should typically favour `StringBuilder` over `StringBuffer` as the operations on it are faster.
You could consider implementing your own "CharBuffer", using for example a `LinkedList` of char[] to avoid expensive array allocation / copy operations. You could make this class implement `CharSequence` and perhaps avoid converting to a `String` altogether. Another suggestion for more compact representation: If you're reading in English text containing large numbers of repeated words you could read and store each word, using the `String.intern()` function to significantly reduce storage. | Why does reading a file into memory takes 4x the memory in Java? | [
"",
"java",
"performance",
"memory",
"file",
"file-io",
""
] |
Does anyone know of an easy 3D modeling application like sketchup but is opensource?
I don't have time for learning blender ( guess I never will ):
and I'm a fan of having multiple small tools do their part of the job
( first cut the plank using the `saw` the nail it using the `hammer` :) ).
**Edit:**
I also might need to do some modifications to the application, for an example I want to be able to preview my GLSL shaders directly at the model. I want also be able to cut the model in half ( or as many cuts as I want to ) and have it saved in my own fileformet.
I does almost only know C++, done some hacking in other langs to.
Ask me if I'm unclear with my askings :)
**Edit2:**
I'm not a GUI tool programmer and have never done anything like a 3D editor, the most tools I've mada have been consolebased. Does anyone know a good startingpoint for a 3Dtool? ( like nehe.gamedev.net but for 3d tools instead of 3d games ) | Blender is the only decent one I know, why not taking a look in Youtube/Vimeo on some tutorials? There are plenty and it's quite fast to scrap with Video tutorials. | Not sure if it helps, but you might look at Wings 3D. Also, Blender is not that strange once you spend an hour working with it :-) | Does anyone know a good/easy/free/open 3d modeling program? | [
"",
"c++",
"3d",
"cross-platform",
"modeling",
""
] |
How to check if a url or url pattern is presnt or not in a string using javascript.
```
<script language="javascript">
var str="http://localhost/testprj?test=123213123";
var s=location.href;
if(s.match('/http://localhost/testprj?test=1232/'){
alert('welcome!!');
}
</script>
```
what i need is to check the url pattern.
complete code
```
<html>
<head>
</head>
<body>
<style>
.active{
color:#009900;
font-weight:bold;
}
</style>
<div id="menu">
<ul><li>
<ul><li> <a href="html1.html">0</a>
<a href="html.html" >1</a>
<a href="2">2</a>
</li>
</ul></li>
</ul>
</div>
<script language="javascript">
var c=document.getElementById('menu').getElementsByTagName('a').length;
var v=document.getElementById('menu').getElementsByTagName('a');
var s=location.href;
//alert(s.match('html'));
for(var i=0;i<c;i++){
//alert('href'+v[i].className);
if(v[i].href==location.href){
v[i].className='active';
}
}
</script>
</body>
</html>
```
this is working fine , but if the get params are cause some problms...
**like page.php?page=userlist**
works fine
but
**like page.php?page=userlist&id=121221**
this is the base link url
***link*** | Yes finaly i got the solution
i used the functions
```
for(var i=0;i<len;i++){
if(strstr(url,a[i].href)) {
a[i].className='active';
}
}
function strstr( url, href) {
var pos = 0;
url += '';
pos = url.indexOf( href );
if (pos == -1) {
return false;
}
else{
if(strcmp(url,href)==0)
return 1;
}
}
function strcmp ( str1, str2 ) {
return ( ( str1 == str2 ) ? 0 : ( ( str1 > str2 ) ? 1 : -1 ) );
}
```
like this way, its working fine!!!
Thank you | For pattern checking, you will want to look into [regular expressions](https://developer.mozilla.org/En/Core_JavaScript_1.5_Guide/Regular_Expressions).
What particular pattern do you want to check for? If you just want to check whether a string is a URL, the following code should do:
```
var myString = "http://blah.com/helloworld/";
if (myString.match(/http:\/\//)) {
alert("'myString' is a URL.");
}
``` | checking a pattern present in a string using javascript | [
"",
"javascript",
"regex",
"url",
""
] |
I'm getting this error message whiile running a Webservice I'm working on. it builds, but this happens when I Invoke:
```
File or assembly name (Redacted).Framework, or one of its dependencies, was not found
```
The stack trace shows that between my code and the target of the exception, there are 3 referenced DLLs and 4 layers of System.Reflection. How do I find what was passed into the method that threw the Exception, or at least find what dependency it's looking for and where it's looking for it?
I do not have access to the code nor symbols for the referenced DLLs that lie between my code and the Exception. | DependencyWalker helps in finding out which DLLs are missing. | You may be able to use the Assembly Binding Log Viewer:
<http://msdn.microsoft.com/en-us/library/e74a18c4.aspx> | C#: Finding a Missing Dependency | [
"",
"c#",
"exception",
"dependencies",
""
] |
Is it possible to create a web app that, with the help of a central server, could create direct connections with other users of the same web app? I'm imagining a process similar to UDP hole punching.
I've read about the new WebSockets API in HTML5, but it appears you must initiate the connection with a WS-compatible server before the fully-duplexed connection can begin. I'm thinking moreso about a process to make direct connections between clients, with a server getting involved *only* in the initial handshake.
NOTE: Java applets don't count. I'm interested only in standard browser technologies. | Instead of intelligent guesses, here is an informed answer:
HTML 5 plans to allow peer to peer connections from javascript, but these connections WILL NOT BE RAW TCP.
The complete spec can be found at <http://dev.w3.org/html5/websockets/>
jrh
EDIT: with specific reference to peer to peer connections, check out these links:
* Regarding peer to peer connections: <http://www.w3.org/TR/2008/WD-html5-20080122/#peer-to-peer>
* Regarding broadcast connections to the local network: <http://www.w3.org/TR/2008/WD-html5-20080122/#broadcast>
* Regarding TCP connections (in the encoded protocol): <http://www.w3.org/TR/2008/WD-html5-20080122/#tcp-connections>
* Complete proposed spec: <http://www.w3.org/TR/2008/WD-html5-20080122/#network>
Its important to note that the capabilities are still being negotiated. It will be nice to be able to create "local chat" web apps :)
jrh | **UPDATE 10/17/2012:** This functionality now exists in Chrome Stable v22. In order to use this functionality in Chrome, one must enable two flags in chrome://flags:
* Enable MediaStream
* Enable PeerConnection
Then you can visit the [AppRTC Demo Page](http://apprtc.appspot.com) to try out the demo. See the [WebRTC - Running the Demos](http://www.webrtc.org/running-the-demos) page for more detailed instructions on setting up Chrome to use the peer to peer functionality and enabling device capture.
---
**UPDATE:** The engineers at Ericcson Labs have a proof of concept in a WebKit build that does [HTML5 Peer to Peer Conversational Video](https://labs.ericsson.com/developer-community/blog/beyond-html5-peer-peer-conversational-video).
They have demonstrations in their blog of the technology in action, as well as diagrams and explanations on how the technology will work.
They are working on getting this stabilized and committed to the WebKit repository. | Will HTML5 allow web apps to make peer-to-peer HTTP connections? | [
"",
"javascript",
"ajax",
"html",
""
] |
I have found the way to copy the record that I would like, but now I am having a `violation of the Primary Key constraint`. Here is what I am trying to do:
We make a product that comes out of our maching into 2000 lbs bags and it is giving a number, e.g. 26273.
We store and sell it in those bags, but we also can sell it in smaller 50 lbs and 25 lbs bags.
When we convert the bag from 2000 lbs to 25 lbs the product takes up 80 bags.
Only 40 bags can be put onto a pallet, making the product number 26273 take up two pallets.
The problem we have is when we store the pallet we scan the barcode of the product and then scan the barcode of the warehouse location, ONE pallet per location, and only ONE location per pallet. If we have two pallets with the same number than we cannot store them in the warehouse.
To solve this problem my bosses what the first pallet to be number 26273B1 and the second pallet to be 26273B2 so that the pallets still contain the original number but is slighlty different in order to store them.
When the product receives a number it also goes through several tests and that data is part of the record so both of the records still nedd to contain those test results.
When I try to copy the record and place the B2 onto the number I get a **Primary Key Constraint ODBC Failure**. I know why I am getting the error, and I don't what to dissable the constraint to allow duplicate records, but I still need to have the ability to create this new record when we convert to 25lbs bags.
So my question: Is there any way to copy a record, slighty change the Primary Key while copying it, and still be able to save it without the `Primary Key Constraint error` occuring?
NOTE: the database is in `SQL` with the interface front-end is in **Access 2007**. | Why not store the original 2000 bag with the PK "26273-00-0000". That "00-0000" suffix indicates the original Bag.
For each subdivision into a smaller bag, "one-up" or increment the sequence that is suffixed at the end. You could use "00" for palletts, and "0000" for the bag-sequence number.
Hence "26273-B1-0001" - thru "26273-B1-0040" indicates the Product id that went into Pallett - one - the first 40 bags. | I am not sure how you are wanting to copy a record i.e. in a form or programatically.
Note you can have a Primary Key based on more than 1 column so provided the 2 columns together are unique then you will not violate the constraint. | Copying a record without Primary Key Constriant Error | [
"",
"sql",
"ms-access-2007",
"constraints",
""
] |
I'm want to implement thumbs up and down rating system in my web app using jquery. Please tell me some plug-in or code how to implement the thumbs up and down rating system in my website, please share links or resources.
Thanks | ### jQuery
This is nothing more than a roll-over effect, and an address that waits to update a database entry. It's not really jQuery. The "meat" of this would be your database and server-side scripting.
```
$("a.voteup").click(function(){
$.get("updatescore.php", {"id":"112","score":"1"}, function(response){
/* Do something with the response */
});
});
```
That code may be a bit off, but it's close enough to convey the point. From there, you would have a server-side script waiting to receive this:
### PHP / MySQL
**IMPORTANT:** Do not use as-is. Only for demonstration.
**ASP.NET:** I noticed from your past questions you are likely working within the .NET technologies. The process done here will still be faily similar. You'll handle the incoming request, require the user to be logged in, their score to be 1 or -1, and whatever else you wish.
```
session_start();
$userid = $_SESSION["userid"];
$vote = $_GET["score"]; /* Limit to 1 or -1 */
$article = $_GET["id"];
/* Whatever is printed here will be the 'response' variable
over in our jQuery callback function. Ideally, this function
would only allow the vote if the following are true:
1. User has not yet voted on this article
2. Score is 1 or -1
3. Voting is enabled on this article
4. User is indeed logged in */
print castVote($article, $vote, $userid);
?>
``` | here is a style with thumbs up and down using JQuery with a Backend in PHP/MySQL.
[Link to code](http://ad1987.blogspot.com/2009/02/reddit-style-voting-with-php-mysql-and.html) (You can try the demo online and all the source code is there) | JQuery: Thumbs up and down rating system? | [
"",
"javascript",
"jquery",
"ajax",
"rating",
""
] |
I need to extract all MP3 titles from a fuzzy list in a list.
With Python this works for me fine:
```
import re
for i in re.compile('mmc.+?mp3').findall(open("tracklist.txt").read()): print i
```
How can I do that in Ruby? | ```
f = File.new("tracklist.txt", "r")
s = f.read
s.scan(/mmc.+?mp3/) do |track|
puts track
end
```
What this code does is open the file for reading and reads the contents as a string into variable `s`. Then the string is scanned for the regular expression `/mmc.+?mp3/` ([`String#scan`](http://www.ruby-doc.org/core/classes/String.html#M001711) collects an array of all matches), and prints each one it finds. | I don't know python very well, but it should be
```
File.read("tracklist.txt").matches(/mmc.+?mp3/).to_a.each { |match| puts match }
```
or
```
File.read("tracklist.txt").scan(/mmc.+?mp3/) { |match| puts match }
``` | Equivalent to Python’s findall() method in Ruby? | [
"",
"python",
"ruby",
"regex",
""
] |
Doesn't value have to return toString() to be able to call value.toString()? When do you know you can call value.toString()?
```
<script>
var newList = function(val, lst)
{
return {
value: val,
tail: lst,
toString: function()
{
var result = this.value.toString();
if (this.tail != null)
result += "; " + this.tail.toString();
return result;
},
append: function(val)
{
if (this.tail == null)
this.tail = newList(val, null);
else
this.tail.append(val);
}
};
}
var list = newList("abc", null); // a string
list.append(3.14); // a floating-point number
list.append([1, 2, 3]); // an array
document.write(list.toString());
</script>
``` | [Every object in JavaScript has a toString() method.](https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Object/ToString) | As [Mr. Shiny and New](https://stackoverflow.com/questions/1050916/linked-list/1050999#1050999) states, *all* JavaScript objects have a `toString` method. However, that method is not always useful, especially for custom classes and object literals, which tend to return strings like `"[Object object]"`.
You can create your own `toString` methods by adding a function with that name to your class' prototype, like so:
```
function List(val, list) {
this.val = val;
this.list = list;
// ...
}
List.prototype = {
toString: function() {
return "newList(" + this.val + ", " + this.list + ")";
}
};
```
Now, if you create a `new List(...)` and call its `toString` method (or run it through any function or operator that converts it to a string implicitly), your custom `toString` method will be used.
Finally, to detect whether an object has a `toString` method defined for its class (note that this will **not** work with subclassing or object literals; that is left as an exercise for the reader), you can access its `constructor`'s `prototype` property:
```
if (value.constructor.prototype.hasOwnProperty("toString")) {
alert("Value has a custom toString!");
}
``` | When is it safe to use .toString()? | [
"",
"javascript",
"tostring",
""
] |
I want to run the following jquery code on every page in my website.
```
$(document).ready(function(){
$("#more").click(function(){
$("#morediv").slideToggle("slow");
return false;
});
});
```
In all my pages I have the `more` and `morediv` elements defined, for every page I have different js file and adding this code in every file will not be a good solution (I suppose).
I have created a `global.js` to include this code, but in other pages also I have the `$(document).ready(function(){}` function defined and may be that's why its conflicting and not running properly. | You can have multiple $(document).ready(function(){}) elements on your page, so that it's the problem. I suggest using Firefox/Firebug and examining any console errors you find to discover the problem. Perhaps your global.js file is being loaded before jQuery itself? Otherwise, you'll need to dig into it with Firebug's debugger. | Are you actually doing some server-side programming or you are talking about plain HTML pages. I would advise that you have templates (this is specific to your development environment and tools of choice) and include the JS in those templates. Then the actual pages will all use the template and have the JS available. The question you are asking has in fact nothing to do with Javascript or JQuery, but the way you organize your site... unless I'm missing something. | Jquery: how to register an event on all pages? | [
"",
"javascript",
"jquery",
"html",
""
] |
Is there a way to match a pattern (`e\d\d`) several times, capturing each one into a group? For example, given the string..
```
blah.s01e24e25
```
..I wish to get four groups:
```
1 -> blah
2 -> 01
3 -> 24
4 -> 25
```
The obvious regex to use is (in Python regex:
```
import re
re.match("(\w+).s(\d+)e(\d+)e(\d+)", "blah.s01e24e25").groups()
```
..but I also want to match either of the following:
```
blah.s01e24
blah.s01e24e25e26
```
You can't seem to do `(e\d\d)+`, or rather you can, but it only captures the last occurrence:
```
>>> re.match("(\w+).s(\d+)(e\d\d){2}", "blah.s01e24e25e26").groups()
('blah', '01', 'e25')
>>> re.match("(\w+).s(\d+)(e\d\d){3}", "blah.s01e24e25e26").groups()
('blah', '01', 'e26')
```
I want to do this in a single regex because I have multiple patterns to match TV episode filenames, and do not want to duplicate each expression to handle multiple episodes:
```
\w+\.s(\d+)\.e(\d+) # matches blah.s01e01
\w+\.s(\d+)\.e(\d+)\.e(\d+) # matches blah.s01e01e02
\w+\.s(\d+)\.e(\d+)\.e(\d+)\.e(\d+) # matches blah.s01e01e02e03
\w - \d+x\d+ # matches blah - 01x01
\w - \d+x\d+\d+ # matches blah - 01x01x02
\w - \d+x\d+\d+\d+ # matches blah - 01x01x02x03
```
..and so on for numerous other patterns.
Another thing to complicate matters - I wish to store these regexs in a config file, so a solution using multiple regexs and function calls is not desired - but if this proves impossible I'll just allow the user to add simple regexs
Basically, is there a way to capture a repeating pattern using regex? | After thinking about the problem, I think I have a simpler solution, using named groups.
The simplest regex a user (or I) could use is:
```
(\w+\).s(\d+)\.e(\d+)
```
The filename parsing class will take the first group as the show name, second as season number, third as episode number. This covers a majority of files.
I'll allow a few different named groups for these:
```
(?P<showname>\w+\).s(?P<seasonnumber>\d+)\.e(?P<episodenumber>\d+)
```
To support multiple episodes, I'll support two named groups, something like `startingepisodenumber` and `endingepisodenumber` to support things like `showname.s01e01-03`:
```
(?P<showname>\w+\)\.s(?P<seasonnumber>\d+)\.e(?P<startingepisodenumber>\d+)-(?P<endingepisodenumber>e\d+)
```
And finally, allow named groups with names matching `episodenumber\d+` (`episodenumber1`, `episodenumber2` etc):
```
(?P<showname>\w+\)\.
s(?P<seasonnumber>\d+)\.
e(?P<episodenumber1>\d+)
e(?P<episodenumber2>\d+)
e(?P<episodenumber3>\d+)
```
It still requires possibly duplicating the patterns for different amounts of `e01`s, but there will never be a file with two non-consecutive episodes (like `show.s01e01e03e04`), so using the `starting/endingepisodenumber` groups should solve this, and for weird cases users come across, they can use the `episodenumber\d+` group names
This doesn't really answer the sequence-of-patterns question, but it solves the problem that led me to ask it! (I'll still accept another answer that shows how to match `s01e23e24...e27` in one regex - if someone works this out!) | Do it in two steps, one to find all the numbers, then one to split them:
```
import re
def get_pieces(s):
# Error checking omitted!
whole_match = re.search(r'\w+\.(s\d+(?:e\d+)+)', s)
return re.findall(r'\d+', whole_match.group(1))
print get_pieces(r"blah.s01e01")
print get_pieces(r"blah.s01e01e02")
print get_pieces(r"blah.s01e01e02e03")
# prints:
# ['01', '01']
# ['01', '01', '02']
# ['01', '01', '02', '03']
``` | Regex and a sequences of patterns? | [
"",
"python",
"regex",
"sequences",
""
] |
I got some weird error with `response.redirect()` and the project wasn't building at all.. when I removed the *try-catch* block that was surrounding the block of code where `Response.Redirect()` was in it worked normally..
Just want to know if this is a known issue or something... | If I remember correctly, `Response.Redirect()` throws an exception to abort the current request (`ThreadAbortedException` or something like that). So you might be catching that exception.
Edit:
This [KB article](http://support.microsoft.com/kb/312629) describes this behavior (also for the `Request.End()` and `Server.Transfer()` methods).
For `Response.Redirect()` there exists an overload:
```
Response.Redirect(String url, bool endResponse)
```
If you pass `endResponse=false`, then the exception is not thrown (but the runtime will continue processing the current request).
If `endResponse=true` (or if the other overload is used), the exception is thrown and the current request will immediately be terminated. | As Martin points out, Response.Redirect throws a ThreadAbortException. The solution is to re-throw the exception:
```
try
{
Response.Redirect(...);
}
catch(ThreadAbortException)
{
throw; // EDIT: apparently this is not required :-)
}
catch(Exception e)
{
// Catch other exceptions
}
``` | Is there something that prevents Response.Redirect to work inside try-catch block? | [
"",
"c#",
".net",
"visual-studio-2008",
"try-catch",
""
] |
I am wanting to compress results from QUERYS of the database before adding them to the cache.
I want to be able to compress any reference type.
I have a working version of this for compressing strings.. the idea based on scott hanselman 's blog post <http://shrinkster.com/173t>
any ideas for compressing a .net object?
I know that it will be a read only cache since the objects in the cache will just be byte arrays.. | This won't work for **any** reference type. This will work for **Serializable** types. Hook up a `BinaryFormatter` to a compression stream which is piped to a file:
```
var formatter = new BinaryFormatter();
using (var outputFile = new FileStream("OutputFile", FileMode.CreateNew))
using (var compressionStream = new GZipStream(
outputFile, CompressionMode.Compress)) {
formatter.Serialize(compressionStream, objToSerialize);
compressionStream.Flush();
}
```
You could use a `MemoryStream` to hold the contents in memory, rather than writing to a file. I doubt this is really an effective solution for a cache, however. | What sort of objects are you putting in the cache? Are they typed objects? Or things like `DataTable`? For `DataTable`, then perhaps store as xml compressed through `GZipStream`. For typed (entity) objects, you'll probably need to serialize them.
You could use `BinaryFormatter` and `GZipStream`, or you could just use something like [protobuf-net](http://code.google.com/p/protobuf-net/) serialization (free) which is already very compact (adding `GZipStream` typically makes the data *larger* - which is typical of dense binary). In particular, the advantage of things like protobuf-net is that you get the reduced size without having to pay the CPU cost of unzipping it during deserialization. In [some tests](http://code.google.com/p/protobuf-net/wiki/Performance) *before* adding `GZipStream`, it was 4 times faster than `BinaryFormatter`. Add the extra time onto `BinaryFormatter` for GZip and it should win by a *considerable* margin. | How to compress a .net object instance using gzip | [
"",
"c#",
".net",
"asp.net",
"caching",
"compression",
""
] |
I'm porting a software that build from 16bit color depth to 18bit color depth. How can I convert the 16-bit colors to 18-bit colors? Thanks. | Without knowing the device, I can only speculate. Devices are typically Red, Green, Blue so each color would get 6 bits of variation. That means 64 variations of each color and a total of 262,144 colors.
Any bitmap can be scaled to this display. If you take each component (say, red), normalize it, then multiply by 64, you'll have the scaled version.
If you are asking something else or want more detail, please ask.
Update:
There are two 16-bit bitmap formats. One is 5-5-5 (5 bits per pixel) and the other is 5-6-5 (green gets an extra bit). I'll assume 5-5-5 for the sake of this conversion.
For each color within each pixel you need something like this:
```
NewColor = (oldColor/32.0)*64
```
This will turn the old color into a number between 0.0 and 1.0 and then scale it up to the new value range. | Assuming that the 16bit color is in 5-6-5 format:
```
// RRRRR-GGGGGG-BBBBB, 16bit -->
//RRRRR0-GGGGGG-BBBBB0, 18bit with the formula below:
Color18 = ((Color16 & 0xF800) << 2) | ((Color16 & 0x07E0) << 1) | ((Color16 & 0x1F) << 1);
``` | How to represent 18bit color depth to 16bit color depth? | [
"",
"c++",
"graphics",
"bitmap",
""
] |
I'm connecting to a LDAP directory in C#, so I've used the DirectoryEntry class.
When you do the "new DirectoryEntry" with address, login, and password it is supposed to connect to the LDAP directory.
However, even if the connection didn't work, it returns without problem, and the directoryentry variable is set.
So i do i know my connection is really opened ? Right now, I'm using a very very ugly hack : i put a "if(mydirectory.SchemaEntry)" which generates an exception if the connection wasn't etablished, because some of the members of the DirectoryEntry, such as SchemaEntry, aren't set if the connection failed. But 1:that's gotta be 11/10 on the ugliness scale 2:that takes a lot of time before failing.
So what is the good way to do this ? Surely, Microsoft must have provided something (even if I'm using a LDAP directory and not an Active Directory) to know if I'm really connected ? | Ok so marc\_s's solution was approximately what i was doing (except i was looking for SchemaEntry and not NativeObject). But the timeout delay is much too long (the query is run to fill autocompletion values for a form). I think I actually prefer to pretend the connection is open and let the query run. That way, i can set my own, smaller, timeout delay. | Just "newing" up a DirectoryEntry does **NOT** create a connection to the LDAP store.
Only once you start using its properties, or when you access the `.NativeObject` property explicitly, you'll actually get a connection to the LDAP store.
In order to make sure you're connected, just read out the `(DirectoryEntry).NativeObject` in a try...catch clause - if it bombs out, you have a problem, otherwise your connection is now up and active.
Unfortunately, to my knowledge, there is no property or method you can call to figure out whether or not you've successfully connected to LDAP using DirectoryEntry.
Marc | How to know if my DirectoryEntry is really connected to my LDAP directory? | [
"",
"c#",
"active-directory",
"ldap",
"directoryentry",
""
] |
I'm working on a calendar page that allows a user to click on a day, and enter an entry for that day with a form that pops up.
I'm no stranger to DOM manipulation with jQuery, but this is something I've done before and I'm beginning to wonder if there's a more efficient way to do this?
Would building the HTML manually within JavaScript be the most efficient way performancewise (I assume this is true, over using functions like appendTo() etc) or would creating a hidden construct within the DOM and then cloning it be better?
Ideally I want to know the optimal method of doing this to provide a balance between code neatness and performance.
Thanks,
Will | Working with huge chunks of HTML strings in JavaScript can become very ugly very quickly. For this reason it might be worth considering a JavaScript "template engine". They needn't be complicated - Check out **[this one](http://ejohn.org/blog/javascript-micro-templating/)** by Resig.
If you're not up for that then it's probably fine to just continue as you are. Just remember that DOM manipulation is generally quite slow when compared to string manipulation.
An example of this performance gap:
```
// DOM manipulation... slow
var items = ['list item 1', 'list item 2', 'list item 3'];
var UL = $('<ul/>');
$.each(items, function(){
UL.append('<li>' + this + '</li>');
});
// String manipulation...fast
var items = ['list item 1', 'list item 2', 'list item 3'];
var UL = $('<ul/>').append( '<li>' + items.join('</li><li>') + '</li>' );
``` | [Here](http://www.learningjquery.com/2009/03/43439-reasons-to-use-append-correctly) you can find the explanation. | What is the best way to inject HTML into the DOM with jQuery? | [
"",
"javascript",
"jquery",
"html",
"dom",
"code-injection",
""
] |
I am using PDF documents for various purposes using iText library.
Its like one class per PDF document. In a way there are a lot of similarities among the classes and the same have been listed below:
1. The fields have (x,y) location
2. The field can be wrapped after some no. of words
3. A field can have a value which is a function of one or more parameters
4. Subsequent page of PDF has to kept same or different
I am thinking of doing this layout business through a XML file. Any thoughts or innovative ideas of solving this are welcome. | take a look at PDFBox Library which is now in the incubator of Apache | PDFBox is nice, Used it before and good good help from the developer. You might want to have a look at XSL:FO. It is an XML based formatting language that can output the result as PDF (and other formats) using Apache:FOP. | Java - PDF Generation Framework | [
"",
"java",
"itext",
""
] |
let's say I have
```
public delegate DataSet AutoCompleteDelegate(
string filter, long rowOffset);
```
can I make the following class to enforce that method signature? (just a conjured up idea):
```
public class MiddleTier
{
[Follow(AutoCompleteDelegate)]
public DataSet Customer_AutoComplete(string filter, long rowOffset)
{
var c = Connect();
// some code here
}
[Follow(AutoCompleteDelegate)]
public DataSet Item_AutoComplete(string filter, long rowOffset)
{
var c = Connect();
// some code here
}
// this should give compilation error, doesn't follow method signature
[Follow(AutoCompleteDelegate)]
public DataSet BranchOffice_AutoComplete(string filter, string rowOffset)
{
var c = Connect();
// some code here
}
}
```
[EDIT]
Purpose: I already put attributes in my middletier's methods. I have methods like this:
```
public abstract class MiddleTier : MarshalByRefObject
{
// Operation.Save is just an enum
[Task("Invoice", Operation.Save)]
public Invoice_Save(object pk, DataSet delta);
[Task("Receipt", Operation.Save)]
public Receipt_Save(object pk, DataSet delta);
// compiler cannot flag if someone deviates from team's standard
[Task("Receipt", Operation.Save)]
public Receipt_Save(object pk, object[] delta);
}
```
then on runtime, i'll iterate all the middletier's methods and put them to collection(attributes helps a lot here), then map them on winform's delegate functions(facilitated by interface, plugins-based system) as loaded
I'm thinking if I can make the attributes more self-describing, so the compiler can catch inconsistencies.
```
namespace Craft
{
// public delegate DataSet SaveDelegate(object pk, DataSet delta); // defined in TaskAttribute
public abstract class MiddleTier : MarshalByRefObject
{
[Task("Invoice", SaveDelegate)]
public abstract Invoice_Save(object pk, DataSet delta);
[Task("Receipt", SaveDelegate)]
// it's nice if the compiler can flag an error
public abstract Receipt_Save(object pk, object[] delta);
}
}
```
I'm thinking if putting the methods on each class, it would be an overkill to always instantiate a Remoting object. And putting them on separate class, it could be harder to facilitate code reuse, let's say Invoice\_Save need some info on Receipt\_Open. In fact I even have a report here(crystal), which fetched data from Remoting middletier DataSet, inside the invoked method, it gets some info on other methods and merge in its own DataSet, they are all happening on middletier, no several roundtrips, all are done on server-side(middle-tier) | You could implement both the `FollowAttribute` you use in your example and [write a Static Analysis (say, FxCop) rule](http://www.binarycoder.net/fxcop/) that could check if any method that is tagged with that attribute has the same signature as the mentioned delegate. So it should be possible. | Other answers are obviously valid but nothing will guard you against forgetting to apply `[Follow(AutoCompleteDelegate)]` attribute on your method.
I think you would be better off making turning methods into classes that implement an interface:
```
public interface IAutoComplete
{
DataSet Complete(string filter, long rowOffset);
}
public class CustomerAutoComplele : IAutoComplete
{
public DataSet Complete(string filter, long rowOffset)
{
var c = Connect();
// some code here
}
}
```
and then use the [factory method pattern](http://en.wikipedia.org/wiki/Factory_method_pattern) to get your "auto completers":
```
public static class AutoCompleteFactory
{
public static IAutoComplete CreateFor(string purpose)
{
// build up and return an IAutoComplete implementation based on purpose.
}
}
```
or
```
public static class AutoCompleteFactory
{
public static IAutoComplete CreateFor<T>()
{
// build up and return an IAutoComplete implementation based on T which
// could be Customer, Item, BranchOffice class.
}
}
```
Once you have that you could have a look at inversion of control and dependency injection to avoid hard coding the list of auto complete implementations in your factory method. | Is there a way I can enforce a method to follow certain method signature? | [
"",
"c#",
"design-patterns",
"attributes",
"enforcement",
""
] |
I have some experience using parallel extensions in .Net development, but I was looking at doing some work in Java that would benefit from an easy to use parallelism library. Does the JVM offer any comparable tools to parallel-extensions? | There are some limited support in [java.util.concurrent](http://java.sun.com/j2se/1.5.0/docs/api/index.html?java/util/concurrent/package-summary.html) package since java 5, but full supports are [java 7 feature](http://tech.puredanger.com/java7/#jsr166). | You should become familiar with the [java.util.concurrent](http://java.sun.com/j2se/6/docs/api/index.html?java/util/concurrent/package-summary.html) package. It has simple and robust primitives for parallel programming upon which to base higher-level libraries. One example of such a library is [Functional Java](http://functionaljava.org), which has [an easy-to-use module for parallel programming](http://functionaljava.googlecode.com/svn/artifacts/2.20/javadoc/fj/control/parallel/ParModule.html).
For example, here is the canonical MapReduce example written using Functional Java. It counts the number of words in a set of documents, assuming documents are Streams of characters:
```
public static long countWords(final List<Stream<Character>> documents,
final ParModule m)
{ return m.parFoldMap(documents,
new F<Stream<Character>, Long>()
{ public Long f(final Stream<Character> document)
{ return (long)fromStream(document).words().length(); }},
longAdditionMonoid)
.claim(); }
```
To instantiate ParModule, you give it a parallel Strategy. You can implement your own Strategies, or use one that's supplied. Here's one that uses a fixed pool of 16 threads:
```
ExecutorService pool = newFixedThreadPool(16);
ParModule m = parModule(executorStrategy(pool));
```
You need the following imports for the example above:
```
import fj.F;
import fj.data.Stream;
import fj.control.parallel.ParModule;
import static fj.control.parallel.ParModule.parModule;
import static fj.pre.Monoid.longAdditionMonoid;
import static fj.data.LazyString.fromStream;
import static fj.control.parallel.Strategy.executorStrategy;
import static java.util.concurrent.Executors.newFixedThreadPool;
import java.util.concurrent.ExecutorService;
``` | Parallel Extensions Equivalent in Java | [
"",
"java",
".net",
"parallel-extensions",
""
] |
Is there any way to use server controls in ASP.NET MVC?
Specifically I need to use the FarPoint Spread control in my application to display an Excel file that exists on the server with the ability to display updates on the client in real time.
The reason that I want to use MVC instead of webforms is that eventually we're going to scrap the excel files and create the views programmatically but I have to display these files now since we don't have time to create that functionality in this phase. | My suggestion would be to use WebForms for pages that need the custom control and MVC for everything else. In order to mix WebForms in MVC in the same application you'll need an IgnoreRoute call so MVC doesn't try to process .aspx files and you need to make sure everything needed for WebForms gets added to the web.config. Scott Hanselman has a great blog post [here](http://www.hanselman.com/blog/PlugInHybridsASPNETWebFormsAndASPMVCAndASPNETDynamicDataSideBySide.aspx) with the details. | FarPoint recently released a Spread component which is supported on the MVC platform .You can go through which blog which gives detailed information on using Spread with MVC 3 .I hope this helps.
<http://www.gcpowertools.info/2011/12/using-grapecity-spread-for-net-with-mvc.html> | Excel files in ASP.Net MVC | [
"",
"javascript",
"asp.net-mvc",
"excel",
"farpoint-spread",
""
] |
I work in the maintenance team of a big project (around 7k+ classes) and my daily work is mainly to fix bugs. Sometimes, though, I have no bugs to work in. When this happens, I spent most of the time looking for performance gaps in the code. The fact that I have more than 7 thousand classes to look in means it's not obvious to find these gaps.
So I'd like to know **what simple things should I look for when trying to improve the performance of the system?**
I'm not asking about specific code techniques, but general ones. For example:
* I already looked for all occurrences of code like `String a = new String("")` and changed to `StringBuilder a = new StringBuilder();`
* I already changed all the access to the database, where applicable, to use `PreparedStatement`
* All of the `Debug` logging were removed, and the `Finest` ones were removed when possible
As you can see, *those changes could easily be made because they do not require measuring the system performance* -- the only thing I needed to do was using the search tool inside Eclipse. | Instead of focusing on performance, you may want to use some of the following static analysis tools to identify any bugs/potential bugs in code, and fix those. These will sometimes help identify performance issues:
* [FindBugs](http://findbugs.sourceforge.net/)
* [Crap4J](http://www.crap4j.org/)
Both of these include Eclipse plug ins. | Laudable goal, but you need to focus on the actual demonstrable performance problems -- not where you 'think' the performance problems are.
Spend time in a profiler to find the real issues...then go from there. Otherwise you're just churning code without any way of knowing whether you're making a measurable impact.
Even if you had a list of "things to change without measuring system performance" would you really trust them to be right for your circumstance?
In your situation I would suggest you spend time building test harnesses/performance instrumentation so you can see where to get the most bang for your buck.
EDIT:
To address the downvote(s) and sentiment about "I know using a PreparedStatement is faster" -- rather than asking for silver bullets, a better question to ask when faced with this issue is "how should I most productively spend my free time to make things better?" The OP clearly wants to improve the situation -- which is great...but without measuring "where it hurts" he's literally shooting in the dark. Is a PreparedStatement faster? Sure -- but if the real performance gremlin is in some other spot, why spend time 'fixing' the DB code when you could make a REAL impact by going after the actual points-of-pain?
One other thing: in a stable system such as the OP is describing, making code changes without good quantifiable justification is often considered bad practice, due to the risks introduced. In such stable systems, the question of risk/reward is for ANY code change must be considered. The risk is significant: many "simple, couldn't break anything" changes have slipped release schedules/introduced major problems. The reward? Uncertain, since you don't actually know if your change was responsible for a performance gain. Hence, we profile to make sure we're improving code which matters. | What should I look for when improving performance in Java? | [
"",
"java",
"performance",
""
] |
I am trying to convert numerical values written as words into integers. For example,
```
iPhone has two hundred and thirty thousand seven hundred and eighty three apps
```
would become
```
iPhone has 230783 apps
```
Is there any library or function that does this? | There are lots of pages discussing the conversion from numbers to words. Not so many for the reverse direction. The best I could find was some pseudo-code on Ask Yahoo. See <http://answers.yahoo.com/question/index?qid=20090216103754AAONnDz> for a nice algorithm:
> Well, overall you are doing two things: Finding tokens (words that translates to numbers) and applying grammar. In short, you are building a parser for a very limited language.
>
> The tokens you would need are:
>
> POWER: thousand, million, billion
> HUNDRED: hundred
> TEN: twenty, thirty... ninety
> UNIT: one, two, three, ... nine,
> SPECIAL: ten, eleven, twelve, ... nineteen
>
> (drop any "and"s as they are meaningless. Break hyphens into two tokens. That is sixty-five should be processed as "sixty" "five")
>
> Once you've tokenized your string, move from RIGHT TO LEFT.
>
> 1. Grab all the tokens from the RIGHT until you hit a POWER or the whole string.
> 2. Parse the tokens after the stop point for these patterns:
>
> SPECIAL
> TEN
> UNIT
> TEN UNIT
> UNIT HUNDRED
> UNIT HUNDRED SPECIAL
> UNIT HUNDRED TEN
> UNIT HUNDRED UNIT
> UNIT HUNDRED TEN UNIT
>
> (This assumes that "seventeen hundred" is not allowed in this grammar)
>
> This gives you the last three digits of your number.
> 3. If you stopped at the whole string you are done.
> 4. If you stopped at a power, start again at step 1 until you reach a higher POWER or the whole string. | Old question, but for anyone else coming across this I had to write up a solution to this today. The following takes a vaguely similar approach to the algorithm described by John Kugelman, but doesn't apply as strict a grammar; as such it will permit some weird orderings, e.g. "one hundred thousand and one million" will still produce the same as "one million and one hundred thousand" (1,100,000). Invalid bits (e.g. misspelled numbers) will be ignored, so the consider the output on invalid strings to be undefined.
Following user132513's comment on joebert's answer, I used Pear's Number\_Words to generate test series. The following code scored 100% on numbers between 0 and 5,000,000 then 100% on a random sample of 100,000 numbers between 0 and 10,000,000 (it takes to long to run over the whole 10 billion series).
```
/**
* Convert a string such as "one hundred thousand" to 100000.00.
*
* @param string $data The numeric string.
*
* @return float or false on error
*/
function wordsToNumber($data) {
// Replace all number words with an equivalent numeric value
$data = strtr(
$data,
array(
'zero' => '0',
'a' => '1',
'one' => '1',
'two' => '2',
'three' => '3',
'four' => '4',
'five' => '5',
'six' => '6',
'seven' => '7',
'eight' => '8',
'nine' => '9',
'ten' => '10',
'eleven' => '11',
'twelve' => '12',
'thirteen' => '13',
'fourteen' => '14',
'fifteen' => '15',
'sixteen' => '16',
'seventeen' => '17',
'eighteen' => '18',
'nineteen' => '19',
'twenty' => '20',
'thirty' => '30',
'forty' => '40',
'fourty' => '40', // common misspelling
'fifty' => '50',
'sixty' => '60',
'seventy' => '70',
'eighty' => '80',
'ninety' => '90',
'hundred' => '100',
'thousand' => '1000',
'million' => '1000000',
'billion' => '1000000000',
'and' => '',
)
);
// Coerce all tokens to numbers
$parts = array_map(
function ($val) {
return floatval($val);
},
preg_split('/[\s-]+/', $data)
);
$stack = new SplStack; // Current work stack
$sum = 0; // Running total
$last = null;
foreach ($parts as $part) {
if (!$stack->isEmpty()) {
// We're part way through a phrase
if ($stack->top() > $part) {
// Decreasing step, e.g. from hundreds to ones
if ($last >= 1000) {
// If we drop from more than 1000 then we've finished the phrase
$sum += $stack->pop();
// This is the first element of a new phrase
$stack->push($part);
} else {
// Drop down from less than 1000, just addition
// e.g. "seventy one" -> "70 1" -> "70 + 1"
$stack->push($stack->pop() + $part);
}
} else {
// Increasing step, e.g ones to hundreds
$stack->push($stack->pop() * $part);
}
} else {
// This is the first element of a new phrase
$stack->push($part);
}
// Store the last processed part
$last = $part;
}
return $sum + $stack->pop();
}
``` | Converting words to numbers in PHP | [
"",
"php",
"nlp",
"numbers",
""
] |
Do most people use .NET's SqlMembershipProvider, SqlRoleProvider, and SqlProfileProvider when developing a site with membership capabilities?
Or do many people make their own providers, or even their own membership systems entirely?
What are the limitations of the SQL providers that would make you roll your own?
Is it easy to extend the SQL providers to provide additional functionality?
**For Reference**
[Per Scott Gu's Blog](http://weblogs.asp.net/scottgu/archive/2006/04/13/442772.aspx), [Microsoft provides the source code for the SqlMembershipProvider](http://download.microsoft.com/download/a/b/3/ab3c284b-dc9a-473d-b7e3-33bacfcc8e98/ProviderToolkitSamples.msi) so that you can customize it, instead of starting from scratch. Just an FYI. | We use everything except the Profile Provider. The Profile Provider is completly text based and does full text seearches - this becomes exceedingly slow as you user base gets larger. We have found it a much better solution to "role our own" profile section of the membership api database that is keyed to the userid in membership. | I've rolled my own `MembershipProvider` classes using derived `MembershipUser` types to wrap the custom user schema, so profile-style properties are now available everywhere as part of the derived user via a cast. | Do most people use .NET's SqlMembershipProvider, SqlRoleProvider, and SqlProfileProvider? | [
"",
"c#",
"asp.net",
"sqlmembershipprovider",
"sqlroleprovider",
"sqlprofileprovider",
""
] |
The code below removes "www.", etc. from the beginning of websites that are entered into a database. It works great.
Is there a way I could use similar code to remove a forward-slash from the tail-end of a website that is entered into the same database?
```
$remove_array = array('http://www.', 'http://', 'https://', 'https://www.', 'www.');
$site = str_replace($remove_array, "", $_POST['site']);
``` | ```
$site = preg_replace('{/$}', '', $site);
```
This uses a relatively simple [regular expression](http://us.php.net/manual/en/book.pcre.php). The `$` means only match slashes at the end of the string, so it won't remove the first slash in `stackoverflow.com/questions/`. The curly braces `{}` are just delimiters; PHP requires matching characters and the front and back of regular expressions, for some silly reason. | You can pass a string of characters that you want trimmed off of a string to the [`trim`](https://www.php.net/trim) family of functions. Also, you could use `rtrim` to trim just the end of the string:
```
$site = rtrim($site, "/");
``` | Removing a forward-slash from the tail-end of an URL | [
"",
"php",
""
] |
```
<?php if (isset($_GET['action']) && (!$_GET['action'] == 'reply')) { ?>
<div class="actions">
<input type="button" onclick="javascript: document.location='?threadID=<?=$threadID?>&action=reply';" value="Post reply" class="btn" />
</div>
<?php } ?>
```
I want to hide this when I'm calling reply. It doesn't show at all.
Can you see the problem? | I suspect that the first time you hit this page, there's no action parameter in the URL. If so, then isset() is going to be false. Also, you probably want !=, rather than ! ... == ....
I haven't tested this code, but here's where I would start:
```
<?php if (!isset($_GET['action']) || ($_GET['action'] != 'reply')) { ?>
<div class="actions">
<input type="button" onclick="javascript: document.location='?threadID=<?=$threadID?>&action=reply';" value="Post reply" class="btn" />
</div>
<?php } ?>
```
I also find this format slightly easier to read:
```
<?php if (!isset($_GET['action']) || ($_GET['action'] != 'reply')): ?>
<div class="actions">
<input type="button" onclick="javascript: document.location='?threadID=<?=$threadID?>&action=reply';" value="Post reply" class="btn" />
</div>
<?php endif; ?>
``` | try
`if (isset($_GET['action']) && $_GET['action'] !== 'reply') {` | PHP GET control statements | [
"",
"php",
"html",
"forms",
""
] |
i have a list of lists that looks like this:
```
dupe = [['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'apa.txt'], ['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', 'knark.txt'], ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'apa2.txt'], ['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', 'jude.txt']]
```
I write it to a file using a very basic function():
```
try:
file_name = open("dupe.txt", "w")
except IOError:
pass
for a in range (len(dupe)):
file_name.write(dupe[a][0] + " " + dupe[a][1] + " " + dupe[a][2] + "\n");
file_name.close()
```
With the output in the file looking like this:
```
95d1543adea47e88923c3d4ad56e9f65c2b40c76 ron\c apa.txt
95d1543adea47e88923c3d4ad56e9f65c2b40c76 ron\c knark.txt
b5cc17d3a35877ca8b76f0b2e07497039c250696 ron\a apa2.txt
b5cc17d3a35877ca8b76f0b2e07497039c250696 ron\a jude.txt
```
However, how can i make the output in the dupe.txt file to look like this:
```
95d1543adea47e88923c3d4ad56e9f65c2b40c76 ron\c apa.txt, knark.txt
b5cc17d3a35877ca8b76f0b2e07497039c250696 ron\a apa2.txt, jude.txt
``` | First, group the lines by the "key" (the first two elements of each array):
```
dupedict = {}
for a, b, c in dupe:
dupedict.setdefault((a,b),[]).append(c)
```
Then print it out:
```
for key, values in dupedict.iteritems():
print ' '.join(key), ', '.join(values)
``` | i take it your last question didn't solve your problem?
instead of putting each list with repeating ID's and directories in seperate lists, why not make the file element of the list another sub list which contains all the files which have the same id and directory.
so dupe would look like this:
```
dupe = [['95d1543adea47e88923c3d4ad56e9f65c2b40c76', 'ron\\c', ['apa.txt','knark.txt']],
['b5cc17d3a35877ca8b76f0b2e07497039c250696', 'ron\\a', ['apa2.txt','jude.txt']]
```
then your print loop could be similar to:
```
for i in dupe:
print i[0], i[1],
for j in i[2]
print j,
print
``` | Formatting output when writing a list to textfile | [
"",
"python",
"list",
""
] |
I've got a simple method that does this:
```
private void searchButton_Click(object sender, EventArgs e)
{
searchResultsBox.Hide();
doSomething();
}
```
searchResultsBox is a listbox, and when I call its Hide method, it doesn't actually completely vanish until 'doSomething' finishes processing. It kind of leaves artifacts (in fact you can still see any part of the box that had an empty form surface behind it.
If I comment out 'doSomething', it vanishes promptly.
Any ideas on how to fix this? It's just a bit ugly. | You could try calling this.refresh() after calling searchResultsBox.Hide(); | You should not do significant work in the GUI event thread, as it will cause the UI to freeze up while it is busy running your event handling code. It is a good practice to do any long-running tasks in another thread, either by signaling another already-running thread to do the work or by starting a new thread on the spot.
```
new Thread(new ThreadStart(doSomething)).Start();
``` | Listbox not completely vanishing on hide | [
"",
"c#",
"forms",
""
] |
I have got myself stuck into a really amazing issue here.The code is like as below.
```
class A
{
public:
A(){
m_event = CreateEvent(NULL, false, false, NULL); // create an event with initial value as non-signalled
m_thread = _beginthread(StaticThreadEntry, 0, this); // create a thread
}
static void StaticThreadEntry(A * obj) { obj->ThreadEntry(); }
void ThreadEntry();
};
void A::ThreadEntry()
{
WaitforSingleObject(m_event,INFINITE);
}
int main()
{
A a;
SetEvent(m_event); // sets the event to signalled state which causes the running thread to terminate
WaitForSingleObject(m_thread, INFINITE); // waits for the thread to terminate
return 0;
}
```
Problem :
When the above code is run,sometimes( 1 out of 5 ) it hangs and the control gets stuck in the call to WaitforSingleObject()( inside the main function ).The code always calls SetEvent() function to ensure that the thread would terminate before calling Wait() function.
I do not see any reason why it should ever hang? | The problem is your use of the \_beginthread API. You cannot use the handle returned from this function with the Win32 wait functions. You should use \_beginthreadex or CreateThread. From MSDN:
> If successful, each of these functions returns a handle to the newly created thread; however, if the newly created thread exits too quickly, \_beginthread might not return a valid handle...
>
> You are ... able to use the thread handle returned by \_beginthreadex with the synchronization APIs, which you cannot do with \_beginthread. | I don't see any issues in the code (Assuming event is created before the thread is started in constructor).
* The event is a auto reset event and
the initial state is non signaled.
* Child thread has to wait until the
event is signaled.
* Main thread will signal the event and
waits for child process to terminate.
Assuming this is the complete code (not the sample code ), it looks quite fine to me.
I suggest you to use [process Explorer](http://technet.microsoft.com/en-us/sysinternals/bb896653.aspx) to observe the state of the event.
**EDIT**:
There is a slight chance that child thread gets terminated before the main thread waits on the thread handle. If the handle is reused for some other kernel objects and main thread will wait infinitely.
Try duplicating the handle using [DuplicateHandle](http://msdn.microsoft.com/en-us/library/ms724251(VS.85).aspx) after thread creation and use this handle in WaitForSingleObject. | WaitForSingleObject( ) | [
"",
"c++",
"multithreading",
"winapi",
""
] |
I am doing a testing scenario
6 people in each Site
```
Site 1 - A, B, C, D, E, F
Site 2 - G, H, I, J, K, L
Site 3 - M, N, O, P, Q, R
Site 4 - S, T, U, V, W, X
```
I want to write a query that can suggests me datewise the people who can test the site - two at a time. Here are the rules:
**Rule 1:** If a person has tested his site on Day 1, then his turn should come on Day 4 and not before that - APPLICABLE ONLY FOR CURRENT WEEK. So if A and D test a site on 22nd, B and E test it on 23rd and C and F test on 24th, then for this week, A and D can test the site only on 25th. Sunday is a holiday
**Rule 2:** Every week, the pair should change. Rule 1 is still applicable with the new pair.
**Rule 3:** A person belonging to a particular site cannot test other sites.
> In the query, I should be able to
> later change the pair from 2 people
> and make them 3 people at a time or
> increase the people on each sites from 6 to 10, with
> few changes to the code.
**SAMPLE DATA**
```
DECLARE @Site TABLE
(
SiteID int,
SiteNm varchar(10)
)
DECLARE @Person TABLE
(
PersonID int,
PersonName char(1),
SiteID int
)
INSERT @Site
SELECT 1, 'Site1' UNION ALL
SELECT 2, 'Site2' UNION ALL
SELECT 3, 'Site3' UNION ALL
SELECT 4, 'Site4'
INSERT @Person
SELECT 1, 'A', 1 UNION ALL
SELECT 2, 'B', 1 UNION ALL
SELECT 3, 'C', 1 UNION ALL
SELECT 4, 'D', 1 UNION ALL
SELECT 5, 'E', 1 UNION ALL
SELECT 6, 'F', 1 UNION ALL
SELECT 7, 'G', 2 UNION ALL
SELECT 8, 'H', 2 UNION ALL
SELECT 9, 'I', 2 UNION ALL
SELECT 10, 'J', 2 UNION ALL
SELECT 11, 'K', 2 UNION ALL
SELECT 12, 'L', 2 UNION ALL
SELECT 13, 'M', 3 UNION ALL
SELECT 14, 'N', 3 UNION ALL
SELECT 15, 'O', 3 UNION ALL
SELECT 16, 'P', 3 UNION ALL
SELECT 17, 'Q', 3 UNION ALL
SELECT 18, 'R', 3 UNION ALL
SELECT 19, 'S', 4 UNION ALL
SELECT 20, 'T', 4 UNION ALL
SELECT 21, 'U', 4 UNION ALL
SELECT 22, 'V', 4 UNION ALL
SELECT 23, 'W', 4 UNION ALL
SELECT 24, 'X', 4
```
**Here's how I want the Output:**
```
Date Site 1 Site 2 Site 3 Site 4
22Jun A,D H,I N,R T,W
23Jun B,E J,K M,P V,X
...
26Jun A,D H,I N,R T,W
...
29Jun F,A K,L R,Q W,U
```
and so on
Can you help me with the query?
> In the query, I should be able to
> later change the pair from 2 people
> and make them 3 people at a time or
> increase the people on each sites from 6 to 10, with
> few changes to the code. I want this flexibility | ```
WITH sets AS
(
SELECT SiteID, SUBSTRING(CAST(PersonID AS VARCHAR(MAX)) + SPACE(8), 1, 8)AS result, 1 AS rn
FROM @Person p
UNION ALL
SELECT p2.SiteID, s.result + SUBSTRING(CAST(PersonID AS VARCHAR(MAX)) + SPACE(8), 1, 8), rn + 1
FROM sets s
JOIN @Person p2
ON p2.siteid = s.siteid
AND PATINDEX('%' + SUBSTRING(CAST(PersonID AS VARCHAR(MAX)) + SPACE(8), 1, 8) + '%', s.result) = 0
),
cal AS
(
SELECT 1 AS rn
UNION ALL
SELECT rn + 1
FROM cal
WHERE rn < 99
),
pairs AS
(
SELECT SiteId, result, ROW_NUMBER() OVER (PARTITION BY siteid ORDER BY rn2 % 30) pn
FROM (
SELECT s.*,
ROW_NUMBER() OVER (PARTITION BY siteid ORDER BY siteid) AS rn2
FROM sets s
WHERE rn = 6
) q
WHERE rn2 % 2 > 0
AND rn2 % 12 > 5
AND rn2 % 240 > 119
)
SELECT CAST('2009-01-01' AS DATETIME) + rn, siteid,
SUBSTRING(result, 1 + (rn % 3) * 16, 8) AS first,
SUBSTRING(result, 1 + (rn % 3) * 16 + 8, 8) AS second
FROM cal
JOIN pairs
ON pn = (rn / 7 + 1)
AND DATEPART(weekday, CAST('2009-01-01' AS DATETIME) + rn) <> 1
``` | This is not something SQL is meant to handle. I would DEFINATELY move this sort of algorithmic logic to code.
If, for some reason, you can't move it to the code and absolutely have to get the predictive information from the database, I would consider a CLR assembly in SqlSever if you are using MS SQL Server 2005 or 2008.
[Reference from MSDN on how to use CLR in SQL](http://msdn.microsoft.com/en-us/library/ms254498(VS.80).aspx) | Tricky question on predicting next records | [
"",
"sql",
"sql-server",
""
] |
I'm working on a video codec for OMAP3430. I already have code written in C++, and I try to modify/port certain parts of it to take advantage of the DSP (the SDK (OMAP ZOOM3430 SDK) I have has an additional DSP).
I tried to port a small for loop which is running over a very small amount of data (~250 bytes), but about 2M times on different data. But the overload from the communication between CPU and DSP is much more than the gain (if I have any).
I assume this task is much like optimizing a code for the GPU's in normal computers. My question is porting what kind of parts would be beneficial? How do GPU programmers take care of such tasks?
## edit:
1. GPP application allocates a buffer of size 0x1000 bytes.
2. GPP application invokes DSPProcessor\_ReserveMemory to reserve a DSP virtual address space for each allocated buffer using a size that is 4K greater than the allocated buffer to account for automatic page alignment. The total reservation size must also be aligned along a 4K page boundary.
3. GPP application invokes DSPProcessor\_Map to map each allocated buffer to the DSP virtual address spaces reserved in the previous step.
4. GPP application prepares a message to notify the DSP execute phase of the base address of virtual address space, which have been mapped to a buffer allocated on the GPP. GPP application uses DSPNode\_PutMessage to send the message to the DSP.
5. GPP invokes memcpy to copy the data to be processed into the shared memory.
6. GPP application invokes DSPProcessor\_FlushMemory to ensure that the data cache has been flushed.
7. GPP application prepares a message to notify the DSP execute phase that it has finished writing to the buffer and the DSP may now access the buffer. The message also contains the amount of data written to the buffer so that the DSP will know just how much data to copy. The GPP uses DSPNode\_PutMessage to send the message to the DSP and then invokes DSPNode\_GetMessage to wait to hear a message back from the DSP.
After these the execution of DSP program starts, and DSP notifies the GPP with a message when it finishes the processing. Just to try I don't put any processing inside the DSP program. I just send a "processing finished" message back to the GPP. And this still consumes a lot of time. Could that be because of the internal/external memory usage, or is it merely because of the communication overload? | From the measurements I did, one messaging cycle between CPU and DSP takes about 160us. I don't know whether this is because of the kernel I use, or the bridge driver; but this is a very long time for a simple back & forth messaging.
It seems that it is only reasonable to port an algorithm to DSP if the total computational load is comparable to the time required for messaging; and if the algorithm is suitable for simultaneous computing on CPU and DSP. | The OMAP3430 does not have an on board DSP, it has a IVA2+ Video/Audio decode engine hooked to the system bus and the Cortex core has DSP-like SIMD instructions. The GPU on the OMAP3430 is a PowerVR SGX based unit. While it does have programmable shaders and i don't believe there is any support for general purpose programming ala CUDA or OpenCL. I could be wrong but I've never heard of such support
If your using the IVA2+ encode/decode engine that is on board you need to use the proper libraries for this unit and it only supports specific codecs from that I know. Are you trying to write your own library to this module?
If your using the Cortex's built in DSPish (SIMD instructions), post some code.
If your dev board has some extra DSP on it, what is the DSP and how is it connected to the OMAP?
As to the desktop GPU question, in the case of video decode you use the vender supplied function libraries to make calls to the hardware, there are several, VDAPU for Nvidia on linux, similar libraries on windows(PureViewHD I think its called). ATI also has both linux and windows libraries for their on board decode engines, i don't know the names. | How to use DSP to speed-up a code on OMAP? | [
"",
"c++",
"c",
"embedded",
"signal-processing",
"omap",
""
] |
This has been bugging me for years now, and I thought one of you fine people would know - in Eclipse's .classpath files, what is the combineaccessrules attribute of the classpathentry element actually used for?
I can see in the Java Build Path config dialog that it can be maniuplated, but I can't think of a good use case for it. If I muck about with the settings, or modify the .classpath file manually, it doesn't seem to have any effect.
I'm hoping someone else has put it to good use, and I can steal their ideas. Basically, it's an itch I'm trying to scratch. | With proper use of access rules you can prevent using "internal" and/or "non-api" classes and methods. When you add a class or package as *Forbidden* or *Discouraged* the compiler show an error or warning when you use that class or class from the specified package. For a longer introduction of access rules you should read [this short article](http://www.eclipsezone.com/eclipse/forums/t53736.html).
For using combine access rules imagine the following situation:
* You have 2 projects, A and B.
* On the classpath of project A there is a jar file that is exported. The jar contains some "stable api", "unstable api" and "non-api" public classes.
* Project B depends on project A.
You do not allow using "non-api" classes in project A so you set some *Forbidden* access rules on those classes / packages.
In project B you do not allow using "non-api" as well, but you do want to get a warning when using "unstable api". In this case in project B you only have to set the additional *Discouraged* access rules if you check the *Combine rules with the access rules of the exported project entries*. | Access rules are handy little things, but dangerous. They exclude a source file from the project compiler but leave the file intact in the filesystem.
The project I work on has a bootstrap class in one of our source folders, but if we include the entire folder the project classpath it won't compile (it's a long story and the build process handles this).
So we use an eclipse access rule to exclude it and it never bothers us during development. This means we can't easily change the code, but it's one of those classes that literally hasn't been touched in years.
Combine Access Rules, judging by the JavaDoc, is a real edge use case. To use it you would have to have:
* an access rule in an exported source entry of one project
* a link to that project from a parent project
* a need to combine the access rules of the sub project with the parent
I really can't say how it would be useful, but I hope that at least answers your "what is it" question :) | What does combineaccessrules mean in Eclipse classpaths? | [
"",
"java",
"eclipse",
"classpath",
""
] |
I have this URL:
```
site.fwx?position=1&archiveid=5000&columns=5&rows=20&sorting=ModifiedTimeAsc
```
what I need is to be able to change the 'rows' url param value to something i specify, lets say 10. And if the 'rows' doesn't exist, I need to add it to the end of the url and add the value i've already specified (10). | To answer my own question 4 years later, after having learned a lot. Especially that you shouldn't use jQuery for everything. I've created a simple module that can parse/stringify a query string. This makes it easy to modify the query string.
You can use [query-string](https://github.com/sindresorhus/query-string) as follows:
```
// parse the query string into an object
var q = queryString.parse(location.search);
// set the `row` property
q.rows = 10;
// convert the object to a query string
// and overwrite the existing query string
location.search = queryString.stringify(q);
``` | I've extended Sujoy's code to make up a function.
```
/**
* http://stackoverflow.com/a/10997390/11236
*/
function updateURLParameter(url, param, paramVal){
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL) {
tempArray = additionalURL.split("&");
for (var i=0; i<tempArray.length; i++){
if(tempArray[i].split('=')[0] != param){
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
var rows_txt = temp + "" + param + "=" + paramVal;
return baseURL + "?" + newAdditionalURL + rows_txt;
}
```
Function Calls:
```
var newURL = updateURLParameter(window.location.href, 'locId', 'newLoc');
newURL = updateURLParameter(newURL, 'resId', 'newResId');
window.history.replaceState('', '', updateURLParameter(window.location.href, "param", "value"));
```
Updated version that also take care of the anchors on the URL.
```
function updateURLParameter(url, param, paramVal)
{
var TheAnchor = null;
var newAdditionalURL = "";
var tempArray = url.split("?");
var baseURL = tempArray[0];
var additionalURL = tempArray[1];
var temp = "";
if (additionalURL)
{
var tmpAnchor = additionalURL.split("#");
var TheParams = tmpAnchor[0];
TheAnchor = tmpAnchor[1];
if(TheAnchor)
additionalURL = TheParams;
tempArray = additionalURL.split("&");
for (var i=0; i<tempArray.length; i++)
{
if(tempArray[i].split('=')[0] != param)
{
newAdditionalURL += temp + tempArray[i];
temp = "&";
}
}
}
else
{
var tmpAnchor = baseURL.split("#");
var TheParams = tmpAnchor[0];
TheAnchor = tmpAnchor[1];
if(TheParams)
baseURL = TheParams;
}
if(TheAnchor)
paramVal += "#" + TheAnchor;
var rows_txt = temp + "" + param + "=" + paramVal;
return baseURL + "?" + newAdditionalURL + rows_txt;
}
``` | Change URL parameters and specify defaults using JavaScript | [
"",
"javascript",
"url",
"query-string",
"url-parameters",
"url-parsing",
""
] |
I'm kind of stuck with my heap sort here in php:
```
<?php
function heapSort($a, $count){
$a = heapify($a, $count);
$end = $count - 1;
while ($end > 0){
$temp = $a[$end];
$a[$end] = $a[0] ;
$a[0]= $temp;
$end = $end - 1;
siftDown($a, 0, $end);
}
return $a;
}
```
---
```
function heapify($a,$count){
$start = ($count - 2) / 2;
while ($start >= 0){
$a = siftDown($a, $start, $count-1);
$start = $start - 1;
}
return $a;
}
```
---
```
function siftDown($a, $start, $end){
$root = $start;
while ($root * 2 + 1 <= $end){// While the root has at least one child
$child = $root * 2 + 1; // root*2+1 points to the left child
//If the child has a sibling and the
//child's value is less than its
//sibling's
if ($child + 1 <= $end and $a[$child] < $a[$child + 1])
$child = $child + 1;// then point to the right child instead)
if ($a[$root] < $a[$child]){ // out of max-heap order
list($a[$child],$a[$root]) = array($a[$root],$a[$child]);
$root = $child; // repeat to continue sifting down
// the child now
}
else {
return $a;
}}
return $a;
}
$a = Array(3,1,5,2);
$b = heapSort($a,count($a));
print_r($b);
?>
```
I can't get to sort the array, any idea what's wrong? | siftDown() is suposed to alter the array you pass in. Therefore you have to pass it by reference. Otherwise the function will operate on a copy of the data.
```
function siftDown(&$a, $start, $end) {
``` | I think this is simplest code for [heap Sort in php](http://phpcyborg.blogspot.com/2011/04/heap-sort-in-php.html) | Need help with my heap sort | [
"",
"php",
"sorting",
"heap",
""
] |
I'm using PHP to pass a login form when required, and here is the code:
```
$htmlForm = '<form id="frmlogin">'.'<label>';
switch(LOGIN_METHOD)
{
case 'both':
$htmlForm .= $ACL_LANG['USERNAME'].'/'.$ACL_LANG['EMAIL'];
break;
case 'email':
$htmlForm .= $ACL_LANG['EMAIL'];
break;
default:
$htmlForm .= $ACL_LANG['USERNAME'];
break;
}
$htmlForm .= ':</label>'.
'<input type="text" name="u" id="u" class="textfield" />'.
'<label>'.$ACL_LANG['PASSWORD'].'</label>'.
'<input type="password" name="p" id="p" class="textfield" />'.
'<center><input type="submit" name="btn" id="btn" class="buttonfield" value="Sign in to extranet" /></center>'.
'</form>';
return $htmlForm;
```
The problem is, is that when the user hits enter in IE8, the form does not submit, and the user is forced to hit the submit button.
How do I rectify this? | If this is a real problem and you can't find another solution you can always do an `onkeypress` event for the form and check if the `Enter` key was pressed.
EDIT:
Here's the correct code according to Machine's answer:
```
$htmlForm .= ':<form><label>'.$ACL_LANG['USERNAME'].'</label>'.
'<input type="text" name="u" id="u" class="textfield" />'.
'<label>'.$ACL_LANG['PASSWORD'].'</label>'.
'<input type="password" name="p" id="p" class="textfield" />'.
'<center><input type="submit" name="btn" id="btn" class="buttonfield" value="Sign in to extranet" /></center>'.
'</form>';
```
EDIT 2:
Your HTML is valid.
Try [this](http://jennifermadden.com/javascript/stringEnterKeyDetector.html):
```
function checkEnter(e) { //e is event object passed from function invocation
var characterCode //literal character code will be stored in this variable
if (e && e.which) { //if which property of event object is supported (NN4)
e = e
characterCode = e.which //character code is contained in NN4's which property
}
else {
e = event
characterCode = e.keyCode //character code is contained in IE's keyCode property
}
if (characterCode == 13) { //if generated character code is equal to ascii 13 (if enter key)
document.forms[0].submit() //submit the form
return false
}
else {
return true
}
}
``` | Also watch out for this fun fun bug:
I've learned the hard way that if your form is `display:none` at page load, even if you show it later with Javascript, IE8 still won't submit on enter.
However, if it's not hidden at page load, and you set it to `display:none` after, like onDOMReady, then it works! WTF
More details and workaround here: <http://www.thefutureoftheweb.com/blog/submit-a-form-in-ie-with-enter> | Hitting "enter" does not post form in IE8 | [
"",
"php",
"html",
"forms",
"submit",
"form-submit",
""
] |
I want to check whether a string is a file name (name DOT ext) or not.
Name of file cannot contain `/ ? * : ; { } \`
Could you please suggest me the regex expression to use in preg\_match()? | Here you go:
```
"[^/?*:;{}\\]+\\.[^/?*:;{}\\]+"
```
"One or more characters that aren't any of these ones, then a dot, then some more characters that aren't these ones."
(As long as you're sure that the dot is really required - if not, it's simply: `"[^/?*:;{}\\]+"` | ```
$a = preg_match('=^[^/?*;:{}\\\\]+\.[^/?*;:{}\\\\]+$=', 'file.abc');
^ ... $ - begin and end of the string
[^ ... ] - matches NOT the listed chars.
``` | Regex for finding valid filename | [
"",
"php",
"regex",
"validation",
"preg-match",
""
] |
This is a crossbrowser window.onload script, I want to add a **message, when the page loads** (`<div id="message">Loading, please wait</div>`), and **it must disappear when page finished loading**. How can I do that? Please help.
```
function init() {
if (arguments.callee.done) return;
arguments.callee.done = true;
};
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", init, false);
}
/*@cc_on @*/
/*@if (@_win32)
document.write("<script id=\"__ie_onload\" defer=\"defer\" src=\"javascript:void(0)\"><\/script>");
var script = document.getElementById("__ie_onload");
script.onreadystatechange = function() {
if (this.readyState == "complete") {
init();
}
};
/*@end @*/
if (/WebKit/i.test(navigator.userAgent)) {
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
clearInterval(_timer);
init();
}
}, 10);
}
window.onload = init;
``` | The easiest way is to have a div in the DOM that you hide on the load event:
```
<html>
<body>
<div id="loading">The page is loading, please wait</div>
[...]
<script>
window.onload = function () {
document.getElementById('loading').style.display = "none";
}
</script>
</body>
</html>
```
To ensure that this always works, even when the user has JavaScript disabled:
```
<html>
<body>
<script>
document.write('<div id="loading">The page is loading, please wait</div>');
</script>
[...]
<script>
window.onload = function () {
document.getElementById('loading').style.display = "none";
}
</script>
</body>
</html>
``` | Just load the page with the loading DIV visible from the beginning. Hide it at the end of the init function...? | Message on loading | [
"",
"javascript",
""
] |
I'm developing a site that's pretty lightweight on the interface and mostly database driven (equal amounts read and write). It's written in PHP and I've found the easiest way to make each page is:
Page:
```
<?php include("header-nav.php"); ?>
<table>
<tr>
<th>Column 1</th>
<th>Column 2</th>
</tr>
<tr>
<td>Data Point 1</td>
<td>Data Point 2</td>
</tr>
<tr>
<td>Data Point 3</td>
<td>Data Point 4</td>
</tr>
</table>
<?php include("footer.php"); ?>
```
header-nav.php:
```
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Welcome</title>
<link rel="stylesheet" type="text/css" href="assets/style.css" />
</head>
<?php include("db_connect.php"); ?>
<body>
<div id="wrapper">
<h1>Welcome</h1>
<ul id="nav">
<li><a href="index.php">Home</a></li>
<li><a href="data.php">Data</a></li>
</ul>
```
footer.php:
```
</div>
</body>
<?php mysql_close($dbc); ?>
</html>
```
All of these pages by themselves are not valid and may produce errors. Working together to create a whole page, they look great.
My question is: **Would this be an efficient and easy to maintain solution?**
It seems that just adding a couple includes (one at the top and one at the bottom) makes sense. Especially because the site is so lightweight that I don't need a web framework. It just feels uncomfortable to create pages without starting with `<html><head>`...etc. | This is definitely an okay thing. I would highly recommend it. This way if you need to change the header or anything you can do so in once place easily. And the read time for hitting the file system for the include really isn't that big of a concern. So I would say that this is definitely acceptable. | "All of these pages by themselves are not valid" - I'm not sure what you mean by this. You mean a HTML Validator wouldn't pass them? Well of course not - they are fragments of pages. What matters is what the validator says when ran against the HTML the executed PHP generates.
This is one approach, and depending on the size of the problem you're tackling it's a valid one. | Any problem with using includes for everything but page-specific content? | [
"",
"php",
"html",
""
] |
I use JBoss AS. I have a long and heavy SQL that run inside the application server. I want to cache the results based on input parameters.
I have a few options here:
1. Use a caching manager and manually putting the results in the cache.
2. Use a caching manager with loader that will "load" the results into cache when there's no results in cache.
I don't care for now about replication of the cache to other servers in cluster.
My question is what option should I choose? What are the benefits and drawbacks of each option. (ease of deployment, configuration mess)
Is this can be implemented using JBoss Cache or ehcache or both.
---
**Update:**
I am using hibernate but the results are not entities, they are counters. I need to count all rows that belong to specific category and have specific status. I want that result to be cached.
Should I wrap the results inside an entity? Then, how can I make it work like (materialized?) view in oracle - to be update automatically or by trigger. | You're going to have to get the data out of the `ResultSet` and into *objects* in order to cache it so why don't you just start using Hibernate, which provides caching using a verity of options inclucing Ehcache, JBoss Cache and a simple Map.
<http://docs.jboss.org/hibernate/core/4.1/manual/en-US/html/ch20.html#performance-cache> | For starting a WeakHashMap can probably do what you need for now.
Create two classes, a Key holding the values needed to identify the key (remember to implement equals() and hashcode()), and a Value holding the retreived values as pulled out from the ResultSet. The easiest is probably a List of Maps (a map per row).
Java will automatically invalidate the entries when running out of memory in a WeakHashMap. | Caching in Java EE application | [
"",
"java",
"caching",
"jakarta-ee",
"jboss",
"ehcache",
""
] |
I need to mix Objective-C and C++. I would like to hide all the C++ stuff inside one class and keep all the others plain Objective-C. The problem is that I want to have some C++ classes as instance variables. This means they have to be mentioned in the header file, which gets included by other classes and C++ starts spreading to the whole application. The best solution I was able to come with so far looks like this:
```
#ifdef __cplusplus
#import "cppheader.h"
#endif
@interface Foo : NSObject
{
id regularObjectiveCProperty;
#ifdef __cplusplus
CPPClass cppStuff;
#endif
}
@end
```
This works. The implementation file has an `mm` extension, so that it gets compiled as Objective-C mixed with C++, the `#ifdef` unlocks the C++ stuff and there we go. When some other, purely Objective-C class imports the header, the C++ stuff is hidden and the class does not see anything special. This looks like a hack, is there a better solution? | This sounds like a classic use for an interface/@protocol. Define an objective-c protocol for the API and then provide an implementation of that protocol using your Objective-C++ class. This way clients need only know about the protocol and not the header of the implementation. So given the original implementation
```
@interface Foo : NSObject
{
id regularObjectiveCProperty;
CPPClass cppStuff;
}
@end
```
I would define a protocol
```
//Extending the NSObject protocol gives the NSObject
// protocol methods. If not all implementations are
// descended from NSObject, skip this.
@protocol IFoo <NSObject>
// Foo methods here
@end
```
and modify the original `Foo` declaration to
```
@interface Foo : NSObject <IFoo>
{
id regularObjectiveCProperty;
CPPClass cppStuff;
}
@end
```
Client code can then work with type `id<IFoo>` and does not need to be compiled as Objective-C++. Obviously you can pass an instance of `Foo` to these clients. | I also ran into this issue recently. In my case a protocol was overkill. I just needed to keep a pointer to a data access object that happened to be a C++ object.
What I did was declare the class with a `void *` instance variable and cast it when I use it in the instance methods.
This is a little bit hack-y, but conceptually, it's very similar to what the Objective-C `id` type is. | C++ classes as instance variables of an Objective-C class | [
"",
"c++",
"objective-c",
"objective-c++",
""
] |
I have created two forms in my Windows Application.
One Form acts as a Form and the other form acts as a MODAL DIALOG BOX.
The Form Dialog Box contains a button and One textBox.
When this button is clicked the MODAL DIALOGBOX should be displayed.
This dialog box also contains One Textbox and Two Buttons(Ok and Cancel).
Now when this dialog box is displayed the TextBox of the dialog box should contain the value entered in the textbox of Form1.
I have used the following coding to accomplish this task.
Form1 Coding:
```
public string UserName;
private void btnFn_Click(object sender, EventArgs e)
{
UserName = txtUserName.Text;
frmFnC objFnC = new frmFnC();
objFnC.ShowDialog();
objFnC.txtUserName.Text = UserName;
}
```
Code in MODAL DIALOGBOX OK button:
Please note that the Cancel button is enabled only when the OK button is clicked.
Coding:
```
private void btnOk_Click(object sender, EventArgs e)
{
btnCancel.Enabled=true;
}
private void btnCancel_Click(object sender,EventArgs e)
{
this.Close();
}
```
The problem I am facing is the value entered by the User in the USERNAME textbox is not displayed in the TEXTBOX in the MODAL DIALOG BOX. Instead it is displaying the textbox as empty.
What should I do to get the values entered by the user in the textbox to this modal dialog box?
Can anybody help me out in performing the desired task?
Thanks in advance!!! | **Change:**
```
objFnC.ShowDialog();
objFnC.txtUserName.Text = UserName
```
**To:**
```
objFnC.txtUserName.Text = UserName
objFnC.ShowDialog();
``` | The problem you've got is that you're showing the dialog before you set the username.
```
//this shows your dialog
objFnC.ShowDialog();
//this won't happen until the dialog is closed
objFnC.txtUserName.Text = UserName;
```
Because the dialog is modal it won't go to the next line until the dialog is closed. You want to swap those lines round and it'll be fine.
```
//do this first
objFnC.txtUserName.Text = UserName;
//then show your dialog
objFnC.ShowDialog();
```
I'd like to point out that exposing the textbox publically isn't a really good idea though. You don't want the consumer to have implementational knowledge of your dialog.
It would be better if you added a parameter to the form constructor and then set the textbox text from within that. Then you could do the following:
```
//get the username
string userName = txtUserName.Text;
//create a new form passing in the username
frmFnC objFnC = new frmFnC(userName);
//display the form
objFnC.ShowDialog();
```
That way, the consumer isn't relying on frmFnC having a textbox named txtUserName which means you're free to change the inner workings of how you display the username. For example, you could change it to a label and you wouldn't break the consumer's code! All the consumer needs to know is that they should pass a username into the constructor. | Modal Dialog Box | [
"",
"c#",
"dialog",
"modal-dialog",
"simplemodal",
""
] |
When initialize an entity framework context.
One is to initialize at class level, such as
```
public class EntityContactManagerRepository
: ContactManager.Models.IContactManagerRepository
{
private ContactManagerDBEntities _entities = new ContactManagerDBEntities();
// Contact methods
public Contact GetContact(int id)
{
return (from c in _entities.ContactSet.Include("Group")
where c.Id == id
select c).FirstOrDefault();
}
}
```
The other way is to initialize at the method level.
```
public class EntityContactManagerRepository
: ContactManager.Models.IContactManagerRepository
{
// Contact methods
public Contact GetContact(int id)
{
using (var entities = new ContactManagerDBEntities())
return (from c in entities.ContactSet.Include("Group")
where c.Id == id
select c).FirstOrDefault();
}
}
```
From an Ado.Net background, I prefer the later one-initialize in method, but the first one is from the example developed by [Stephen Walthe](http://stephenwalther.com/blog/Default.aspx). Or another question, does it matter at all? | It does matter, because the context controls the lifetime of change tracking data, and also impacts which object instances you can link together when you edit the objects, since objects on two different contexts cannot have a relationship with each other. It looks to me like the examples you're sharing come from an ASP.NET MVC application. In this case, I generally use one entity context per request, since requests are short-lived, and since it's common, when updating an object in a request, to have to fetch other objects and create relationships between them.
On the other hand, you don't want to keep an entity context around for a long time, because it will chew up memory as it tracks changes to more and more objects.
This may seem like an argument for the "one context per class" option, but it isn't, really. It's more like an argument for "one context per unit of work." | Generally speaking: it's context per request in ASP.NET and context per window in WinForms/WPF.
There's an article that explains quite well the reasoning behind the context per request paradigm:
[Entity Framework Object Context Scope](http://csharpquestions.com/entity-framework/scope-of-entity-framework-object-context-in-asp-net-websites) | Best way to initialize an entity framework context? | [
"",
"c#",
"entity-framework",
""
] |
I am attempting to reduce the amount of signals I have to use in my contextmenus. The menu consists of actions which switches the operation mode of the program, so the operation carried out by the slots is very simple. Quoting the documentation on QMenu::triggered,
> Normally, you connect each menu action's triggered() signal to its own custom slot, but sometimes you will want to connect several actions to a single slot, for example, when you have a group of closely related actions, such as "left justify", "center", "right justify".
However, I can't figure out how to accomplish this, and the documentation does not go into any further detail.
Suppose I have actions `actionOpMode1` and `actionOpMode2` in menu `actionMenu`, and a slot `setOpMode`. I want `setOpMode` to be called with a parameter which somehow relates to which of the actions was triggered. I tried various permutations on this theme:
```
QObject.connect(self.actionMenu, SIGNAL('triggered(QAction)'), self.setOpMode)
```
But I never even got it to call setOpMode, which suggests that actionMenu never "feels triggered", so to speak.
In [this SO question](https://stackoverflow.com/questions/940555/pyqt-sending-parameter-to-slot-when-connecting-to-a-signal), it's suggested that it can be done with lamdbas, but this:
```
QObject.connect(self.actionOpMode1, SIGNAL('triggered()'), lambda t: self.setOpMode(t))
```
gives `"<lambda> () takes exactly 1 argument (0 given)"`. I can't say I really understand how this is supposed to work, so I may have done something wrong when moving from clicked() to triggered().
How is it done? | Using QObject.Sender is one of the solution, although not the cleanest one.
Use [QSignalMapper](http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qsignalmapper.html) to associate cleanly a value with the object that emitted the signal. | I use this approach:
```
from functools import partial
def bind(self, action, *params):
self.connect(action, QtCore.SIGNAL('triggered()'),
partial(action, *params, self.onMenuAction))
def onMenuAction(self, *args):
pass
bind(self.actionOpMode1, 'action1')
bind(self.actionOpMode2, 'action2')
``` | PyQt: Consolidating signals to a single slot | [
"",
"python",
"qt",
""
] |
I tried to read a file in a view like this:
```
def foo(request):
f = open('foo.txt', 'r')
data = f.read()
return HttpResponse(data)
```
I tried to place the foo.txt in almost every folder in the project but it still returns
> [Errno 2] No such file or directory:
> 'foo.txt'
So does anybody knows how to open a file in app engine patch? Where should i place the files i wish to open? many thanks.
I'm using app-engine-patch 1.1beta1 | In App Engine, patch or otherwise, you should be able to open (read-only) any file that gets uploaded with your app's sources. Is 'foo.txt' in the same directory as the py file? Does it get uploaded (what does your app.yaml say?)? | Put './' in front of your file path:
```
f = open('./foo.txt')
```
If you don't, it will still work in App Engine Launcher 1.3.4, which could be confusing, but once you upload it, you'll get an error.
Also it seems that you shouldn't mention the file (or its dir) you want to access in app.yaml. I'm including css, js and html in my app this way. | How to open a file on app engine patch? | [
"",
"python",
"django",
"google-app-engine",
""
] |
Can anyone help with this...
```
vector<unsigned int> *vVec = new vector<unsigned int>;
vVec .reserve(frankReservedSpace);
start = std::clock();
for(int f=0; f<sizeOfvec; f++)
{ //Populate the newly created vector on the heap
vVec .push_back(pArray[f]);
}
```
I'm getting:
error C2228: left of '.reserve' must have class/struct/union
I'm creating a vector using the new operator so that it outlives the function where it is created. This therefore gives me back a pointer to that vector on the heap rather than an actual vector object itself. therefore it won't let me carry out any .reserve() of push\_backs.
I can't see a way around it, can anyone help? | vVec is a pointer to a vector. Therefore you should be using the indirection (->) operator rather than the dot (.)
```
vector<unsigned int> *vVec = new vector<unsigned int>;
vVec->reserve(frankReservedSpace);
start = std::clock();
for(int f=0; f<sizeOfvec; f++)
{ //Populate the newly created vector on the heap
vVec->push_back(pArray[f]);
}
``` | Use "->" instead of "." `vVec` is of pointer type, so you need to use `operator ->` to access members of the object it points to. | manipulation of Vectors created with new | [
"",
"c++",
"vector",
"heap-memory",
"push-back",
""
] |
In order to satisfy customer requirements, we will need to let users exchange information among each other. The '**messaging system**' does not have sophisticated back-end requirements and could be easily implemented with a few tables to store messages and message types.
The problem is that I believe that the requirements on the front-end are very high and usability is very important. In addition I expect this communication's part to become an important part of the system in the long run.
Is there anything that can be directly integrated into a Java web application and adapted to the application's design? What we need is the following interface
From service layer:
* send message to user (header, subject)
* reply to a message
* notification on new message in user inbox (if possible: on current page)
* interface to existing user management
Preferably, the component should already have a front-end with the following functionality:
* message management (select, remove, reply, delete/restore, ...)
* folders: inbox, sent, trash
* tagging: message categories
* show last *x* messages in a panel/div
* styling to look like the application
If there is something reasonably stable, I would prefer using a component before implementing something like this into the application. The application runs on Wicket, but we are not tied to this framework for the messaging component.
Thank you,
Kariem
---
In portal servers, you have the flexibility to add portlets that could do something similar to the component I am looking for; e.g. [Liferay](http://www.liferay.com/) provides [mail](http://www.liferay.com/web/guest/community/wiki/-/wiki/Main/Mail%20Portlet) and [message boards](http://www.liferay.com/web/guest/community/wiki/-/wiki/Main/Message%20Boards%20Portlet) portlets.
As *akf* points out in a comment [Jabber](http://www.jabber.org/) provides a solid basis for messaging. We are looking for something that can be integrated into a web application. If we have to build a lot of UI around Jabber, we cannot really consider it a good fit for our requirements. | Ok, it may be a bit surprising but what about giving the [Google Wave](https://wave.google.com) a try ?
If I review your criteria :
> Is there anything that can be directly
> integrated into a Java web application
> and adapted to the application's
> design [...]
It can be as you will discover on this mini-tutorial : <http://blog.zenika.com/index.php?post/2010/01/27/Google-Wave-Embedded-API-the-missing-tutorial> (how interesting isn't it ?)
> From service layer:
>
> * send message to user (header, subject)
> * reply to a message
> * notification on new message in user inbox (if possible: on current page)
> * interface to existing user management
Everything but the last point is offered by the Google Wave instance. The last point may be a bit harder to solve as you will require that all of your user have a googlewave account. Managing those accounts [may become available through Google Apps](http://googleenterprise.blogspot.com/2009/09/waving-hello-to-google-apps.html), but atm it's not feasible. If it's absolutely mandatory you could plan to have your own instance since it is an [open protocol](http://www.waveprotocol.org/) but your goal was to have something already done for you, right ?
> Preferably, the component should
> already have a front-end with the
> following functionality:
>
> * message management (select, remove, reply, delete/restore, ...)
> * folders: inbox, sent, trash
> * tagging: message categories
> * show last x messages in a panel/div
> * styling to look like the application
Great, all of this is ok with the Wave.
> If there is something reasonably
> stable, I would prefer using a
> component before implementing
> something like this into the
> application. The application runs on
> Wicket, but we are not tied to this
> framework for the messaging component.
Ok Wicket is so trendy, you should love this solution :-)
I acknowledge that is a bit '[avant-gardiste](http://en.wikipedia.org/wiki/Avant-garde)', I have never done such a thing myself but thought it could have broaden your vision as regard to your problem... | If you are looking for opensource java email clients:
<http://java-source.net/open-source/mail-clients>
You may also want to have a look at **Google Wave** . With this you will have next generation communication and collboration tool. Please see some awesome videos about google wave on [www.youtube.com](http://www.youtube.com)
<http://code.google.com/apis/wave/>
<http://code.google.com/p/wave-protocol/wiki/Installation>
.
**Updated solution... Web based email clients**
<http://java-source.net/open-source/web-mail>
<http://code.google.com/p/cubusmail/>
<http://www.zimbra.com/downloads/os-downloads.html> | Embeddable messaging component for Java web application | [
"",
"java",
"email",
"messaging",
"wicket",
""
] |
I am using ElementTree to parse a XML file. In some fields, there will be HTML data. For example, consider a declaration as follows:
```
<Course>
<Description>Line 1<br />Line 2</Description>
</Course>
```
Now, supposing \_course is an Element variable which hold this Couse element. I want to access this course's description, so I do:
```
desc = _course.find("Description").text;
```
But then desc only contains "Line 1". I read something about the .tail attribute, so I tried also:
```
desc = _course.find("Description").tail;
```
And I get the same output. What should I do to make desc be "Line 1
Line 2" (or literally anything between and )? In other words, I'm looking for something similar to the .innerText property in C# (and many other languages I guess). | Do you have any control over the creation of the xml file? The contents of xml tags which contain xml tags (or similar), or markup chars ('`<`', etc) should be encoded to avoid this problem. You can do this with either:
* a [CDATA](http://en.wikipedia.org/wiki/Cdata) section
* Base64 or some other encoding (which doesn't include xml reserved characters)
* Entity encoding ('`<`' `==` '`<`')
If you can't make these changes, and ElementTree can't ignore tags not included in the xml schema, then you will have to pre-process the file. Of course, you're out of luck if the schema overlaps html. | You are trying to read the tail attribute from the wrong element. Try
```
desc = _course.find("br").tail;
```
The tail attribute is used to store trailing text nodes when reading mixed-content XML files; text that follows directly after an element are stored in the tail attribute for that element:
```
<tag><elem>this goes into elem's
text attribute</elem>this goes into
elem's tail attribute</tag>
```
Simple code snippet to print text and tail attributes from all elements in xml/xhtml.
```
import xml.etree.ElementTree as ET
def processElem(elem):
if elem.text is not None:
print elem.text
for child in elem:
processElem(child)
if child.tail is not None:
print child.tail
xml = '''<Course>
<Description>Line 1<br />Line 2 <span>child text </span>child tail</Description>
</Course>'''
root = ET.fromstring(xml)
processElem(root)
```
Output:
```
Line 1
Line 2
child text
child tail
```
See <http://code.activestate.com/recipes/498286-elementtree-text-helper/> for a better solution. It can be modified to suit.
P.S. I changed my name from user839338 as quoted in the next post | HTML inside node using ElementTree | [
"",
"python",
"html",
"xml",
"elementtree",
""
] |
I need to pass audio data into a 3rd party system as a "16bit integer array" (from the limited documentation I have).
This is what I've tried so far (the system reads it in from the resulting bytes.dat file).
```
AudioInputStream inputStream = AudioSystem.getAudioInputStream(new File("c:\\all.wav"));
int numBytes = inputStream.available();
byte[] buffer = new byte[numBytes];
inputStream.read(buffer, 0, numBytes);
BufferedWriter fileOut = new BufferedWriter(new FileWriter(new File("c:\\temp\\bytes.dat")));
ByteBuffer bb = ByteBuffer.wrap(buffer);
while (bb.remaining() > 1) {
short current = bb.getShort();
fileOut.write(String.valueOf(current));
fileOut.newLine();
}
```
This doesn't seem to work - the 3rd party system doesn't recognise it and I also can't import the file into Audacity as raw audio.
Is there anything obvious I'm doing wrong, or is there a better way to do it?
Extra info: the wave file is 16bit, 44100Hz, mono. | **Edit 2:**
I rarely use AudioInputStream but the way you write out the raw data seems to be rather complicated. A file is just a bunch of subsequent bytes so you could write your audio byte array with one single FileOutputStream.write() call. The system might use big endian format whereas the WAV file is stored in little endian (?). Then your audio might play but extremely silently for example.
**Edit 3**
Removed the code sample.
Is there a reason you are writing the audio bytes as strings into the file with newlines?
I would think the system expects the audio data in binary format, not in string format. | I've just managed to sort this out.
I had to add this line after creating the ByteBuffer.
```
bb.order(ByteOrder.LITTLE_ENDIAN);
``` | Java - converting byte array of audio into integer array | [
"",
"java",
""
] |
I have a table that's created like this:
```
CREATE TABLE bin_test
(id INTEGER PRIMARY KEY, b BLOB)
```
Using Python and cx\_Oracle, if I do this:
```
value = "\xff\x00\xff\x00" #The string represented in hex by ff00ff00
self.connection.execute("INSERT INTO bin_test (b) VALUES (rawtohex(?))",
(value,))
self.connection.execute("SELECT b FROM bin_test")
```
I eventually end up with a hex value of `a000a000`, which isn't correct! However if I do this:
```
import binascii
value = "\xff\x00\xff\x00"
self.connection.execute("INSERT INTO bin_test (b) VALUES (?)",
(binascii.hexlify(value,)))
self.connection.execute("SELECT b FROM bin_test")
```
I get the correct result. I have a type conversion system here, but it's a bit difficult to describe it here. Thus, can someone point me in the right direction as to whether I'm doing something wrong at the SQL level or whether something weird is happening with my conversions? | rawtohex() is for converting Oracles RAW datatypes to hex strings. It's possible it gets confused by you passing it a string, even if the string contains binary data. In this case, since Oracle expects a string of hex characters, give it a string of hex characters. | `RAWTOHEX` in `Oracle` is bit order insensitive, while on your machine it's of course sensitive.
Also note that an argument to `RAWTOHEX()` can be implicitly converted to `VARCHAR2` by your library (i. e. transmitted as `SQLT_STR`), which makes it also encoding and collation sensitive. | What is the difference between converting to hex on the client end and using rawtohex? | [
"",
"python",
"oracle",
"oracle10g",
"blob",
"cx-oracle",
""
] |
I recently installed PHP 5 on IIS, however, I am unable to find a PHP syntax highlighting plug-in or extension for VWD. Where can I find a plug-in? I thought there was an official one. | I've tried a lot of text editors, some free, some commercial. So far Visual Studio is the only one that has the right combination of features to be most useful to me. So, coding PHP in VS is important to me.
You can trick Visual Studio (and hopefully also Visual Web Developer) into thinking `.php` files are C++ with a registry hack. The syntax highlighting is close enough to be useful.
This blog post explains how to do it for all versions of VS: <http://blog.cumps.be/visual-studio-2008-and-php-coloring/> | Consider PHP IDE for Visual Studio.
<http://www.jcxsoftware.com/vs.php>
I have used this and it adds a lot of nice PHP specific features to Visual Studio.
From their site...
Editor and File Management
•PHP4 and PHP5 Support
•Syntax Coloring for PHP, Smarty, HTML, JavaScript, CSS, XML and XSLT
•File templates for PHP, Smarty, HTML, JavaScript, CSS, XML and XSLT
•Intellisense for PHP, Smarty, HTML, JavaScript, CSS, XML and XSLT
Debugging
•XDebug and DBG support
•Debug PHP, JavaScript and .Net in one single session
•Built-in Apache web server for ease of debugging. Preconfigured with Php4, Php5, XDebug and DBG. | PHP syntax highlighting in Visual Web Developer? | [
"",
"php",
"syntax-highlighting",
"visual-studio-express",
"visual-web-developer",
"vwdexpress",
""
] |
How can I allow selected rows in a DataGridView (DGV) to be moved up or down. I have done this before with a ListView. Unfortunetly, for me, replacing the DGV is not an option (*curses*). By the way, the DGV datasource is a Generic Collection.
The DGV has two buttons on the side, yes, UP & Down. Can anyone help point me in the right direction. I do have the code that I used for the ListView if it'll help (it did not help me). | If you programatically change the ordering of the items in your collection, the DGV should reflect that automatically.
Sloppy, half-working example:
```
List<MyObj> foo = DGV.DataSource;
int idx = DGV.SelectedRows[0].Index;
int value = foo[idx];
foo.Remove(value);
foo.InsertAt(idx+1, value)
```
Some of that logic may be wrong, and this may not be the most efficient approach either. Also, it doesn't take into account multiple row selections.
Hmm, one last thing, if you're using a standard List or Collection this isn't going to go as smoothly. List and Collection on't emit events that the DGV finds useful for databinding. You could 'burp' the databinding every time you change the collection, but a better solution would be for you to use a System.ComponentModel.BindingList. When you change the ordering of the BindingList the DGV should reflect the change automatically. | Just to expand on Yoopergeek's answer, here's what I have.
I was not using a DataSource (data is being dropped to registry on form close, and reload on form load)
This sample will keep rows from being moved off the grid and lost, and reselect the cell the person was in as well.
To make things simpler for copy / paste, I modified so you need only change "gridTasks" to your DataGridView's name, rather than renaming it throughout the code.
**This solution works only for single cell/row selected.**
```
private void btnUp_Click(object sender, EventArgs e)
{
DataGridView dgv = gridTasks;
try
{
int totalRows = dgv.Rows.Count;
// get index of the row for the selected cell
int rowIndex = dgv.SelectedCells[ 0 ].OwningRow.Index;
if ( rowIndex == 0 )
return;
// get index of the column for the selected cell
int colIndex = dgv.SelectedCells[ 0 ].OwningColumn.Index;
DataGridViewRow selectedRow = dgv.Rows[ rowIndex ];
dgv.Rows.Remove( selectedRow );
dgv.Rows.Insert( rowIndex - 1, selectedRow );
dgv.ClearSelection();
dgv.Rows[ rowIndex - 1 ].Cells[ colIndex ].Selected = true;
}
catch { }
}
private void btnDown_Click(object sender, EventArgs e)
{
DataGridView dgv = gridTasks;
try
{
int totalRows = dgv.Rows.Count;
// get index of the row for the selected cell
int rowIndex = dgv.SelectedCells[ 0 ].OwningRow.Index;
if ( rowIndex == totalRows - 1 )
return;
// get index of the column for the selected cell
int colIndex = dgv.SelectedCells[ 0 ].OwningColumn.Index;
DataGridViewRow selectedRow = dgv.Rows[ rowIndex ];
dgv.Rows.Remove( selectedRow );
dgv.Rows.Insert( rowIndex + 1, selectedRow );
dgv.ClearSelection();
dgv.Rows[ rowIndex + 1 ].Cells[ colIndex ].Selected = true;
}
catch { }
}
``` | DataGridView Selected Row Move UP and DOWN | [
"",
"c#",
".net",
"winforms",
"collections",
"datagridview",
""
] |
Here is the piece of code that I have used for Java 5.0
```
TreeSet<Integer> treeSetObj = new TreeSet<Integer>( Collections.reverseOrder() ) ;
```
`Collections.reverseOrder()` is used to obtain a comparator in order to reverse the way the elements are stored and iterated.
Is there a more optimized way of doing it? | Why do you think this approach won't be optimized? The reverse order `Comparator` is simply going to be flipping the sign of the output from the actual `Comparator` (or output from `compareTo` on the `Comparable` objects being inserted) and I would therefore imagine it is very fast.
An alternative suggestion: Rather than change the order you store the elements in you could iterate over them in descending order using the `descendingIterator()` method. | # `TreeSet::descendingSet`
In Java 6 and later, there is a method on [`TreeSet`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/TreeSet.html) called [`descendingSet()`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/TreeSet.html#descendingSet()) producing a [`NavigableSet`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/NavigableSet.html) interface object.
> public NavigableSet descendingSet()
>
> The descending set is backed by this
> set, so changes to the set are
> reflected in the descending set, and
> vice-versa. If either set is modified
> while an iteration over either set is
> in progress (except through the
> iterator's own remove operation), the
> results of the iteration are
> undefined.
>
> ```
> The returned set has an ordering equivalent to
> ```
>
> Collections.reverseOrder(comparator()).
> The expression
> s.descendingSet().descendingSet()
> returns a view of s essentially
> equivalent to s.
>
> ```
> Specified by:
> descendingSet in interface NavigableSet<E>
>
> Returns:
> a reverse order view of this set
> Since:
> 1.6
> ``` | Treeset to order elements in descending order | [
"",
"java",
"collections",
"treeset",
""
] |
I'm looking for an XML parser that instead of parsing from an InputStream or InputSource will instead allow blocks of text to be pushed into the parser. E.g. I would like to have something like the following:
```
public class DataReceiver {
private SAXParser parser = //...
private DefaultHandler handler = //...
/**
* Called each time some data is received.
*/
public void onDataReceived(byte[] data) {
parser.push(data, handler);
}
}
```
The reason is that I would like something that will play nice with the NIO networking libraries rather than having to revert back to a thread per connection model required to support a blocking InputStream. | This is a (April 2009) post from the Xerces J-Users mailing list, where the original poster is having the exact same issue. One potentially very good response by "Jeff" is given, but there is no follow up to the original poster's response:
<http://www.nabble.com/parsing-an-xml-document-chunk-by-chunk-td22945319.html>
It's potentially new enough to bump on the list, or at very least help with the search.
**Edit**
Found another useful link, mentioning a library called Woodstox and describing the state of Stream vs. NIO based parsers and some possible approaches to emulating a stream:
<http://markmail.org/message/ogqqcj7dt3lwkbov> | Surprisingly no one mentioned one Java XML parser that does implement non-blocking ("async") parsing: [Aalto](http://www.cowtowncoder.com/hatchery/aalto/index.html). Part of the reason may be lack of documentation (and its low level of activity). Aalto implements basic Stax API, but also minor extensions to allow pushing input (this part has not been finalized; functionality exists but API is not finalized).
For more information you could check out related [discussion group](http://tech.groups.yahoo.com/group/aalto-xml-interest/). | Is there a Push-based/Non-blocking XML Parser for Java? | [
"",
"java",
"xml",
"nonblocking",
""
] |
I am using reflection class to invoke some methods which are on the some other dll.
And one of the methods' parameters are type of delegate.
And I want to invoke this methods by using reflection.
So I need to pass function parameters as object array, but I could not find anything about
how to convert delegate to object.
Thanks in advance | A delegate is an object. Just create the expected delegate as you would normally, and pass it in the parameters array. Here is a rather contrived example:
```
class Mathematician {
public delegate int MathMethod(int a, int b);
public int DoMaths(int a, int b, MathMethod mathMethod) {
return mathMethod(a, b);
}
}
[Test]
public void Test() {
var math = new Mathematician();
Mathematician.MathMethod addition = (a, b) => a + b;
var method = typeof(Mathematician).GetMethod("DoMaths");
var result = method.Invoke(math, new object[] { 1, 2, addition });
Assert.AreEqual(3, result);
}
``` | Instances of delegates are objects, so this code works (C#3 style) :
```
Predicate<int> p = (i)=> i >= 42;
Object[] arrayOfObject = new object[] { p };
```
Hope it helps !
Cédric | How to convert delegate to object in C#? | [
"",
"c#",
"object",
"delegates",
""
] |
I'm working on a kind of "store and forward" application for WCF services. I want to save the message in a database as a raw XML blob, as XElement. I'm having a bit of trouble converting the datacontract into the XElement type I need for the database call. Any ideas? | this returns it as a string, which you can put into the db into an xml column. Here is a good generic method you can use to serialize datacontracts.
```
public static string Serialize<T>(T obj)
{
StringBuilder sb = new StringBuilder();
DataContractSerializer ser = new DataContractSerializer(typeof(T));
ser.WriteObject(XmlWriter.Create(sb), obj);
return sb.ToString();
}
```
btw, are you using linq to sql? The reason i ask is because of the XElement part of your question. if thats the case, you can modify this in the .dbml designer to use a string as the CLR type, and not the default XElement. | The most voted on answer (Jason W. posted) did not work for me. I dont know why that answer got the most votes. But after searching around I found this
<http://billrob.com/archive/2010/02/09/datacontractserializer-converting-objects-to-xml-string.aspx>
Which worked for my project. I just had a few classes and put the datacontract and datamemeber attributes on classes and properties and then wanted to get an XML string which I could write to the database.
Code from the link above incase it goes 404:
Serializes:
```
var serializer = new DataContractSerializer(tempData.GetType());
using (var backing = new System.IO.StringWriter())
using (var writer = new System.Xml.XmlTextWriter(backing))
{
serializer.WriteObject(writer, tempData);
data.XmlData = backing.ToString();
}
```
Deserializes:
```
var serializer = new DataContractSerializer(typeof(T));
using (var backing = new System.IO.StringReader(data.XmlData))
using (var reader = new System.Xml.XmlTextReader(backing))
{
return serializer.ReadObject(reader) as T;
}
``` | Persist a DataContract as XML in a database | [
"",
"c#",
"xml",
"wcf",
"datacontract",
""
] |
Is there a simple way to work with C++ objects directly from C?
I want to expose some classes from C++ to C or to FFI(foreign function interface).
Sure, I can write a stuff like that:
```
class Foo{
....
};
void *make_foo(...){
Foo *ptr = new Foo(..)
return static_cast<void *>(ptr);
}
..
int *foo_method1(void *fooptr, ...){
Foo *ptr = static_cast<Foo*>(fooptr);
}
```
But there is a simpler method? | That, in general, is the simplest method.
Remember, too, that you'll need to use `extern "C"` on all of your C "wrapper" methods, as well. | You almost there. Prefix your standalone functions with `extern "C"` to turn off the C++ compiler's [name mangling](http://en.wikipedia.org/wiki/Name_mangling).
For example:
```
extern "C" void *make_foo(...){
Foo *ptr = new Foo(..)
return static_cast<void *>(ptr);
}
``` | C++ code and objects from C? | [
"",
"c++",
"c",
"lisp",
""
] |
How can I make an average between dates in MySQL?
I am more interested in the time values, hours and minutes.
On a table with:
```
| date_one | datetime |
| date_two | datetime |
```
Doing a query like:
```
SELECT AVG(date_one-date_two) FROM some_table WHERE some-restriction-applies;
```
---
### Edit:
The `AVG(date1-date2)` works but I have no clue what data it is returning. | This seems a bit hackish, but will work for dates beteen ~ 1970 and 2030 (on 32 bit arch). You are essentially converting the datetime values to integer, averaging them, and converting the average back to a datetime value.
```
SELECT
from_unixtime(
avg(
unix_timestamp(date_one)-unix_timestamp(date_two)
)
)
FROM
some_table
WHERE
some-restriction-applies
```
There is likely a better solution out there, but this will get you by in a pinch. | ```
select avg(datediff(date1,date2))
select avg(timediff(datetime,datetime))
``` | How can I make an average of dates in MySQL? | [
"",
"sql",
"mysql",
""
] |
I have an application that I restart at 2 am every morning using
`Application.Restart();`
the problem is that a inspection a couple of weeks later shows that there are 6 or so instances running.
I tried to limit the number of instances by using
```
bool IsOwned;
Mutex m = new Mutex(true, Name, out IsOwned);
if (!IsOwned)
Environment.Exit(0);
```
But this didn't work as for some reason the recently stopped instance was still visible...or at least that's my interpretation and as a result the application didn't reatart.
Where have I gone wrong? | Make sure that you hook on application exit event a method that releases the mutex and closes it. | By any chance, are you using multiple threads? If you don't shut down your background threads, they will keep your process running, even through a call to Application.Restart.
I have pasted in some code below that demonstrates this behavior. To see it, compile a test project with the code below and run it. (you will need to put 1 button on the form and assign the click handler that I have defined in the code below).
Start Task Manager, go to the Process tab, and make sure to add the PID (process id) column to the view.
Each time you click the button, the app will restart, but you should see the old process still hung in memory (due to a background thread that was not closed down).
```
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// start a background thread that will never be exited.
System.Threading.Thread thread = new System.Threading.Thread(delegate() { while (true) System.Threading.Thread.Sleep(1000); });
thread.Start();
}
private void button1_Click(object sender, EventArgs e)
{
Application.Restart();
}
}
```
Assuming that this is your problem, the best way to correct it is to put some kind of a check into your background threads (even a bool flag will do). Have them check for exited periodically and and exit gracefully when your app shuts down.
Note: you could set the thread's background property to true, and it will be exited automatically, but if you do that, you don't have control over which instruction the thread is executing when it exits, so you can't perform any type of cleanup. It's best to code your own check. | how do I restart a single instance winforms application | [
"",
"c#",
""
] |
I got a string array and values are as follows
```
sNames[0] = "Root | [<root>] | [ID = 1]";
sNames[1] = "Planning | [Root] | [ID = 2]";
```
From this I would like to just extract ID value .. 1,2..
for now am do this as :
```
foreach (var s in sNames)
{
int id = Convert.ToInt32(s.Split('|')[2].Split('=')[1].Substring(1,1));
...
}
```
Is there some other good way to do it ?
Thanks | You can use a regex to find the ID (the Match() part may not be 100% correct -- exercise left to the reader).
```
var regex = new Regex(@"\[ID = (?<id>[0-9]+)\]");
var ids = sNames.Select(s => Convert.ToInt32(regex.Match(s).Groups["id"].Value));
``` | You can use regex...
```
// using System.Text.RegularExpressions
Regex rx = new Regex(@"\[ID\s*=\s*(\d+)\]", RegexOptions.IgnoreCase);
foreach (var s in sNames)
{
Match m = rx.Match(s);
if (!m.Success) continue; // Couldn't find ID.
int id = Convert.ToInt32(m.Groups[1].ToString());
// ...
}
```
But [now you have two problems](http://regex.info/blog/2006-09-15/247). ;-) | How do I extract a value from inside of a formatted string? | [
"",
"c#",
"parsing",
"input",
""
] |
Like many people here, I started my programming experience with the good ol' green screen BASIC that you get when you booted an Apple II without a disk. I taught myself C++ in my teens, and even took a class on it in college, but as soon as I discovered .NET and C#, I dropped C++ like a bad habit. Now, (many) years later, I'm interested in getting back into C++ development - thank the iPhone for that - and I have to admit, I feel a little daunted. Having to deal with pointers, ATL, macros, etc. seems a bit overwhelming at times when you've been in managed .NET land for a long time.
What are some good resources or weekend type projects I could do to ease me back into C++? I'm not interested in debating the relative merits between platforms, stacks, but I would be interested in hearing about *objective* comparisons between different development platforms, although keep in mind I'm a Windows guy.
If anyone wants to change the tags around, feel free - I wasn't quite sure how to tag this.
TIA! | Try [Euler Project](http://projecteuler.net/)
> Project Euler is a series of
> challenging mathematical/computer
> programming problems that will require
> more than just mathematical insights
> to solve. Although mathematics will
> help you arrive at elegant and
> efficient methods, the use of a
> computer and programming skills will
> be required to solve most problems. | I had this problem a while back, I chose to find a cool open source project.
I chose [Chromium](http://dev.chromium.org/developers).
It was really interesting, and all C++
They have a vast number of small bugs which can be fun to fix, I ended up fixing about 4 in a few evenings/weekends. Check it out (pun intended) | What is a good project / way for an out of practice C++ developer to get back into it? | [
"",
"c++",
"iphone",
""
] |
In C++, if you define this function in header.hpp
```
void incAndShow()
{
static int myStaticVar = 0;
std::cout << ++myStaticVar << " " << std::endl;
}
```
and you include header.hpp in at least two .cpp files. Then you will have `multiple definition of incAndShow()`. Which is expected. However, if you add a template to the function
```
template <class T>
void incAndShow()
{
static int myStaticVar = 0;
std::cout << ++myStaticVar << " " << std::endl;
}
```
then you won't have any `multiple definition of` error. Likewise, two different .cpp calling the function with the same template (e.g. `incAndShow<int>()`), will share `myStaticVar`. Is this normal? I'm asking this question, because I do rely on this "feature" (sharing the static variable) and I want to be sure that it is not only my implementation that is doing this. | You can rely on this. The ODR (One Definition Rule) says at `3.2/5` in the Standard, where `D` stands for the non-static function template (cursive font by me)
> If D is a template, and is defined in more than one translation unit, then the last four requirements from the list above shall apply to names from the template’s enclosing scope used in the template definition (14.6.3), and also to dependent names at the point of instantiation (14.6.2). *If the definitions of D satisfy all these requirements, then the program shall behave as if there were a single definition of D.* If the definitions of D do not satisfy these requirements, then the behavior is undefined.
Of the last four requirements, the two most important are roughly
* each definition of D shall consist of the same sequence of tokens
* names in each definition shall refer to the same things ("entities")
**Edit**
I figure that this alone is not sufficient to guarantee that your static variables in the different instantiations are all the same. The above only guarantees that the multiple definitions of the template is valid. It doesn't say something about the specializations generated from it.
This is where *linkage* kicks in. If the name of a function template specialization (which is a function) has external linkage (`3.5/4`), then a name that refers to such a specialization refers to the same function. For a template that was declared static, functions instantiated from it have internal linkage, because of
> Entities generated from a template with internal linkage are distinct from all entities generated in other translation units. `-- 14/4`
>
> A name having namespace scope (3.3.6) has internal linkage if it is the name of [...] an object, reference, function or function template that is explicitly declared static `-- 3.5/3`
If the function template wasn't declared with static, then it has extern linkage (that, by the way, is also the reason that we have to follow the ODR at all. Otherwise, `D` would not be multiply defined at all!). This can be derived from `14/4` (together with `3.5/3`)
> A non-member function template can have internal linkage; any other template name shall have external linkage. `-- 14/4`.
Finally, we come to the conclusion that a function template specialization generated from a function template with external linkage has itself external linkage by `3.5/4`:
> A name having namespace scope has external linkage if it is the name of [...] a function, unless it has internal linkage `-- 3.5/4`
And when it has internal linkage was explained by `3.5/3` for functions provided by explicit specializations, and `14/4` for generated specializations (template instantiations). Since your template name has external linkage, all your specializations have external linkage: If you use their name (`incAndShow<T>`) from different translation units, they will refer to the same functions, which means your static objects will be the same in each occasion. | Just so i understand your question. You are asking if it is normal for each version of the templated function to have its own instance of myStaticVar. (for example: `incAndShow<int>` vs. `intAndShow<float>` The answer is yes.
Your other question is, if two files include the header containing the template function, will they still share the static variable for a given T. I would say yes. | Static variable inside template function | [
"",
"c++",
"templates",
"static",
""
] |
As as rule of thumb I generally put classes in a file of their own. Visual studio seems to encourage this but what is appropriate with regards to interfaces?
e.g.
I have Class Foo that implements interface Bar
```
public interface IBar
{
}
public class Foo : IBar
{
}
```
it seems natural to group these within the same file until another class implements the interface but to dedicate a file to 2 lines code seems excessive but correct.
What is appropriate? | I would split them into 2 files. I often found classes starting to go unmanageable when they are not in their own files.
Imagine trying to find class Foo in a file named IBar.cs or vice versa. | Since the purpose of an interface is to define a "contract" for (potentially) multiple implementing classes, I'd say putting the interface definition in its own file makes more sense. i.e. What happens if you also want to make Baz implement Foo? | do interfaces belong in files of their own | [
"",
"c#",
"coding-style",
"interface",
""
] |
The problem is during inserting data from staging table during import routine.
The system is a legacy one I inherited, and short term while I develop something more suitable I want to patch things to avoid the data transfer failing.
Unfortunately the facility exists via another application to create an entry into table, called CommReceipt. The key is called CR\_Key . if this happens then when the auto routine runs to insert, say 1000 rows we need to import from another system (not my system) with CR\_Key values already defined, it fails.
The way I see it I have several options, but all suggestions will be appreciated moving forward for the best solution to this issue (both long and short term fixes) .
It is part of the plan to eliminate functionality in the rogue application (but this is a legacy system, written in legacy unfamilar language and might take a bit of effort)
How do I deal with the primary key violation. Can I continue, reporting the violation to deal with after running data insert.
UPDATE: the Primary key CR\_Key also happens to be an identity , is there a way to delete rows which should not be there and insert rows using the same ID. I presume....I turn the identity off, then specify unique values in the 'missing rows', is that plausible?
I don't need to auto increment id now, theinsert routine has ID's
Thanks | You could use an *instead of insert* trigger. Inside the trigger, do an Insert into the table, where not exists CommReceipt.CR\_Key = inserted.CR\_Key.
```
Create trigger T_CommReceiptInsteadOfInsert on CommReceipt
Instead of Insert
As
Begin
--Insert duplicate records into another table
Insert Into CommReceipt_Duplicates(CR_Key, ...)
Select CR_Key, ...
From inserted i
Where exists (select * from CommReceipt c Where c.CR_Key = i.CR_Key)
--Insert non duplicate records
Insert Into CommReceipt(CR_Key, ...)
Select CR_Key, ...
From inserted i
Where not exists (select * from CommReceipt c Where c.CR_Key = i.CR_Key)
End
``` | maybe you could use a trigger, to verify that the insert can be done (the PK don't exist). If the PK already exist, you can store some information in other table as a log, and cancel the insert making a rollback and launching an exception. | Continue after primary key violation error | [
"",
"sql",
"sql-server",
"database",
"t-sql",
"stored-procedures",
""
] |
```
public void MyTest()
{
bool eventFinished = false;
myEventRaiser.OnEvent += delegate { doStuff(); eventFinished = true; };
myEventRaiser.RaiseEventInSeperateThread()
while(!eventFinished) Thread.Sleep(1);
Assert.That(stuff);
}
```
Why can't eventFinished be volatile and does it matter?
It would seem to me that in this case the compiler or runtime could become to smart for its own good and 'know' in the while loop that eventFinished can only be false. Especially when you consider the way a lifted variable gets generated as a member of a class and the delegate as a method of that same class and thereby depriving optimizations of the fact that eventFinished was once a local variable. | There exists a threading primitive, [`ManualResetEvent`](http://msdn.microsoft.com/en-us/library/system.threading.manualresetevent.aspx) to do precisely this task - you don't want to be using a boolean flag.
Something like this should do the job:
```
public void MyTest()
{
var doneEvent = new ManualResetEvent(false);
myEventRaiser.OnEvent += delegate { doStuff(); doneEvent.Set(); };
myEventRaiser.RaiseEventInSeparateThread();
doneEvent.WaitOne();
Assert.That(stuff);
}
```
Regarding the lack of support for the `volatile` keyword on local variables, I don't believe there is any reason why this might not in theory be *possible* in C#. Most likely, it is not supported simply because there was no use for such a feature prior to C# 2.0. Now, with the existence of anonymous methods and lambda functions, such support could potentially become useful. Someone please clarify matters if I'm missing something here. | In **most** scenarios, local variables are specific to a thread, so the issues associated with `volatile` are completely unnecessary.
This changes when, like in your example, it is a "captured" variable - when it is silently implemented as a field on a compiler-generated class. So in theory it *could* be volatile, but in most cases it wouldn't be worth the extra complexity.
In particular, something like a `Monitor` (aka `lock`) with `Pulse` etc could do this just as well, as could any number of other threading constructs.
Threading is tricky, and an active loop is rarely the best way to manage it...
---
Re the edit... `secondThread.Join()` would be the obvious thing - but if you really want to use a separate token, see below. The advantage of this (over things like `ManualResetEvent`) is that it doesn't require anything from the OS - it is handled purely inside the CLI.
```
using System;
using System.Threading;
static class Program {
static void WriteLine(string message) {
Console.WriteLine(Thread.CurrentThread.Name + ": " + message);
}
static void Main() {
Thread.CurrentThread.Name = "Main";
object syncLock = new object();
Thread thread = new Thread(DoStuff);
thread.Name = "DoStuff";
lock (syncLock) {
WriteLine("starting second thread");
thread.Start(syncLock);
Monitor.Wait(syncLock);
}
WriteLine("exiting");
}
static void DoStuff(object lockHandle) {
WriteLine("entered");
for (int i = 0; i < 10; i++) {
Thread.Sleep(500);
WriteLine("working...");
}
lock (lockHandle) {
Monitor.Pulse(lockHandle);
}
WriteLine("exiting");
}
}
``` | why can't a local variable be volatile in C#? | [
"",
"c#",
"multithreading",
"volatile",
""
] |
is there anyway that I can convert a png to a bmp in C#?
I want to download a image then convert it to a bmp then set it as the desktop background.
I have the downloading bit and the background bit done.
I just need to convert the png to a bmp. | ```
Image Dummy = Image.FromFile("image.png");
Dummy.Save("image.bmp", ImageFormat.Bmp);
``` | Certainly. You'd want to load up a Bitmap object with your png:
```
Bitmap myBitmap = new Bitmap("mypng.png");
```
Then save it:
```
myBitmap.Save("mybmp.bmp", System.Drawing.Imaging.ImageFormat.Bmp);
``` | png to bmp in C# | [
"",
"c#",
"image",
"png",
"bmp",
""
] |
> **Possible Duplicate:**
> [What are the reasons why Map.get(Object key) is not (fully) generic](https://stackoverflow.com/questions/857420/what-are-the-reasons-why-map-getobject-key-is-not-fully-generic)
According to the javadocs (<http://java.sun.com/javase/6/docs/api/java/util/Map.html>) for the Map interface, the definition of get is
> V get(Object key)
> Returns the value to which the specified key is mapped, or null
> if this map contains no mapping for
> the key.
Code Example:
```
Map<InstrumentInfo, Double> moo = new HashMap<InstrumentInfo,Double>();
moo.get(new Integer(5));
```
I would expect that the above code will throw an exception or at least give a warning.
I would expect that with generics and type safety, the get method would take in a parameter of type . What is the reason for taking in type Object and not ? | Discussed in this question [What are the reasons why Map.get(Object key) is not (fully) generic](https://stackoverflow.com/questions/857420/what-are-the-reasons-why-map-getobject-key-is-not-fully-generic), as well... | The definition of Map.get is **Y get(Object key)** for a **Map< X,Y >** and the Map.get will return (key==null ? k==null : key.equals(k) , which I'd expect to return null, unless your InstrumentInfo have overloaded .equals to be able to compare to Integers.
Why **Y get(Object key)** isn't **Y get(X key)** I don't know though, but I'm guessing it has to do with backwards compatibility issues. | Java 6 Map.get() Type Safety Unexpected Behavior(?) | [
"",
"java",
"generics",
""
] |
Given a URL, how can you tell if the referenced file is and html file?
Obviously, its an html file if it ends in .html or /, but then there are .jsp files, too, so I'm wondering what other extensions may be out there for html.
Alternatively, if this information can be easily gained from a URL object in Java, that would be sufficient for my purposes. | Just from the URL you cannot, think of the following urls:
* <http://host1/index.html>
* <http://host2/index.php>
* <http://host3/index.asp>
* <http://host4/index.jsp>
* <http://host5/index.aspx>
* Or the the url of this question - [How do you determine if a file is html from the URL?](https://stackoverflow.com/questions/1065503/how-do-you-determine-if-a-file-is-html-from-the-url)
All of them return HTML content. The only sure way is to ask the server for the resource, and check the Content-TYpe header. It is better to use to send an HEAD request to the server, instead of GET or POST - it will give you just the headers and without the content.
```
URL url = ...
HttpURLConnection urlc = (HttpURLConnection)url.openConnection();
urlc.setAllowUserInteraction( false );
urlc.setDoInput( true );
urlc.setDoOutput( false );
urlc.setUseCaches( true );
urlc.setRequestMethod("HEAD");
urlc.connect();
String mime = urlc.getContentType();
if(mime.equals("text/html") {
// do your stuff
}
``` | you can't. but you can ask the server for headers and check the content type to see if it is text/html. | How do you determine if a file is html from the URL? | [
"",
"java",
"html",
"url",
""
] |
I'm wondering what a better design is for the intersection table for a many-to-many relationship.
The two approaches I am considering are:
```
CREATE TABLE SomeIntersection
(
IntersectionId UNIQUEIDENTIFIER PRIMARY KEY,
TableAId UNIQUEIDENTIFIER REFERENCES TableA NOT NULL,
TableBId UNIQUEIDENTIFIER REFERENCES TableB NOT NULL,
CONSTRAINT IX_Intersection UNIQUE(TableAId, TableBId )
)
```
or
```
CREATE TABLE SomeIntersection
(
TableAId UNIQUEIDENTIFIER REFERENCES TableA NOT NULL,
TableBId UNIQUEIDENTIFIER REFERENCES TableB NOT NULL,
PRIMARY KEY(TableAId, TableBId )
)
```
Are there benefits to one over the other?
**EDIT 2:\*\*\*\*Please Note:** I plan to use Entity Framework to provide an API for the database. With that in mind, does one solution work better with EF than the other?
**EDIT:** On a related note, for a intersection table that the two columns reference the same table (example below), is there a way to make the two fields differ on a record?
```
CREATE TABLE SomeIntersection
(
ParentRecord INT REFERENCES TableA NOT NULL,
ChildRecord INT REFERENCES TableA NOT NULL,
PRIMARY KEY(TableAId, TableBId )
)
```
I want to prevent the following
```
ParentRecord ChildRecord
=================================
1 1 --Cyclical reference!
``` | The second version is the best for me, it avoids the creation of an extra index. | It's a topic of some debate. I prefer the first form because I consider it better to be able to look up the mapping row by a single value, and like to enforce a perhaps-foolish consistency of having a single-column primary key available in every table without fail. Others think that having that column is a silly waste of space.
We meet for a few rounds of bare-knuckle boxing at a bar in New Jersey every couple of months. | Many to Many Relation Design - Intersection Table Design | [
"",
"sql",
"t-sql",
"database-design",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.