Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a setup function that runs onload to add some behaviours to elements. The setup function passes arguments to the mouseover event but those arguments are being changed during the for loop because they are local references.
```
function setupAreas( image, map, lots ) {
// obj is a simple wrapper for doc.getElementById
var image = obj(image); // image for imagemap
var map = obj(map); // imagemap element
var areas = map.getElementsByTagName('area');
for (var i in areas) {
var area = areas[i]; // imagemap area element
area.id = area.alt;
}
for (var lot_id in lots) {
if (lot_id != 'Lot No' && lot_id != '') {
var area = document.getElementById(lot_id);
if (!area || !area.coords) {
alert('no map coords for lot '+lot_id);
} else {
var coords = area.coords.split(",");
//alert('tag: '+area.tagName+' id: '+lot_id+' area: '+area);
var details = lots[lot_id];
if (details) {
// setup mouseover call with complete details of area
area.onmouseover = function(){ showLot(lot_id, area, coords, details, image, map, areas, lots) };
... snip ...
```
The problem is that because of the for loop the references `lot_id` and `area` are changed on each iteration. The result is the mouseover event for any element gives the `lot_id` and area of the *last area only*.
I don't want or need jQuery for this. A simple JS solution that doesn't pollute the global namespace is preferred. | Try surrounding the contents of your for loop in a closure:
```
for (var lot_id in lots) {
(function(lid){
//contents of for loop - use lid instead of lot_id
})(lot_id);
}
```
let me know how that works out
**EDIT:** You don't have to surround the whole loop actually, you could just surround the line that attaches the event:
```
(function(lid){
area.onmouseover = function(){ showLot(lid, area, coords, details, image, map, areas, lots) };
})(lot_id);
```
However surrounding the whole loop may prevent future bugs arising :) | You need to create a closure around your function. Something like this might help:
```
function makeShowLot(lot_id, area, coords, details, image, map, areas, lots) {
return function () {
showLot(lot_id, area, coords, details, image, map, areas, lots);
};
}
```
Then, do this instead:
```
area.onmouseover = makeShowLot(lot_id, area, coords, details, image, map, areas, lots);
```
`makeShowLot` is a function that returns a function. That function that is returned takes no arguments; all of the arguments needed for `showLot` are enclosed in this anonymous function. | how to pass local variables when assigning mouseover via anonymous function? | [
"",
"javascript",
""
] |
I need to compile [cdrtools](http://cdrecord.berlios.de/private/cdrecord.html) with mingw (to avoid cygwin dependancy).
It was done somehow long time ago but sources are not available anymore:
<http://web.archive.org/web/20040707140819/http://cdrtools.bootcd.ru/>
Does anyone know how to compile cdrtools with mingw?
Thanks. | These so called "forks" both have less functionality than the original software but they are full of bugs and dead since many years.
dvdrtools started with a cdrtools version from 2001 (now 12 years old), removed the original DVD support code and replaced that by something that may work with a Pioneer A03. It did not destroy portability so it compiles on Win-DOS as cdrtools from 2001 do.
wodim uses a cdrtools version from September 2004 and did the same for the dvd support code but in addition destroyed the portability framework and added own specific bugs.
Cdrtools compile and work on Win-Dos since aprox. y1998.
To compile on Win-Dos, you need a cygwin environment and "smake" (gmake has bugs that prevent it from working correctly on that platform).
On such an environment, you may compile for cygwin and even using cl.exe. If you use cl.exe to compile, you will not get a working mkisofs due to intended non-POSIX compliance of the compile enviroment from Microsoft (struct stat always contains st\_ino == 0, telling mkisofs that all files are hardlinked together).
There was a working mingw compile several years ago, but it seems that the instructions in READMEs/README.mingw32 no longer apply.
There has been a DJGPP compile aprox. 10 years ago (see READMEs/README.msdos) but this is also no longer correct for current DJGPP releases. | cdrtools has been forked into [cdrkit](http://www.cdrkit.org/) and [dvdrtools](http://freshmeat.net/projects/dvdrtools/)
Both of these have the same (or greater) functionality so you might be better to attempt to compile them instead.
The prior seems to have a [patch on a mailing list](http://lists.alioth.debian.org/pipermail/debburn-devel/2009-July/000647.html) to allow it to be compiled on Windows. Give it a go. | compile cdrtools with mingw | [
"",
"c++",
"mingw",
""
] |
given a traceback error log, i don't always know how to catch a particular exception.
my question is in general, how do i determine which "except" clause to write in order to handle a certain exception.
example 1:
```
File "c:\programs\python\lib\httplib.py", line 683, in connect
raise socket.error, msg
error: (10065, 'No route to host')
```
example 2:
```
return codecs.charmap_encode(input,errors,encoding_table)
UnicodeDecodeError: 'ascii' codec can't decode byte 0xd7 in position(...)
```
catching the 2nd example is obvious:
```
try:
...
except UnicodeDecodeError:
...
```
how do i catch specifically the first error? | Look at the stack trace. The code that raises the exception is: `raise socket.error, msg`.
So the answer to your question is: You have to catch `socket.error`.
```
import socket
...
try:
...
except socket.error:
...
``` | First one is also obvious, as second one e.g.
```
>>> try:
... socket.socket().connect(("0.0.0.0", 0))
... except socket.error:
... print "socket error!!!"
...
socket error!!!
>>>
``` | which exception catches xxxx error in python | [
"",
"python",
"exception",
""
] |
I have a problem where a couple 3 dimensional arrays allocate a huge amount of memory and the program sometimes needs to replace them with bigger/smaller ones and throws an OutOfMemoryException.
Example: there are 5 allocated 96MB arrays (200x200x200, 12 bytes of data in each entry) and the program needs to replace them with 210x210x210 (111MB). It does it in a manner similar to this:
```
array1 = new Vector3[210,210,210];
```
Where array1-array5 are the same fields used previously. This should set the old arrays as candidates for garbage collection but seemingly the GC does not act quickly enough and leaves the old arrays allocated before allocating the new ones - which causes the OOM - whereas if they where freed before the new allocations the space should be enough.
What I'm looking for is a way to do something like this:
```
GC.Collect(array1) // this would set the reference to null and free the memory
array1 = new Vector3[210,210,210];
```
I'm not sure if a full garbage collecion would be a good idea since that code may (in some situations) need to be executed fairly often.
Is there a proper way of doing this? | This is not an exact answer to the original question, "how to force GC', yet, I think it will help you to reexamine your issue.
After seeing your comment,
* *Putting the GC.Collect(); does seem to help, altought it still does not solve the problem completely - for some reason the program still crashes when about 1.3GB are allocated (I'm using System.GC.GetTotalMemory( false ); to find the real amount allocated).*
I will suspect you may have **memory fragmentation**. If the object is large (85000 bytes under .net 2.0 CLR if I remember correctly, I do not know whether it has been changed or not), the object will be allocated in a special heap, **Large Object Heap (LOH)**. GC does reclaim the memory being used by unreachable objects in LOH, yet, **it does not perform compaction,** in LOH as it does to other heaps (gen0, gen1, and gen2), due to performance.
If you do frequently allocate and deallocate large objects, it will make LOH fragmented and even though you have more free memory in total than what you need, you may not have a contiguous memory space anymore, hence, will get OutOfMemory exception.
I can think two workarounds at this moment.
1. Move to 64-bit machine/OS and take advantage of it :) (Easiest, but possibly hardest as well depending on your resource constraints)
2. If you cannot do #1, then try to allocate a huge chuck of memory first and use them (it may require to write some helper class to manipulate a smaller array, which in fact resides in a larger array) to avoid fragmentation. This may help a little bit, yet, it may not completely solve the issue and you may have to deal with the complexity. | Seems you've run into LOH (Large object heap) fragmentation issue.
[Large Object Heap](http://blogs.msdn.com/maoni/archive/2006/04/18/large-object-heap.aspx)
[CLR Inside Out Large Object Heap Uncovered](http://msdn.microsoft.com/en-us/magazine/cc534993.aspx)
You can check to see if you're having loh fragmentation issues using SOS
Check this [question](https://stackoverflow.com/questions/686950/large-object-heap-fragmentation) for an example of how to use SOS to inspect the loh. | Force garbage collection of arrays, C# | [
"",
"c#",
"arrays",
"garbage-collection",
"xna",
"out-of-memory",
""
] |
I have a C# WinForms app with an About box. I am putting the version number in the about box using:
```
FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location)
.FileVersion
```
This ends up giving me the Subversion revision number from which the executable was built.
I would also like to get the **date** of the build into the About box. I tried:
```
File.GetLastWriteTime(Assembly.GetEntryAssembly().Location)
```
But that gives me the write date of the executable, which only corresponds to the date when the app was **installed** (we are using ClickOnce) not **built**.
How can I get the **build date**? | If you use automatic versioning, you can convert the last two bits of the version number into a build date: [MSDN](http://channel9.msdn.com/forums/Coffeehouse/255737-AssemblyInfo-Version-Numbers/) | We're using this very similiar piece of code:
```
DateTime buildDate = new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime;
```
and I'm pretty sure it doesn't change when installing from ClickOnce.. If I'm wrong please correct me! | put build date in about box | [
"",
"c#",
"version-control",
"build-process",
"assemblies",
"clickonce",
""
] |
Prior to PHP 5.3 I used to name interfaces/abstract classes like this:
```
abstract class Framework_Package_Subpackage_Abstract {}
Framework/Package/Subpackage/Abstract.php
interface Framework_Package_Subpackage_Interface {}
Framework/Package/Subpackage/Interface.php
```
Now with PHP 5.3 and using namespaces I can't use my convention anymore, because `interface` and `abstract` are reserved keywords.
```
namespace Framework\Package\Subpackage;
abstract class Abstract {}
Framework/Package/Subpackage/Abstract.php
namespace Framework\Package\Subpackage;
interface Interface {}
Framework/Package/Subpackage/Interface.php
```
So, what should I name my classes/interfaces like? | A current coding guide "PSR-2" basically suggests you drop the interface down one directory and combine the name.
eg:
```
File \Vendor\Foo\Interface.php ===> \Vendor\FooInterface.php.
```
and the use stament eg:
```
use \Vendor\Foo\Interface; ===> use\Vendor\FooInterface;
```
see: <https://github.com/php-fig/fig-standards/blob/master/accepted/PSR-2-coding-style-guide.md> | About this question (Abstract and Interface), you might have a look at the post "[Migrating OOP Libraries and Frameworks to PHP 5.3](http://weierophinney.net/matthew/archives/181-Migrating-OOP-Libraries-and-Frameworks-to-PHP-5.3.html)" on Matthew Weier O'Phinney's blog -- it's about Zend Framework, and how they could solve that problem in 2.0.
One of the things they note is :
> In other OOP languages, such as
> Python, C#, interfaces are denoted by
> prefixing the interface with a capital
> 'I'; in the example above, we would
> then have Zend::View::IView.
So, in your example, you would have something like this, I guess :
```
namespace Framework\Package\Subpackage;
abstract class ASubpackage {}
Framework/Package/Subpackage/ASubpackage.php
namespace Framework\Package\Subpackage;
interface ISubpackage {}
Framework/Package/Subpackage/ISubpackage.php
```
What do you think about that ?
*(I have not tested this way, but it doesn't look like a bad idea ? )* | Naming of interfaces/abstract classes in PHP 5.3 (using namespaces) | [
"",
"php",
"namespaces",
"naming-conventions",
""
] |
I'm trying to set up a Spring JPA Hibernate simple example WAR for deployment to Glassfish.
I see some examples use a persistence.xml file, and other examples do not.
Some examples use a dataSource, and some do not. So far my understanding is that a dataSource is not needed if I have:
```
<persistence-unit name="educationPU"
transaction-type="JTA">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.coe.jpa.StudentProfile</class>
<properties>
<property name="hibernate.connection.driver_class"
value="com.mysql.jdbc.Driver" />
<property name="hibernate.connection.url"
value="jdbc:mysql://localhost:3306/COE" />
<property name="hibernate.connection.username" value="root" />
<property name="show_sql" value="true" />
<property name="dialect" value="org.hibernate.dialect.MySQLDialect" />
</properties>
</persistence-unit>
```
I can deploy fine, but my EntityManager is not getting injected by Spring.
My applicationContext.xml:
```
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalEntityManagerFactoryBean">
<property name="persistenceUnitName" value="educationPU" />
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<tx:annotation-driven transaction-manager="transactionManager" />
<bean id="StudentProfileDAO" class="com.coe.jpa.StudentProfileDAO">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<bean id="studentService" class="com.coe.services.StudentService">
</bean>
```
My class with the EntityManager:
```
public class StudentService {
private String saveMessage;
private String showModal;
private String modalHeader;
private StudentProfile studentProfile;
private String lastName;
private String firstName;
@PersistenceContext(unitName="educationPU")
private EntityManager em;
@Transactional
public String save()
{
System.out.println("*** em: " + this.em); //em is null
this.studentProfile= new StudentProfile();
this.saveMessage = "saved";
this.showModal = "true";
this.modalHeader= "Information Saved";
return "successs";
}
```
My web.xml:
```
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
```
Are there any pieces I am missing to have Spring inject "em" in to StudentService? | Just to confirm though you probably did...
Did you include the
```
<!-- tell spring to use annotation based congfigurations -->
<context:annotation-config />
<!-- tell spring where to find the beans -->
<context:component-scan base-package="zz.yy.abcd" />
```
bits in your application context.xml?
Also I'm not so sure you'd be able to use a jta transaction type with this kind of setup? Wouldn't that require a data source managed connection pool? So try RESOURCE\_LOCAL instead. | I'm confused. You're injecting a PU into the service layer and not the persistence layer? I don't get that.
I inject the persistence layer into the service layer. The service layer contains business logic and demarcates transaction boundaries. It can include more than one DAO in a transaction.
I don't get the magic in your save() method either. How is the data saved?
In production I configure spring like this:
```
<jee:jndi-lookup id="entityManagerFactory" jndi-name="persistence/ThePUname" />
```
along with the reference in web.xml
For unit testing I do this:
```
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
p:dataSource-ref="dataSource" p:persistence-xml-location="classpath*:META-INF/test-persistence.xml"
p:persistence-unit-name="RealPUName" p:jpaDialect-ref="jpaDialect"
p:jpaVendorAdapter-ref="jpaVendorAdapter" p:loadTimeWeaver-ref="weaver">
</bean>
``` | Spring JPA and persistence.xml | [
"",
"java",
"spring",
"jpa",
""
] |
What is the specific reason that [`clone()`](http://docs.oracle.com/javase/7/docs/api/java/lang/Object.html#clone%28%29) is defined as protected in `java.lang.Object`? | The fact that clone is protected is extremely dubious - as is the fact that the `clone` method is not declared in the `Cloneable` interface.
It makes the method pretty useless for taking copies of data because **you cannot say**:
```
if(a instanceof Cloneable) {
copy = ((Cloneable) a).clone();
}
```
I think that the design of `Cloneable` is now **largely regarded as a mistake** (citation below). I would normally want to be able to make implementations of an interface `Cloneable` but *not necessarily make the interface `Cloneable`* (similar to the use of `Serializable`). This cannot be done without reflection:
```
ISomething i = ...
if (i instanceof Cloneable) {
//DAMN! I Need to know about ISomethingImpl! Unless...
copy = (ISomething) i.getClass().getMethod("clone").invoke(i);
}
```
> Citation From **Josh Bloch's Effective Java**:
> *"The Cloneable interface was intended as a mixin interface for objects to advertise that they permit cloning. Unfortunately it fails to serve this purpose ... This is a highly atypical use of interfaces and not one to be emulated ... In order for implementing the interface to have any effect on a class, it and all of its superclasses must obey a **fairly complex, unenforceable and largely undocumented protocol**"* | The Clonable interface is just a marker saying the class can support clone. The method is protected because you shouldn't call it on object, you can (and should) override it as public.
From Sun:
In class Object, the clone() method is declared protected. If all you do is implement Cloneable, only subclasses and members of the same package will be able to invoke clone() on the object. To enable any class in any package to access the clone() method, you'll have to override it and declare it public, as is done below. (When you override a method, you can make it less private, but not more private. Here, the protected clone() method in Object is being overridden as a public method.) | Why is the clone() method protected in java.lang.Object? | [
"",
"java",
"oop",
"clone",
""
] |
Lets say I have an absolute url /testserver/tools/search.aspx that I store in a variable url.
I want to check if url == /tools/search.aspx without having to use /testserver.
A more complete example would be:
My testserver contains the url <http://www.testserver.com/tools/Search.aspx>,
but my live server contains the url <http://www.liveserver.com/tools/Search.aspx>
If I compare a variable url which stores the testserver url to the liveserver url, it will fail, thats why I want to just check the /tools/Search.aspx portion. | ```
if (url.ToLower().Contains("/tools/search.aspx"))
{
//do stuff here
}
```
I would use Contains in case you have a query string, but you could also use EndsWith("/tools/search.aspx") if you don't have query strings. | If your input is of the form `"http://www.testserver.com/tools/Search.aspx"`:
```
var path1 = new Uri("http://www.testserver.com/tools/Search.aspx").AbsolutePath;
var path2 = new Uri("http://www.liveserver.com/tools/Search.aspx").AbsolutePath;
```
Both result in `"/tools/Search.aspx"`.
Using the `Uri` is the best solution if you have to accept any URI, i.e. including those with a query string, fragment identifiers, etc.
---
If your input is of the form "/testserver.com/tools/Search.aspx" **and** you know that all input will always be of this form and valid and contain no other URI components:
```
var input = "/testserver.com/tools/Search.aspx";
var path1 = input.Substring(input.Index('/', 1));
```
Result is `"/tools/Search.aspx"`. | How can I get part of the following string? | [
"",
"c#",
"asp.net",
""
] |
I have a program that reads server information from a configuration file and would like to encrypt the password in that configuration that can be read by my program and decrypted.
Requirements:
* Encrypt plaintext password to be stored in the file
* Decrypt the encrypted password read in from the file from my program
How would I go about doing this? I was thinking of writing my own algorithm, but I feel it would be terribly insecure. | A simple way of doing this is to use Password Based Encryption in Java. This allows you to encrypt and decrypt a text by using a password.
This basically means initializing a `javax.crypto.Cipher` with algorithm `"AES/CBC/PKCS5Padding"` and getting a key from `javax.crypto.SecretKeyFactory` with the `"PBKDF2WithHmacSHA512"` algorithm.
Here is a code example (updated to replace the less secure MD5-based variant):
```
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.AlgorithmParameters;
import java.security.GeneralSecurityException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
public class ProtectedConfigFile {
public static void main(String[] args) throws Exception {
String password = System.getProperty("password");
if (password == null) {
throw new IllegalArgumentException("Run with -Dpassword=<password>");
}
// The salt (probably) can be stored along with the encrypted data
byte[] salt = new String("12345678").getBytes();
// Decreasing this speeds down startup time and can be useful during testing, but it also makes it easier for brute force attackers
int iterationCount = 40000;
// Other values give me java.security.InvalidKeyException: Illegal key size or default parameters
int keyLength = 128;
SecretKeySpec key = createSecretKey(password.toCharArray(),
salt, iterationCount, keyLength);
String originalPassword = "secret";
System.out.println("Original password: " + originalPassword);
String encryptedPassword = encrypt(originalPassword, key);
System.out.println("Encrypted password: " + encryptedPassword);
String decryptedPassword = decrypt(encryptedPassword, key);
System.out.println("Decrypted password: " + decryptedPassword);
}
private static SecretKeySpec createSecretKey(char[] password, byte[] salt, int iterationCount, int keyLength) throws NoSuchAlgorithmException, InvalidKeySpecException {
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA512");
PBEKeySpec keySpec = new PBEKeySpec(password, salt, iterationCount, keyLength);
SecretKey keyTmp = keyFactory.generateSecret(keySpec);
return new SecretKeySpec(keyTmp.getEncoded(), "AES");
}
private static String encrypt(String property, SecretKeySpec key) throws GeneralSecurityException, UnsupportedEncodingException {
Cipher pbeCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
pbeCipher.init(Cipher.ENCRYPT_MODE, key);
AlgorithmParameters parameters = pbeCipher.getParameters();
IvParameterSpec ivParameterSpec = parameters.getParameterSpec(IvParameterSpec.class);
byte[] cryptoText = pbeCipher.doFinal(property.getBytes("UTF-8"));
byte[] iv = ivParameterSpec.getIV();
return base64Encode(iv) + ":" + base64Encode(cryptoText);
}
private static String base64Encode(byte[] bytes) {
return Base64.getEncoder().encodeToString(bytes);
}
private static String decrypt(String string, SecretKeySpec key) throws GeneralSecurityException, IOException {
String iv = string.split(":")[0];
String property = string.split(":")[1];
Cipher pbeCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
pbeCipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(base64Decode(iv)));
return new String(pbeCipher.doFinal(base64Decode(property)), "UTF-8");
}
private static byte[] base64Decode(String property) throws IOException {
return Base64.getDecoder().decode(property);
}
}
```
One problem remains: Where should you store the password that you use to encrypt the passwords? You can store it in the source file and obfuscate it, but it's not too hard to find it again. Alternatively, you can give it as a system property when you start the Java process (`-DpropertyProtectionPassword=...`).
The same issue remains if you use the KeyStore, which also is protected by a password. Basically, you will need to have one master password somewhere, and it's pretty hard to protect. | Check out [jasypt](http://www.jasypt.org/), which is a library offering basic encryption capabilities with minimum effort. | Encrypt password in configuration files | [
"",
"java",
"security",
"encryption",
"configuration",
"cryptography",
""
] |
Often when writing PHP I'll have it output some HTML like this -
```
echo "<a href="../" title="link title">".$link_text."</a>";
```
Obviously this won't parse as I need to escape the double quotes in the attributes of the `<a>` element. Is there a regex that would quickly do this rather than me manually adding the backslashes?
One other thing - the regex shouldn't escape double quotes outside of the tag (e.g. where I've appended the `$link_text` variable.
Any ideas? | You should just use single-quotes instead:
```
echo '<a href="../" title="link title">' . $link_text . '</a>';
``` | Solutions I can come up with (not without escaping):
* Single quotes
```
echo '<a href="../">' . $link_text. '</a>';
```
* Use double quotes
```
echo "<a href='../'>$link_text</a>";
```
* Sprintf
```
echo sprintf('<a href="../">%s</a>', $link_text);
```
* Use HEREDOC
```
echo <<<EOF
<a href="../">$link_text</a>
EOF;
```
* Use template engine like [smarty](http://smarty.net)
* Exit *PHP-mode*:
```
?><a href="../"><?php echo $link_text ?></a><?php // other code...
```
BTW, be sure to use `htmlspecialchars()` on `$link_text` variable, or you’ll have a XSS security hole. | Escape double quotes of HTML attributes output by PHP | [
"",
"php",
"html",
"regex",
"bbedit",
""
] |
I am writing python scripts and execute them in a Makefile. The python script is used to process data in a pipeline. I would like Makefile to execute the script every time I make a change to my python scripts.
Does anyone have an idea of how to do this? | That's not a lot of information, so this answer is a bit vague. The basic principle of Makefiles is to list dependencies for each target; in this case, your target (let's call it foo) depends on your python script (let's call it do-foo.py):
```
foo: do-foo.py
python do-foo.py > foo
```
Now foo will be rerun whenever do-foo.py changes (provided, of course, you call make). | And in case when the scripts that need to be run don't produce any useful output file that can be used as a target, you can just use a dummy target:
```
scripts=a.py b.py c.py
checkfile=.pipeline_up_to_date
$(checkfile): $(scripts)
touch $(checkfile)
echo "Launching some commands now."
default: $(checkfile)
``` | Python Script Executed with Makefile | [
"",
"python",
"makefile",
""
] |
I know that google's v8 compiles javascript into native machine (binary if I understand correctly) code.
Is there a way to take the output and turn it into a exe? | I don't think you can directly turn a piece of JavaScript into an executable using V8, but you can probably make an application that bundles the V8 engine with the JavaScript and runs it as a stand-alone.
You can find all information about V8 on [its project page](http://code.google.com/p/v8/).
Also note that JavaScript can't be completely compiled as it's a dynamic language. With V8, it's JIT-compiled (like .NET, for example.) It's still possible to turn it into a stand-alone executable though (like .NET, for example.)
If you want to develop stand-alone applications that make use of HTML for rendering, you could have a look at [Adobe Air](http://www.adobe.com/products/air/) as well. | Javascript cannot be compiled just once. The language has *eval* which is pretty widely used. (for JSON for instance) You need to carry around the JIT, and the whole runtime.
JIT here is only an optimization, not the way to get rid of the compiler/interpreter. | How to turn the V8 compiled javascript into an EXE? | [
"",
"javascript",
"executable",
"v8",
""
] |
I needed a **function** that simply checks **if a string can be converted to a valid integer** (for form validation).
After searching around, I ended up using a function I had from 2002 which works using C#1 (below).
However, it just seems to me that although the code below works, **it is a misuse of try/catch** to use it not to catch an error but to determine a value.
**Is there a better way to do this in C#3?**
```
public static bool IsAValidInteger(string strWholeNumber)
{
try
{
int wholeNumber = Convert.ToInt32(strWholeNumber);
return true;
}
catch
{
return false;
}
}
```
# Answer:
John's answer below helped me build the function I was after without the try/catch. In this case, a blank textbox is also considered a valid "whole number" in my form:
```
public static bool IsAValidWholeNumber(string questionalWholeNumber)
{
int result;
if (questionalWholeNumber.Trim() == "" || int.TryParse(questionalWholeNumber, out result))
{
return true;
}
else
{
return false;
}
}
``` | ```
if (int.TryParse(string, out result))
{
// use result here
}
``` | This probably won't be much faster, but at least it looks cleaner (no exception handling):
```
public static bool IsAValidInteger(string strWholeNumber)
{
int wholeNumber;
return int.TryParse(strWholeNumber, out wholeNumber);
}
``` | Is there a better way to determine if a string can be an integer other than try/catch? | [
"",
"c#",
"validation",
""
] |
I'm writing a small library in C++ that I need to be able to build on quite a few different platforms, including iPhone, Windows, Linux, Mac and Symbian S60. I've written most of the code so that it is platform-agnostic but there are some portions that must be written on a per-platform basis.
Currently I accomplish this by including a different header depending on the current platform but I'm having trouble fleshing this out because I'm not sure what preprocessor definitions are defined for all platforms. For windows I can generally rely on seeing WIN32 or \_WIN32. For Linux I can rely on seeing \_UNIX\_ but I am less certain about the other platforms or their 64-bit variants. Does anyone have a list of the different definitions found on platforms or will I have to resort to a config file or gcc parameter? | I have [this sourceforge pre-compiler](http://sourceforge.net/p/predef/wiki/Home/) page in my bookmarks. | The definitions are going to be purely up to your compiler vendor. If you are using the same compiler (say, gcc) on all your platforms then you will have a little bit easier time of it.
You might also want to try to instead organize your project such that most of the .h files are not platform dependent. Split your implementation (cpp files) into separate files; one for the nonspecific stuff and one for each platform. The platform specific ones can include 'private' headers that only make sense for that platform. You may have to make adapter functions to get something like this to work 100% (when the system libs take slightly differed arguments) but I have found it to be really helpful in the end, and bringing on a new platform is a whole lot easier in the future. | Platform C Preprocessor Definitions | [
"",
"c++",
"c-preprocessor",
"portability",
""
] |
i want to pass large variables to a PHP script on another server with http like:
"example.com/get.php?data=this is quite alot data..."
I always get the server(apache) response: "Request-URI Too Large"
Any ideas hot to pass the big variables to that script? | If data is too long for GET, what about using POST ?
*(Considering the limitation on POST's size is generally arround 2 MB in PHP ; depends on configuration, and can be more.)*
If you are using [curl](http://php.net/curl) *(that is if it's a PHP script on you server that does the request to another server ; else, you'll probably use a form in HTML)*, have a look at te documentation of [`curl_setopt`](http://php.net/manual/en/function.curl-setopt.php) : some options will definitly interest you ;-) | Try using POST instead of GET? That is, something like this:
`<form name=fooForm method=POST action=http://example.com/get.php>
<input type="hidden" name=data value="this is quite a lot of data">
</form>`
Either add in a submit button or trigger the submit using javascript somewhat like this:
`<a href="javascript:document.fooForm.submit()">Submit</a>`
You might also try passing the data via cookies, they can be up to 4KB in size. | Pass large variables with php and http? | [
"",
"php",
"http",
"variables",
""
] |
In my C# application I need to create a .resx file of strings customized for every customer.
What I want to do is avoid recompiling the entire project every time I have to provide my application to my customer, so I need to dynamic access to this string.
So, how can I access (during the app execution) to a resx file if I kwow the file name only on the execution time?
Since now I write something similar:
```
Properties.Resources.MyString1
```
where Resource is my Resource.resx file.
But I need something like this:
```
GetStringFromDynamicResourceFile("MyFile.resx", "MyString1");
```
Is it possible?
Thanks
Mark | Will something like this help in your case?
```
Dictionary<string, string> resourceMap = new Dictionary<string, string>();
public static void Func(string fileName)
{
ResXResourceReader rsxr = new ResXResourceReader(fileName);
foreach (DictionaryEntry d in rsxr)
{
resourceMap.Add(d.Key.ToString(),d.Value.ToString());
}
rsxr.Close();
}
public string GetResource(string resourceId)
{
return resourceMap[resourceId];
}
``` | You could put the needed resources into a separate DLL (one for each customer), then extract the resources dynamically using Reflection:
```
Assembly ass = Assembly.LoadFromFile("customer1.dll");
string s = ass.GetManifestResource("string1");
```
I may have the syntax wrong - it's early. One potential caveat here: accessing a DLL through Reflection will lock the DLL file for a length of time, which may block you from updating or replacing the DLL on the client's machine. | Read a string stored in a resource file (resx) with dynamic file name | [
"",
"c#",
"dynamic",
"resources",
""
] |
I am confused about what means the update and delete rule in SQL Server 2008 Management Studio when we define foreign key constraints. I also did not find related help documents (e.g. F1 help).
Here is the screen snapshot. Appreciate if anyone could describe what do they mean and recommend some related documents to read. :-)
 | The foreign key defines a parent - child relationship between two tables. The primary key in the parent table is the foreign key in the up to n child table rows.
Now if that primary key in the parent table gets UPDATE, the UPDATE RULE kicks in. Either all the child rows are also updated, set to NULL or whatever. Best practice however is to have a primary key that NEVER changes (a fixed ID or something), so that's the less important rule.
The more important one is the DELETE rule - what if the parent row is deleted (e.g. the Order is deleted)? You can either also delete all child rows (all the Order line items) with CASCADE DELETE, or you can set their foreign key to NULL (they don't have a parent anymore) - that's totally up to your concrete scenario.
In the Order/order lines scenario, it might be totally useful to delete the order lines when the complete order gets deleted, but you probably don't want to delete a product, just because an order that references it has been deleted - there's no one single CORRECT answer - it depends on your scenario and your app.
Marc | It looks like the documentation is at [Foreign Key Relationships Dialog Box](http://technet.microsoft.com/en-us/library/ms177288.aspx).
BTW, F1 help worked fine for me in SSMS 2008. It took me right to the above page (after I searched for 1/2 hour online, of course). | Understanding Update and Delete Rules for Relationships in SSMS 2008 | [
"",
"sql",
"sql-server",
"sql-server-2008",
"foreign-keys",
""
] |
I am new to Qt and have one error I am unable to fix.
I have a bunch of windows (VS2005) static library file (`.lib`). And I am testing if they work well with Qt. So I took the most simple library that I have. (Called `MessageBuffer`).
So I added `MessageBuffer.h` to the `main.cpp`, and added the location of those file in the `INCLUDEPATH` of the `.pro`.
Until then everything seem fine, I can use the class and Qt IDE show all method and everything. So to me it look like it found the .h file.
Now I added the `MessageBuffer.lib` (VS2005/Debug build) in the `.pro` like this:
```
LIBS += E:/SharedLibrary/lib/MessageBufferd.lib
```
I have also tried the following:
```
win32:LIBS += E:/SharedLibrary/lib/MessageBufferd.lib
LIBS += -LE:/SharedLibrary/lib -lMessageBufferd
win32:LIBS += -LE:/SharedLibrary/lib -lMessageBufferd
```
Here is the content of my `.pro` file:
```
QT += opengl
TARGET = SilverEye
TEMPLATE = app
INCLUDEPATH += E:/SharedLibrary/MessageBuffer
SOURCES += main.cpp \
silvereye.cpp
HEADERS += silvereye.h
FORMS += silvereye.ui
OTHER_FILES +=
win32:LIBS += E:/SharedLibrary/lib/MessageBufferd.lib
```
They all give me the same errors: (and I get the same even if I don't include the `.lib`)
```
Running build steps for project SilverEye...
Configuration unchanged, skipping QMake step.
Starting: C:/Qt/2009.03/mingw/bin/mingw32-make.exe -w
mingw32-make: Entering directory `C:/Documents and Settings/JP/My Documents/QTProjects/SilverEye'
C:/Qt/2009.03/mingw/bin/mingw32-make -f Makefile.Debug
mingw32-make[1]: Entering directory `C:/Documents and Settings/JP/My Documents/QTProjects/SilverEye'
g++ -enable-stdcall-fixup -Wl,-enable-auto-import -Wl,-enable-runtime-pseudo-reloc -mthreads -Wl -Wl,-subsystem,windows -o debug\SilverEye.exe debug/main.o debug/silvereye.o debug/moc_silvereye.o -L"c:\Qt\2009.03\qt\lib" -lopengl32 -lglu32 -lgdi32 -luser32 -lmingw32 -lqtmaind E:/SharedLibrary/lib/MessageBufferd.lib -lQtOpenGLd4 -lQtGuid4 -lQtCored4
mingw32-make[1]: Leaving directory `C:/Documents and Settings/JP/My Documents/QTProjects/SilverEye'
mingw32-make: Leaving directory `C:/Documents and Settings/JP/My Documents/QTProjects/SilverEye'
debug/main.o: In function `Z5qMainiPPc':
C:/Documents and Settings/JP/My Documents/QTProjects/SilverEye/main.cpp:12: undefined reference to `MessageBuffer::MessageBuffer()'
C:/Documents and Settings/JP/My Documents/QTProjects/SilverEye/main.cpp:13: undefined reference to `MessageBuffer::Append(char*, int)'
C:/Documents and Settings/JP/My Documents/QTProjects/SilverEye/main.cpp:17: undefined reference to `MessageBuffer::~MessageBuffer()'
C:/Documents and Settings/JP/My Documents/QTProjects/SilverEye/main.cpp:17: undefined reference to `MessageBuffer::~MessageBuffer()'
collect2: ld returned 1 exit status
mingw32-make[1]: *** [debug\SilverEye.exe] Error 1
mingw32-make: *** [debug] Error 2
Exited with code 2.
Error while building project SilverEye
When executing build step 'Make'
```
Can anyone help please? | Based on the question [Use libraries compiled with visual studio in an application compiled by g++ (mingw)](https://stackoverflow.com/questions/1138170/use-libraries-compiled-with-visual-studio-in-an-application-compiled-by-g-ming) and the MSDN forum post [I can't mix VC & GCC](http://social.msdn.microsoft.com/Forums/en-US/vclanguage/thread/f37a19bd-beb3-438b-8adc-14dc39ccad0b) it does not appear you can link a gcc application with visual c++ compiled libraries.
The solution would be to recompile everything with the same compiler. | The MinGW FAQ discusses this problem and offers a solution:
1. Create a definition file using reimp (for lib files) or pexports (for dll files).
2. Remove the underscore prefixes from the stdcall functions.
3. Use dlltool to convert the MSVC library into a MinGW library with the new definition.
That didn’t work. We finally removed the ordinals from the function names, which caused it to compile. But the program wouldn’t run because it couldn’t find the linked functions in the DLL. Finally, after consulting the MSDN documentation for definition files, we changed the build instructions:
1. Create a definition file using reimp.
2. For each stdcall function (formatted as \_name@ordinal) add a line name = \_name@ordinal, allowing MinGW to map its stdcall naming convention to that of MSVC.
3. Use dlltool to convert the MSVC library into a MinGW library with the new definition.
It worked! To compile the project you must simply:
1. Download and install the Qt/Windows package, which includes MinGW.
2. Download reimp and drop it into the MinGW/bin folder.
3. Download the development packages for the third-party libraries and point an environment variable to that location.
4. Build the project with the usual qmake/make commands.
Taken from:
<http://blog.outofhanwell.com/2006/05/01/linking-msvc-libraries-with-mingw-projects/> | Qt/mingw32 undefined reference errors... unable to link a .lib | [
"",
"c++",
"qt",
"linker",
"mingw",
""
] |
I am too cheap to buy crystal reports so i built the report in asp.net, the only problem I'm facing is printing the report and making it look professional. On different printer's the report looks diff, i want to be able to control the final output and make the report print standard across all printers. You guys have any suggestions on how to achieve this properly? | You could try implementing a print stylesheet (you'll find many examples Googling the term), but that can be laborious if you're not familiar with css.
If you're checking out pdf solutions, I've used iTextSharp to create pdfs. It's relatively easy, open source and mature and used by many corporations. | Why not just use Reporting Services? It's free and easy to integrate with both WebForms and WinForms apps. Supports export to PDF, Excel, etc. | HTML Printing | [
"",
"c#",
"asp.net",
"html",
"printing",
""
] |
I have a strange problem with some documents on my webpage.
My data is stored in a MYSQL Database, UTF8 encoded. If read the values my webbpage displays
> Rezept : Gem�se mal anders (Gem�selaibchen)
I need ü / ü!
Content in the database is "Gemüse ... " ..
The raw data in my error\_log looks like this
> [title] => Rezept : Gemüse mal anders (Gemüselaibchen)
The webpage header is:
```
<!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" xml:lang="en" lang="en">
<head>
<!--[if IE]>
<link rel="stylesheet" href="http://www.dev-twitter-gewitter.com/css//blueprint/ie.css"
type="text/css" media="screen, projection">
<![endif]-->
<meta name="text/html; charset=UTF-8" content="Content-Type" />
``` | MySQL needs to know you want the output as UTF-8 - it's likely configured to send as latin1, so your browser sees the invalid UTF-8 byte sequences and outputs the "not a character" glyph.
Send the query "SET NAMES utf8" immediately after opening the MySQL connection, or change the configuration (if possible). | **You have to set the encoding of your web page.**
There are three ways to set the encoding:
3. **HTML/XHTML**: Use a HTTP header:
```
Content-Type: text/html; charset=UTF-8
```
4. **HTML**: Use a meta element: (Also possible for XHTML, but somewhat unusually)
```
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
```
5. **XHTML only**: Set the encoding in the preamble: (**Preferred for XHTML**)
```
<?xml version="1.0" encoding="UTF-8"?>
```
**If you want to verify the problem first:**
First change the encoding manually using your browser. If that works you can set it in your HTML file. Make sure you reset the manual encoding to automatic detection, otherwise it'll work on your workstation, but not on your users' workstations!
**A PHP speciality**: Make sure your *internal encoding* is set to UTF-8, too! All outputs are converted to this encoding.
You can enforce the internal encoding using [`mb_internal_encoding`](http://www.php.net/manual/en/function.mb-internal-encoding.php) at the top of every file.
**After all**: All this doesn't help if your code isn't actually UTF-8 encoded! If it is, check if there are any helper functions which might destroy the UTF-8 encoding. | UTF-8 Problem, no Idea | [
"",
"php",
"encoding",
"utf-8",
""
] |
how do i call the doSubmit() function from the conFirmUpload() when the confirm msg box is true?
```
<script type="text/javascript">
function confirmUpload() {
if (confirm("Are you sure want to upload '" + document.getElementById("txtWS").value + "' ?") == true) {
return true;
}
else
return false;
}
function doSubmit(btnUpload) {
if (typeof(Page_ClientValidate) == 'function' && Page_ClientValidate() == false) {
return false;
}
btnUpload.disabled = 'disabled';
btnUpload.value = 'Processing. This may take several minutes...';
<%= ClientScript.GetPostBackEventReference(btnUpload, string.Empty) %>;
}
</script>
``` | ```
var btnUpload = document.getElementById('buttonId');
doSubmit(btnUpload);
```
Put that in your if-block. Make sure the button has an ID. | Without knowing more What about this?
```
function confirmUpload(btnUpload) {
if (confirm("Are you sure want to upload '" + document.getElementById("txtWS").value + "' ?") == true) {
doSubmit(btnUpload);
}
else
return false;
}
``` | how to call another function in javascript? | [
"",
"javascript",
""
] |
Python sorts by byte value by default, which means é comes after z and other equally funny things. What is the best way to sort alphabetically in Python?
Is there a library for this? I couldn't find anything. Preferrably sorting should have language support so it understands that åäö should be sorted after z in Swedish, but that ü should be sorted by u, etc. Unicode support is thereby pretty much a requirement.
If there is no library for it, what is the best way to do this? Just make a mapping from letter to a integer value and map the string to a integer list with that? | IBM's [ICU](http://site.icu-project.org/) library does that (and a lot more). It has Python bindings: [PyICU](http://pypi.python.org/pypi/PyICU).
**Update**: The core difference in sorting between ICU and `locale.strcoll` is that ICU uses the full [Unicode Collation Algorithm](http://unicode.org/reports/tr10/) while `strcoll` uses [ISO 14651](http://en.wikipedia.org/wiki/ISO_14651).
The differences between those two algorithms are briefly summarized here: <http://unicode.org/faq/collation.html#13>. These are rather exotic special cases, which should rarely matter in practice.
```
>>> import icu # pip install PyICU
>>> sorted(['a','b','c','ä'])
['a', 'b', 'c', 'ä']
>>> collator = icu.Collator.createInstance(icu.Locale('de_DE.UTF-8'))
>>> sorted(['a','b','c','ä'], key=collator.getSortKey)
['a', 'ä', 'b', 'c']
``` | I don't see this in the answers. My Application sorts according to the locale using python's standard library. It is pretty easy.
```
# python2.5 code below
# corpus is our unicode() strings collection as a list
corpus = [u"Art", u"Älg", u"Ved", u"Wasa"]
import locale
# this reads the environment and inits the right locale
locale.setlocale(locale.LC_ALL, "")
# alternatively, (but it's bad to hardcode)
# locale.setlocale(locale.LC_ALL, "sv_SE.UTF-8")
corpus.sort(cmp=locale.strcoll)
# in python2.x, locale.strxfrm is broken and does not work for unicode strings
# in python3.x however:
# corpus.sort(key=locale.strxfrm)
```
---
Question to Lennart and other answerers: Doesn't anyone know 'locale' or is it not up to this task? | How do I sort unicode strings alphabetically in Python? | [
"",
"python",
"sorting",
"unicode",
"internationalization",
"collation",
""
] |
This is what I am trying to do. We are 5 people in a room. Everybody has a PC. Each PC has mp3 files but only **one of the PCs has speakers** (ex. called Speakers-PC). So, instead of asking the person on Speakers-PC to play you a song you want, I was thinking of ***an application that can take an audio file from a No-Speakers-PC and send it to the Speakers-PC. The Speakers-PC can then play the audio file.*** Of course, if multiple files are sent, the application on Speakers-PC will have a queue.
So, is it worth digging or it will be just better if we buy wireless speakers and rotate the transmitter (instead we are now rotating the speakers) :)
Any ideas on how to implement something like this? I am familiar mostly with .NET technologies.
Any broad or specific help would be greatly appreciated.
Best Regards,
Kiril | Many media players come with web interfaces already. One of the winamp ones, for example, is <http://www.winamp.com/plugins/details/92511> | [VLC](http://www.videolan.org/vlc/features.html) is the swiss army knife of media streaming, [take a peek at the extensive feature set](http://www.videolan.org/vlc/) :) | Streaming audio file to another computer | [
"",
"c#",
".net",
"wpf",
"silverlight",
""
] |
Given any iterable, for example: "ABCDEF"
Treating it almost like a numeral system as such:
A
B
C
D
E
F
AA
AB
AC
AD
AE
AF
BA
BB
BC
....
FF
AAA
AAB
....
How would I go about finding the ith member in this list? Efficiently, not by counting up through all of them. I want to find the billionth (for example) member in this list. I'm trying to do this in python and I am using 2.4 (not by choice) which might be relevant because I do not have access to itertools.
Nice, but not required: Could the solution be generalized for pseudo-["mixed radix"](http://en.wikipedia.org/wiki/Mixed_radix) system?
--- RESULTS ---
```
# ------ paul -----
def f0(x, alph='ABCDE'):
result = ''
ct = len(alph)
while x>=0:
result += alph[x%ct]
x /= ct-1
return result[::-1]
# ----- Glenn Maynard -----
import math
def idx_to_length_and_value(n, length):
chars = 1
while True:
cnt = pow(length, chars)
if cnt > n:
return chars, n
chars += 1
n -= cnt
def conv_base(chars, n, values):
ret = []
for i in range(0, chars):
c = values[n % len(values)]
ret.append(c)
n /= len(values)
return reversed(ret)
def f1(i, values = "ABCDEF"):
chars, n = idx_to_length_and_value(i, len(values))
return "".join(conv_base(chars, n, values))
# -------- Laurence Gonsalves ------
def f2(i, seq):
seq = tuple(seq)
n = len(seq)
max = n # number of perms with 'digits' digits
digits = 1
last_max = 0
while i >= max:
last_max = max
max = n * (max + 1)
digits += 1
result = ''
i -= last_max
while digits:
digits -= 1
result = seq[i % n] + result
i //= n
return result
# -------- yairchu -------
def f3(x, alphabet = 'ABCDEF'):
x += 1 # Make us skip "" as a valid word
group_size = 1
num_letters = 0
while 1: #for num_letters in itertools.count():
if x < group_size:
break
x -= group_size
group_size *= len(alphabet)
num_letters +=1
letters = []
for i in range(num_letters):
x, m = divmod(x, len(alphabet))
letters.append(alphabet[m])
return ''.join(reversed(letters))
# ----- testing ----
import time
import random
tries = [random.randint(1,1000000000000) for i in range(10000)]
numbs = 'ABCDEF'
time0 = time.time()
s0 = [f1(i, numbs) for i in tries]
print 's0 paul',time.time()-time0, 'sec'
time0 = time.time()
s1 = [f1(i, numbs) for i in tries]
print 's1 Glenn Maynard',time.time()-time0, 'sec'
time0 = time.time()
s2 = [f2(i, numbs) for i in tries]
print 's2 Laurence Gonsalves',time.time()-time0, 'sec'
time0 = time.time()
s3 = [f3(i,numbs) for i in tries]
print 's3 yairchu',time.time()-time0, 'sec'
```
times:
```
s0 paul 0.470999956131 sec
s1 Glenn Maynard 0.472999811172 sec
s2 Laurence Gonsalves 0.259000062943 sec
s3 yairchu 0.325000047684 sec
>>> s0==s1==s2==s3
True
``` | Third time's the charm:
```
def perm(i, seq):
seq = tuple(seq)
n = len(seq)
max = n # number of perms with 'digits' digits
digits = 1
last_max = 0
while i >= max:
last_max = max
max = n * (max + 1)
digits += 1
result = ''
i -= last_max
while digits:
digits -= 1
result = seq[i % n] + result
i //= n
return result
``` | Multi-radix solution at the bottom.
```
import math
def idx_to_length_and_value(n, length):
chars = 1
while True:
cnt = pow(length, chars)
if cnt > n:
return chars, n
chars += 1
n -= cnt
def conv_base(chars, n, values):
ret = []
for i in range(0, chars):
c = values[n % len(values)]
ret.append(c)
n /= len(values)
return reversed(ret)
values = "ABCDEF"
for i in range(0, 100):
chars, n = idx_to_length_and_value(i, len(values))
print "".join(conv_base(chars, n, values))
```
---
```
import math
def get_max_value_for_digits(digits_list):
max_vals = []
for val in digits_list:
val = len(val)
if max_vals:
val *= max_vals[-1]
max_vals.append(val)
return max_vals
def idx_to_length_and_value(n, digits_list):
chars = 1
max_vals = get_max_value_for_digits(digits_list)
while True:
if chars-1 >= len(max_vals):
raise OverflowError, "number not representable"
max_val = max_vals[chars-1]
if n < max_val:
return chars, n
chars += 1
n -= max_val
def conv_base(chars, n, digits_list):
ret = []
for i in range(chars-1, -1, -1):
digits = digits_list[i]
radix = len(digits)
c = digits[n % len(digits)]
ret.append(c)
n /= radix
return reversed(ret)
digits_list = ["ABCDEF", "ABC", "AB"]
for i in range(0, 120):
chars, n = idx_to_length_and_value(i, digits_list)
print "".join(conv_base(chars, n, digits_list))
``` | How to produce the i-th combination/permutation without iterating | [
"",
"python",
"combinatorics",
""
] |
If you want to check if something matches a regex, if so, print the first group, you do..
```
import re
match = re.match("(\d+)g", "123g")
if match is not None:
print match.group(1)
```
This is completely pedantic, but the intermediate `match` variable is a bit annoying..
Languages like Perl do this by creating new `$1`..`$9` variables for match groups, like..
```
if($blah ~= /(\d+)g/){
print $1
}
```
From [this reddit comment](http://www.reddit.com/r/Python/comments/92ewt/experiment_adding_re_to_python_string_objects/c0b7895),
```
with re_context.match('^blah', s) as match:
if match:
...
else:
...
```
..which I thought was an interesting idea, so I wrote a simple implementation of it:
```
#!/usr/bin/env python2.6
import re
class SRE_Match_Wrapper:
def __init__(self, match):
self.match = match
def __exit__(self, type, value, tb):
pass
def __enter__(self):
return self.match
def __getattr__(self, name):
if name == "__exit__":
return self.__exit__
elif name == "__enter__":
return self.__name__
else:
return getattr(self.match, name)
def rematch(pattern, inp):
matcher = re.compile(pattern)
x = SRE_Match_Wrapper(matcher.match(inp))
return x
return match
if __name__ == '__main__':
# Example:
with rematch("(\d+)g", "123g") as m:
if m:
print(m.group(1))
with rematch("(\d+)g", "123") as m:
if m:
print(m.group(1))
```
(This functionality could theoretically be patched into the `_sre.SRE_Match` object)
It would be nice if you could skip the execution of the `with` statement's code block, if there was no match, which would simplify this to..
```
with rematch("(\d+)g", "123") as m:
print(m.group(1)) # only executed if the match occurred
```
..but this seems impossible based of what I can deduce from [PEP 343](http://www.python.org/dev/peps/pep-0343/)
Any ideas? As I said, this is really trivial annoyance, almost to the point of being code-golf.. | Starting `Python 3.8`, and the introduction of [assignment expressions (PEP 572)](https://www.python.org/dev/peps/pep-0572/) (`:=` operator), we can now capture the condition value `re.match(r'(\d+)g', '123g')` in a variable `match` in order to both check if it's not `None` and then re-use it within the body of the condition:
```
>>> if match := re.match(r'(\d+)g', '123g'):
... print(match.group(1))
...
123
>>> if match := re.match(r'(\d+)g', 'dddf'):
... print(match.group(1))
...
>>>
``` | I don't think it's trivial. I don't want to have to sprinkle a redundant conditional around my code if I'm writing code like that often.
This is slightly odd, but you can do this with an iterator:
```
import re
def rematch(pattern, inp):
matcher = re.compile(pattern)
matches = matcher.match(inp)
if matches:
yield matches
if __name__ == '__main__':
for m in rematch("(\d+)g", "123g"):
print(m.group(1))
```
The odd thing is that it's using an iterator for something that isn't iterating--it's closer to a conditional, and at first glance it might look like it's going to yield multiple results for each match.
It does seem odd that a context manager can't cause its managed function to be skipped entirely; while that's not explicitly one of the use cases of "with", it seems like a natural extension. | Alternative to the `match = re.match(); if match: ...` idiom? | [
"",
"python",
"idioms",
""
] |
I see variables defined with this type but I don't know where it comes from, nor what is its purpose. Why not use int or unsigned int? (What about other "similar" types? Void\_t, etc). | From [Wikipedia](http://en.wikipedia.org/wiki/Stdlib.h)
> The `stdlib.h` and `stddef.h` header files define a datatype called `size_t`[1](http://en.wikipedia.org/wiki/Stdlib.h) which is used to represent the size of an object. Library functions that take sizes expect them to be of type `size_t`, and the sizeof operator evaluates to `size_t`.
>
> The actual type of `size_t` is platform-dependent; a common mistake is to assume `size_t` is the same as unsigned int, which can lead to programming errors,[2](http://open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf#page=266) particularly as 64-bit architectures become more prevalent.
From [C99 7.17.1/2](http://open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf#page=266)
> The following types and macros are defined in the standard header `stddef.h`
>
> <snip>
>
> `size_t`
>
> which is the unsigned integer type of the result of the sizeof operator | According to [size\_t description on en.cppreference.com](http://en.cppreference.com/w/cpp/types/size_t) `size_t` is defined in the following headers :
```
std::size_t
...
Defined in header <cstddef>
Defined in header <cstdio>
Defined in header <cstring>
Defined in header <ctime>
Defined in header <cwchar>
``` | Where do I find the definition of size_t, and what is it used for? | [
"",
"c++",
"c",
"variables",
"size-t",
""
] |
Here's some code (full program follows later in the question):
```
template <typename T>
T fizzbuzz(T n) {
T count(0);
#if CONST
const T div(3);
#else
T div(3);
#endif
for (T i(0); i <= n; ++i) {
if (i % div == T(0)) count += i;
}
return count;
}
```
Now, if I call this template function with `int`, then I get a factor of 6 performance difference according to whether I define CONST or not:
```
$ gcc --version
gcc (GCC) 3.4.4 (cygming special, gdc 0.12, using dmd 0.125)
$ make -B wrappedint CPPFLAGS="-O3 -Wall -Werror -DWRAP=0 -DCONST=0" &&
time ./wrappedint
g++ -O3 -Wall -Werror -DWRAP=0 -DCONST=0 wrappedint.cpp -o wrappedi
nt
484573652
real 0m2.543s
user 0m2.059s
sys 0m0.046s
$ make -B wrappedint CPPFLAGS="-O3 -Wall -Werror -DWRAP=0 -DCONST=1" &&
time ./wrappedint
g++ -O3 -Wall -Werror -DWRAP=0 -DCONST=1 wrappedint.cpp -o wrappedi
nt
484573652
real 0m0.655s
user 0m0.327s
sys 0m0.046s
```
Examining the disassembly shows that in the fast (const) case, the modulo has been turned into a multiplication and shift type thing, whereas in the slow (non-const) case it's using `idivl`.
Even worse, if I try to wrap my integer in a class, then the optimisation doesn't happen whether I use const or not. The code always uses `idivl` and runs slow:
```
#include <iostream>
struct WrappedInt {
int v;
explicit WrappedInt(const int &val) : v(val) {}
bool operator<=(const WrappedInt &rhs) const { return v <= rhs.v; }
bool operator==(const WrappedInt &rhs) const { return v == rhs.v; }
WrappedInt &operator++() { ++v; return *this; }
WrappedInt &operator+=(const WrappedInt &rhs) { v += rhs.v; return *this; }
WrappedInt operator%(const WrappedInt &rhs) const
{ return WrappedInt(v%rhs.v); }
};
std::ostream &operator<<(std::ostream &s, WrappedInt w) {
return s << w.v;
}
template <typename T>
T fizzbuzz(T n) {
T count(0);
#if CONST
const T div(3);
#else
T div(3);
#endif
for (T i(0); i <= n; ++i) {
if (i % div == T(0)) count += i;
}
return count;
}
int main() {
#if WRAP
WrappedInt w(123456789);
std::cout << fizzbuzz(w) << "\n";
#else
std::cout << fizzbuzz<int>(123456789) << "\n";
#endif
}
```
My questions are:
1) Is there a simple principle of C++ itself, or gcc's optimisation, which explains why this happens, or is it just a case of "various heuristics run, this is the code you get"?
2) Is there any way to make the compiler realise that my locally-declared and never-referenced const WrappedInt can be treated as a compile-time const value? I want this thing to be a straight replacement for int in templates.
3) Is there a known way of wrapping an int such that the compiler can discard the wrapping when optimising? The goal is that WrappedInt will be a policy-based template. But if a "do-nothing" policy results in essentially arbitrary 6x speed penalties over int, I'm better off special-casing that situation and using int directly. | I'm guessing its just the severely old GCC version you are running. The oldest compiler I have on my machine - gcc-4.1.2, performs the fast way with both the non-const and the wrap versions (and does so at only -O1). | Try combining `const int v` in your WrappedInt class with `const T` in your fizzbuzz function and see if the compiler can optimize that.
By declaring `const int` you've created a special case - a compile time constant. The compiler knows what the value is, and can optimize it more heavily than a value that could possibly change during the run of the program. | Optimisation of division in gcc | [
"",
"c++",
"optimization",
"gcc",
""
] |
Can a select query use different indexes if a change the value of a where condition?
The two following queries use different indexes and the only difference is the value of the
condition and typeenvoi='EXPORT' or and typeenvoi='MAIL'
```
select numenvoi,adrdest,nomdest,etat,nbessais,numappel,description,typeperiode,datedebut,datefin,codeetat,codecontrat,typeenvoi,dateentree,dateemission,typedoc,numdiffusion,nature,commentaire,criselcomp,crisite,criservice,chrono,codelangueetat,piecejointe, sujetmail, textemail
from v_envoiautomate
where etat=0 and typeenvoi='EXPORT'
and nbessais<1
select numenvoi,adrdest,nomdest,etat,nbessais,numappel,description,typeperiode,datedebut,datefin,codeetat,codecontrat,typeenvoi,dateentree,dateemission,typedoc,numdiffusion,nature,commentaire,criselcomp,crisite,criservice,chrono,codelangueetat,piecejointe, sujetmail, textemail
from v_envoiautomate
where etat=0 and typeenvoi='MAIL'
and nbessais<1
```
Can anyone give me an explanation? | Details on indexes are stored as *statistics* in a histogram-type dataset in SQL Server.
Each index is chunked into ranges, and each range contains a summary of the key values within that range, things like:
* range High value
* number of values in the range
* number of distinct values in the range (cardinality)
* number of values equal to the High value
...and so on.
You can view the statistics on a given index with:
```
DBCC SHOW_STATISTICS(<tablename>, <indexname>)
```
Each index has a couple of characteristics like *density*, and ultimately *selectivity*, that tell the query optimiser how unique each value in an index is likely to be, and how efficient this index is at quickly locating records.
As your query has three columns in the where clause, it's likely that any of these columns might have an index that could be useful to the optimiser. It's also likely that the primary key index will be considered, in the event of the selectivity of other indexes not being high enough.
Ultimately, it boils down to the optimiser making a quick judgement call on how many page reads will be necessary to read each your non-clustered indexes + bookmark lookups, with comparisons with the other values, vs. doing a table scan.
The statistics that these judgements are based on can vary wildly too; SQL Server, by default, only samples a small percentage of any significant table's rows, so the selectivity of that index might not be representative of the whole. This is particularly problematic where you have highly non-unique keys in the index.
In this specific case, I'm guessing your `typeenvoi` index is highly non-unique. This being so, the statistics gathered probably indicate to the optimiser that one of the values is rarer than the other, and the likelihood of that index being chosen is increased. | The query optimiser in SQL Server (as in most modern DBMS platforms) uses a methodology known as 'cost based optimisation.' In order to do this it uses statistics about the tables in the database to estimate the amount of I/O needed. The optimiser will consider a number of semantically equivalent query plans that it generates by transforming a basic query plan generated by parsing the statement.
Each plan is evaluated for cost by a heuristic based on the statistics maintained about the tables. The statistics come in various flavours:
* Table and index row counts
* Distributions histograms of the values in individual columns.
If the ocurrence of 'MAIL' vs. 'EXPORT' in the distribution histograms is significantly different the query optimiser can come up with different optimal plans. This is probably what happened. | Same query uses different indexes? | [
"",
"sql",
"sql-server",
"sql-server-2005",
"indexing",
""
] |
One method which I can think of is to reverse the list and then read it.
But this involves changing the list which is bad.
OR I can make a copy of the list and then reverse it, but this uses additional O(n) memory.
Is there any better method which doesn't use extra memory and doesn't modify the list and runs in O(n) time
reverse linked list code is something like this in c#
```
Void Reverse (Node head)
{
Node prev= null;
Node current = head;
Node nextNode = null;
while (current!=null)
{
nextNode = current.Next;
current.Next = prev;
prev=current;
current = nextNode;
}
head = prev;
}
```
Recursive solution is
```
void ReadBackWard (Node n)
{
if (n==null)
return;
else
ReadBackward(n.Next);
Console.WriteLine(n.Data);
}
``` | To use O(n) memory and O(n) performance, create a stack; push everything on as you iterate in the forwards direction, then pop everything off, yielding the results.
To use O(n^2) performance (but O(1) extra memory), read it forwards each time, up the the node before the last one you got to.
Example:
```
IEnumerable<T> Reverse (Node head) {
Stack<Node> nodes = new Stack<Node>();
while(head != null) {
nodes.Push(head);
head = head.Next;
}
while(nodes.Count > 0) {
yield return nodes.Pop().Value;
}
}
``` | One of the hallmarks of a singly-linked list is that it is, in fact, singly linked. It is a one-way street, and there's no way to overcome that unless you turn it into something else (such as a reversed singly-linked list, a stack, a doubly-linked list...). One must be true to the nature of things.
As has been pointed out earlier; if you need to traverse a list both ways; you need to have a doubly-linked list. That is the nature of a doubly linked list, it goes both ways. | How to read a singly linked list backwards? | [
"",
"c#",
"singly-linked-list",
""
] |
Take for example an application which has users, each of which can be in exactly one group. If we want to SELECT the list of groups which have no members, what would be the correct SQL? I keep feeling like I'm just about to grasp the query, and then it disappears again.
Bonus points - given the alternative senario, where it's a many to many pairing, what is the SQL to identify unused groups?
(if you want concrete field names:)
One-To-Many:
```
Table 'users': | user_id | group_id |
Table 'groups': | group_id |
```
Many-To-Many:
```
Table 'users': | user_id |
Table 'groups': | group_id |
Table 'user-group': | user_id | group_id |
``` | Groups that have no members (for the many-many pairing):
```
SELECT *
FROM groups g
WHERE NOT EXISTS
(
SELECT 1
FROM users_groups ug
WHERE g.groupid = ug.groupid
);
```
This Sql will also work in your "first" example as you can substitute "users" for "users\_groups" in the sub-query =)
As far as performance is concerned, I know that this query can be quite performant on Sql Server, but I'm not so sure how well MySql likes it.. | For the first one, try this:
```
SELECT * FROM groups
LEFT JOIN users ON (groups.group_id=users.group_id)
WHERE users.user_id IS NULL;
```
For the second one, try this:
```
SELECT * FROM groups
LEFT JOIN user-group ON (groups.group_id=user-group.group_id)
WHERE user-group.user_id IS NULL;
``` | Select all items in a table that do not appear in a foreign key of another table | [
"",
"sql",
"mysql",
""
] |
**Problem:** to run one.py from a server.
**Error**
When I try to do it in Mac, I get errors:
```
$python http://cs.edu.com/u/user/TEST/one.py ~
/Library/Frameworks/Python.framework/Versions/2.5/Resources/Python.app/Contents/MacOS/Python: can't open file 'http://cs.edu.com/u/user/TEST/one.py': [Errno 2] No such file or directory
```
one.py is like:
```
print 1
```
When I do it in Ubuntu, I get "file is not found".
**Question:** How can I run Python code from a server? | So far as I know, the standard Python shell doesn't know how to execute remote scripts. Try using `curl` or `wget` to retrieve the script and run it from the local copy.
```
$ wget http://cs.edu.com/u/user/TEST/one.py
$ python one.py
```
UPDATE: Based on the [question](https://stackoverflow.com/questions/1122609/javascript-for-a-form-on-the-server-side) referenced in the comment to [this answer](https://stackoverflow.com/questions/1125637/running-python-code-from-a-server/1125670#1125670), you need to execute `one.py` based on incoming HTTP requests from end users. The simplest solution is probably [CGI](http://www.garshol.priv.no/download/text/http-tut.html), but depending on what else you need to do, a more robust solution might involve a [framework](http://wiki.python.org/moin/WebFrameworks) of some sort. They each have there strengths and weaknesses, so you should probably consider your requirements carefully before jumping in. | You can't do this. If you have SSH access to the server you can then run the python script located on the server using your SSH connection. If you want to write websites in python google python web frameworks for examples of how to set up and run websites with Python. | Running Python code from a server? | [
"",
"python",
""
] |
I have a multi-line text box on a Winforms app that I want to be able to click on in some states of the app without changing the Text selection.
I still want to subscribe to the MouseDown (or Click) event, I just don't want the text selection to react to it.
I was hoping for a Handled or Cancel property on the MouseEventArgs, but sadly, no.
I could listen to the selection changed event and try to reset it when required, but this feels a little hack-like as I would have to remember current selection before the selection change event. Does anyone have any better suggestions than that? | You could create your own Textbox inheriting from System.Windows.Forms.Textbox and then override the WndProc.
The WndProc is the initial method which receives messages about everything from the operating system, power messages, input, etc. The name of the method is a throwback to the Win32 (and Win16) days where one of the two main functions you would implement was the "WndProc" or Windows Procedure.
By doing so, you can now intercept the windows messages for the mouse (or any other message) prior to the events being dispatched to the base implementation.
In the below example, we do not pass on any Left button down, up or double click to the base control to process.
```
public partial class MyTextBox : TextBox
{
int WM_LBUTTONDOWN = 0x0201; //513
int WM_LBUTTONUP = 0x0202; //514
int WM_LBUTTONDBLCLK = 0x0203; //515
public MyTextBox()
{
InitializeComponent();
}
protected override void WndProc(ref Message m)
{
if (m.Msg == WM_LBUTTONDOWN ||
m.Msg == WM_LBUTTONUP ||
m.Msg == WM_LBUTTONDBLCLK // && Your State To Check
)
{
//Dont dispatch message
return;
}
//Dispatch as usual
base.WndProc(ref m);
}
}
```
Only thing left to do is adding checking for your state to determine when to pass on the messages or not.
You can find a list of the Windows messages to process [here](http://www.pcreview.co.uk/forums/thread-1317840.php). | How about handling the `Enter` event and setting the focus to a different control in this event? Still pretty "hack-like" though, just with less code. | C# Winforms Suppress a Mouse Click event on a Text Box | [
"",
"c#",
"winforms",
"events",
""
] |
I have a raw buffer with it i need to make 3 others, the head which is always the first 8 bytes, body which is always from byte 8 to ? then foot which is from ? to the end of he file.
How do i make a buffer from an already existing buffer so i can fill in body and foot. also how do i create head to use the first 16 bytes. I am assuming i am not using a ref or pointer. | You can use Array.Copy() to copy elements from one array to another. You can specify the start and end positions for the source and destination.
You may also want to check out [Buffer.BlockCopy()](http://msdn.microsoft.com/en-us/library/system.buffer.blockcopy.aspx). | You can use a BinaryReader from a MemoryStream
```
System.IO.MemoryStream stm = new System.IO.MemoryStream( buf, 0, buf.Length );
System.IO.BinaryReader rdr = new System.IO.BinaryReader( stm );
int bodyLen = xxx;
byte[] head = rdr.ReadBytes(8)
byte[] body = rdr.ReadBytes(bodyLen );
byte[] foot = rdr.ReadBytes(buf.Length-bodylen-8);
``` | byte[] buffer or ref/pointer? in C# | [
"",
"c#",
"binary",
"arrays",
""
] |
My program is now still running to import data from a log file into a remote SQL Server Database. The log file is about 80MB in size and contains about 470000 lines, with about 25000 lines of data. My program can import only 300 rows/second, which is really bad. :(
```
public static int ImportData(string strPath)
{
//NameValueCollection collection = ConfigurationManager.AppSettings;
using (TextReader sr = new StreamReader(strPath))
{
sr.ReadLine(); //ignore three first lines of log file
sr.ReadLine();
sr.ReadLine();
string strLine;
var cn = new SqlConnection(ConnectionString);
cn.Open();
while ((strLine = sr.ReadLine()) != null)
{
{
if (strLine.Trim() != "") //if not a blank line, then import into database
{
InsertData(strLine, cn);
_count++;
}
}
}
cn.Close();
sr.Close();
return _count;
}
}
```
InsertData is just a normal insert method using ADO.NET. It uses a parsing method:
```
public Data(string strLine)
{
string[] list = strLine.Split(new[] {'\t'});
try
{
Senttime = DateTime.Parse(list[0] + " " + list[1]);
}
catch (Exception)
{
}
Clientip = list[2];
Clienthostname = list[3];
Partnername = list[4];
Serverhostname = list[5];
Serverip = list[6];
Recipientaddress = list[7];
Eventid = Convert.ToInt16(list[8]);
Msgid = list[9];
Priority = Convert.ToInt16(list[10]);
Recipientreportstatus = Convert.ToByte(list[11]);
Totalbytes = Convert.ToInt32(list[12]);
Numberrecipient = Convert.ToInt16(list[13]);
DateTime temp;
if (DateTime.TryParse(list[14], out temp))
{
OriginationTime = temp;
}
else
{
OriginationTime = null;
}
Encryption = list[15];
ServiceVersion = list[16];
LinkedMsgid = list[17];
MessageSubject = list[18];
SenderAddress = list[19];
}
```
InsertData method:
```
private static void InsertData(string strLine, SqlConnection cn)
{
var dt = new Data(strLine); //parse the log line into proper fields
const string cnnStr =
"INSERT INTO LOGDATA ([SentTime]," + "[client-ip]," +
"[Client-hostname]," + "[Partner-Name]," + "[Server-hostname]," +
"[server-IP]," + "[Recipient-Address]," + "[Event-ID]," + "[MSGID]," +
"[Priority]," + "[Recipient-Report-Status]," + "[total-bytes]," +
"[Number-Recipients]," + "[Origination-Time]," + "[Encryption]," +
"[service-Version]," + "[Linked-MSGID]," + "[Message-Subject]," +
"[Sender-Address]) " + " VALUES ( " + "@Senttime," + "@Clientip," +
"@Clienthostname," + "@Partnername," + "@Serverhostname," + "@Serverip," +
"@Recipientaddress," + "@Eventid," + "@Msgid," + "@Priority," +
"@Recipientreportstatus," + "@Totalbytes," + "@Numberrecipient," +
"@OriginationTime," + "@Encryption," + "@ServiceVersion," +
"@LinkedMsgid," + "@MessageSubject," + "@SenderAddress)";
var cmd = new SqlCommand(cnnStr, cn) {CommandType = CommandType.Text};
cmd.Parameters.AddWithValue("@Senttime", dt.Senttime);
cmd.Parameters.AddWithValue("@Clientip", dt.Clientip);
cmd.Parameters.AddWithValue("@Clienthostname", dt.Clienthostname);
cmd.Parameters.AddWithValue("@Partnername", dt.Partnername);
cmd.Parameters.AddWithValue("@Serverhostname", dt.Serverhostname);
cmd.Parameters.AddWithValue("@Serverip", dt.Serverip);
cmd.Parameters.AddWithValue("@Recipientaddress", dt.Recipientaddress);
cmd.Parameters.AddWithValue("@Eventid", dt.Eventid);
cmd.Parameters.AddWithValue("@Msgid", dt.Msgid);
cmd.Parameters.AddWithValue("@Priority", dt.Priority);
cmd.Parameters.AddWithValue("@Recipientreportstatus", dt.Recipientreportstatus);
cmd.Parameters.AddWithValue("@Totalbytes", dt.Totalbytes);
cmd.Parameters.AddWithValue("@Numberrecipient", dt.Numberrecipient);
if (dt.OriginationTime != null)
cmd.Parameters.AddWithValue("@OriginationTime", dt.OriginationTime);
else
cmd.Parameters.AddWithValue("@OriginationTime", DBNull.Value);
//if OriginationTime was null, then insert with null value to this column
cmd.Parameters.AddWithValue("@Encryption", dt.Encryption);
cmd.Parameters.AddWithValue("@ServiceVersion", dt.ServiceVersion);
cmd.Parameters.AddWithValue("@LinkedMsgid", dt.LinkedMsgid);
cmd.Parameters.AddWithValue("@MessageSubject", dt.MessageSubject);
cmd.Parameters.AddWithValue("@SenderAddress", dt.SenderAddress);
cmd.ExecuteNonQuery();
}
```
How can my program run faster?
Thank you so much! | Use [SqlBulkCopy](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx).
Edit: I created a minimal implementation of `IDataReader` and created a `Batch` type so that I could insert arbitrary in-memory data using `SqlBulkCopy`. Here is the important bit:
```
IDataReader dr = batch.GetDataReader();
using (SqlTransaction tx = _connection.BeginTransaction())
{
try
{
using (SqlBulkCopy sqlBulkCopy =
new SqlBulkCopy(_connection, SqlBulkCopyOptions.Default, tx))
{
sqlBulkCopy.DestinationTableName = TableName;
SetColumnMappings(sqlBulkCopy.ColumnMappings);
sqlBulkCopy.WriteToServer(dr);
tx.Commit();
}
}
catch
{
tx.Rollback();
throw;
}
}
```
The rest of the implementation is left as an exercise for the reader :)
Hint: the only bits of `IDataReader` you need to implement are `Read`, `GetValue` and `FieldCount`. | Hmmm, let's break this down a little bit.
In pseudocode what you did is the ff:
1. Open the file
* Open a connection
* For every line that has data:
* Parse the string
* Save the data in SQL Server
* Close the connection
* Close the file
Now the fundamental problems in doing it this way are:
* You are keeping a SQL connection open while waiting for your line parsing (pretty susceptible to timeouts and stuff)
* You *might* be saving the data line by line, each in its own transaction. We won't know until you show us what the `InsertData` method is doing
* Consequently you are keeping the file open while waiting for SQL to finish inserting
The optimal way of doing this is to parse the file as a whole, and then insert them in bulk. You can do this with [SqlBulkCopy](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopy.aspx) (as suggested by Matt Howells), or with SQL Server Integration Services.
If you want to stick with ADO.NET, you can pool together your INSERT statements and then pass them off into one large SQLCommand, instead of doing it this way e.g., setting up one SQLCommand object per insert statement. | import from text file to SQL Server Database, is ADO.NET too slow? | [
"",
"c#",
"sql-server",
"ado.net",
""
] |
I am just a beginner in ASP.NET. My question is simple, I wanna add list items dynamically from the code behind file and I want each item to have a text and couple of images as hyperlinks. The HTML sample should be like,
```
<ul>
<li>do foo <a href="#"><img src="some_image.png" /></a></li>
<li>do bar <a href="#"><img src="some_image.png" /></a></li>
...
</ul>
```
The number of items is dependent on the collection retrieved by the code behind file.
P.S. my code behind file is written in C# | The [`Repeater`](http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.repeater.aspx) control is the simplest way to create a customized bulleted list, plus it gives you complete control over the HTML you generate. To use it, set up a template like this:
```
<ul>
<asp:Repeater runat="server" ID="ListRepeater">
<ItemTemplate>
<li>do foo <a href='#'><img src='<%# Eval("ImageSource") %>' /></a></li>
</ItemTemplate>
</asp:Repeater>
</ul>
```
Then in your code-behind (or declaratively in your markup, depending on your preference), set the repeater's data source and bind it:
```
void Page_Load(object sender, EventArgs e) {
// Some method you've defined to get your images
List<string> imageList = GetImages();
ListRepeater.DataSource = imageList;
ListRepeater.DataBind();
}
```
ASP.NET renders the template once for each item in your data source.
The `Repeater` control has more features than what I've shown here, but this should get you started. Good luck!
---
**Edit**: a year after writing this answer, I still think repeaters are the best option among server controls, but more and more I prefer `foreach` statements right in my .aspx templates:
```
<ul>
<% foreach(Image image in this.Images) { %>
<li>do foo <a href='#'><img src='<%= image.Source %>' /></a></li>
<% } %>
</ul>
``` | Just use the Repeater control. Simply and easy. :) | Customized bulleted list items in ASP.NET | [
"",
"c#",
"asp.net",
"html",
""
] |
I want to read a book that systematically introduces dom with live examples.
Any recommendation? | [Dom Scripting](http://domscripting.com/book/) was an interesting book, taught me a lot about JavaScript. | its going to be hard to find a book that specifically focuses on the dom (maybe an intense xml book). You want the dom and the dom features with javascript I assume. [check out oreilly's more advanced javascript book.](http://oreilly.com/catalog/9780596101992/) I actually have the book right here, there's a good 34 pages on the dom with examples; its a complete reference for all of javascript, so about 1000 pages in all. | Dom book which introduces DOM as much as possible? | [
"",
"javascript",
"dom",
""
] |
How do I serve a dynamically generated image in Django?
I have an html tag
```
<html>
...
<img src="images/dynamic_chart.png" />
...
</html>
```
linked up to this request handler, which creates an in-memory image
```
def chart(request):
img = Image.new("RGB", (300,300), "#FFFFFF")
data = [(i,randint(100,200)) for i in range(0,300,10)]
draw = ImageDraw.Draw(img)
draw.polygon(data, fill="#000000")
# now what?
return HttpResponse(output)
```
I also plan to change the requests to AJAX, and add some sort of caching mechanism, but my understanding is that wouldn't affect this part of the solution. | I assume you're using PIL (Python Imaging Library). You need to replace your last line with (for example, if you want to serve a PNG image):
```
response = HttpResponse(mimetype="image/png")
img.save(response, "PNG")
return response
```
See [here](http://effbot.org/zone/django-pil.htm) for more information. | I'm relatively new to Django myself. I haven't been able to find anything in Django itself, but I have stumbled upon a project on Google Code that may be of some help to you:
[django-dynamic-media-serve](http://code.google.com/p/django-dynamic-media-serve/) | Serve a dynamically generated image with Django | [
"",
"python",
"ajax",
"django",
"image",
""
] |
I've got a conversion operator that returns a const pointer, and I need to const\_cast it. However, that doesn't work, at least under MSVC8. The following code reproduces my problem:
```
class MyClass {
public:
operator const int* () {
return 0;
}
};
int main() {
MyClass obj;
int* myPtr;
// compiles
const int* myConstPtr = obj;
// compiles
myPtr = const_cast<int*>(myConstPtr);
// doesn't compile (C2440: 'const_cast' : cannot convert from 'MyClass' to 'int *')
myPtr = const_cast<int*>(obj);
}
```
Why is that? It seems counter-intuitive. Thanks! | To make it work you have to do :
```
myPtr = const_cast<int*>(static_cast<const int*>(obj));
```
When you const\_cast directly, the compiler look for the cast operator to int\*. | `const_cast` can only change the constness of a type. If you want to call the implicit operator you have you need a `static_cast` and then a `const_cast`. While it's annoying it makes sure you are explicit in what you are doing.
```
myPtr = const_cast<int*>(static_cast<const int*>(obj));
```
You can also use the old school c-style cast operator
```
myPtr = (int*)(const int*)obj;
```
But this is highly discouraged for several reasons:
* It isn't grepable
* You can very easily do more than you intended. Most of the time you don't want to mess with `const_cast` type operations and using `static_cast` enforces this. In fact you very rarely want a `const_cast`. If you find yourself doing it regularly you have some design mistakes.
Edit: I was slightly off, I fixed it now. It makes the c-style cast a little uglier | Why can't I const_cast the return of the conversion operator? | [
"",
"c++",
"const-cast",
""
] |
I have a winforms datagridview that seems to always have at least one row selected all the time. I'm not interested in being able to select the rows at all really, I just need the user to be able to select the checkbox in column 1.
Any ideas why there is always at least 1 row selected?
How can i prevent this?
Will it affect the ability to select the checkbox in column1?
Below are my Datagridview settings:
```
this.dataGridView1.AllowUserToAddRows = false;
this.dataGridView1.DefaultCellStyle.WrapMode = DataGridViewTriState.True;
this.dataGridView1.DefaultCellStyle.ForeColor = Color.Black;
this.dataGridView1.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
this.dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.AllCells;
this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
this.dataGridView1.MultiSelect = false;
this.dataGridView1.RowHeadersVisible = false;
this.dataGridView1.RowsDefaultCellStyle.BackColor = Color.WhiteSmoke;
this.dataGridView1.AlternatingRowsDefaultCellStyle.BackColor = Color.LightGray;
this.dataGridView1.ColumnCount = 0;
colSelect = new DataGridViewCheckBoxColumn();
colSelect.HeaderText = "Select Message";
colSelect.Width = 90;
this.dataGridView1.Columns.Insert(0, colSelect);
this.dataGridView1.Columns[0].DataPropertyName = "msgSelect";
``` | You should use [DataGridView.ClearSelection()](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridview.clearselection.aspx) to remove any selection(s) after you have populated your DataGridView.
Also you can make specific columns read only allow which would allow to restrict editing to your checkbox column only. See [DataGridViewColumn.ReadOnly Property](http://msdn.microsoft.com/en-us/library/system.windows.forms.datagridviewcolumn.readonly.aspx) | Goober, I encountered a similar problem, where I needed user to select rows using checkboxes. The first row is always selected by default after the gridview is populated irrespective of the gridview settings. To make sure the first row is not selected, everytime the gridview is populated, do a ClearSelection():
```
this.dgridvw.DataSource = this.MyTable;
this.dgridvw.ClearSelection();
```
ClearSelection() clears all the selected rows. | C# WinForms DataGridView - Constant Row Selected! | [
"",
"c#",
".net",
"winforms",
"datagridview",
""
] |
Linq in general, has extensions methods(at IEnumerable) like Where, Select, OrderBy. But use another methods like string.StartsWith.
Where can I find a list with all methods supported, for Linq to SQL and Linq to Entities? | Here's a list of all supported methods for LINQ to entities:
[Supported and Unsupported LINQ Methods (LINQ to Entities)](https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/ef/language-reference/supported-and-unsupported-linq-methods-linq-to-entities) | For LINQ to SQL:
[Data Types and Functions (LINQ to SQL)](http://msdn.microsoft.com/en-us/library/bb386970.aspx) | Linq Methods | [
"",
"c#",
"linq",
""
] |
I have a table `users` which has a primary key `userid` and a datetime column `pay_date`.
I've also got a table `user_actions` which references `users` via the column `userid`, and a datetime column `action_date`.
I want to join the two tables together, fetching only the earliest action from the `user_actions` table which has an `action_date` later than or equal to `pay_date`.
I'm trying things like:
```
select users.userid from users
left join user_actions on user_actions.userid = users.userid
where user_actions.action_date >= users.pay_date
order by user_actions.pay_date
```
But obviously that returns me multiple rows per user (one for every user action occurring on or after `pay_date`). Any idea where to go from here?
Apologies for what probably seems like a simple question, I'm fairly new to t-sql. | If you have a `PRIMARY KEY` on `user_actions`:
```
SELECT u.*, ua.*
FROM users u
LEFT JOIN
user_actions ua
ON user_actions.id =
(
SELECT TOP 1 id
FROM user_actions uai
WHERE uai.userid = u.userid
AND uai.action_date >= u.pay_date
ORDER BY
uai.action_date
)
```
If you don't:
```
WITH j AS
(
SELECT u.*, ua.*, ROW_NUMBER() OVER (PARTITION BY ua.userid ORDER BY ua.action_date) AS rn, ua.action_date
FROM users u
LEFT JOIN
user_actions ua
ON ua.userid = u.userid
AND ua.action_date >= u.pay_date
)
SELECT *
FROM j
WHERE rn = 1 or action_date is null
```
**Update:**
`CROSS APPLY` proposed by `@AlexKuznetsov` is more elegant and efficient. | CROSS APPLY is your friend:
```
select users.*, t.* from users
CROSS APPLY(SELECT TOP 1 * FROM user_actions WHERE user_actions.userid = users.userid
AND user_actions.action_date >= users.pay_date
order by user_actions.pay_date) AS t
``` | Joining to a table with multiple rows for the join item | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I have a list of two-item lists and need to search for things in it.
If the list is:
```
list = [['a','b'], ['a','c'], ['b','d']]
```
I can search for a pair easily by doing
```
['a','b'] in list
```
Now, is there a way to see if I have a pair in which a string is present in just the second position? I can do this:
```
for i in range (0, len(list)):
if list[i][1]==search:
found=1
```
But is there a (better) way without the `for` loop? I don't need to know `i` or keep the loop going after it's found. | You're always going to have a loop - someone might come along with a clever one-liner that hides the loop within a call to `map()` or similar, but it's always going to be there.
My preference would always be to have clean and simple code, unless performance is a major factor.
Here's perhaps a more Pythonic version of your code:
```
data = [['a','b'], ['a','c'], ['b','d']]
search = 'c'
for sublist in data:
if sublist[1] == search:
print "Found it!", sublist
break
# Prints: Found it! ['a', 'c']
```
It breaks out of the loop as soon as it finds a match.
(You have a typo, by the way, in `['b''d']`.) | Here's the Pythonic way to do it:
```
data = [['a','b'], ['a','c'], ['b','d']]
search = 'c'
any(e[1] == search for e in data)
```
Or... well, I'm not going to claim this is the "one true Pythonic way" to do it because at some point it becomes a little subjective what is Pythonic and what isn't, or which method is more Pythonic than another. But using `any()` is definitely more typical Python style than a `for` loop as in e.g. [RichieHindle's answer](https://stackoverflow.com/a/1156114/56541),
Of course there is a hidden loop in the implementation of `any`, although it breaks out of the loop as soon as it finds a match.
---
Since I was bored I made a timing script to compare performance of the different suggestions, modifying some of them as necessary to make the API the same. Now, we should bear in mind that fastest is not always best, and being fast is definitely not the same thing as being Pythonic. That being said, the results are... strange. Apparently `for` loops are very fast, which is not what I expected, so I'd take these with a grain of salt without understanding why they've come out the way they do.
Anyway, when I used the list defined in the question with three sublists of two elements each, from fastest to slowest I get these results:
1. [RichieHindle's answer](https://stackoverflow.com/a/1156114/56541) with the `for` loop, clocking in at 0.22 μs
2. [Terence Honles' first suggestion](https://stackoverflow.com/a/1158136/56541) which creates a list, at 0.36 μs
3. [Pierre-Luc Bedard's answer (last code block)](https://stackoverflow.com/a/18412156/56541), at 0.43 μs
4. Essentially tied between [Markus's answer](https://stackoverflow.com/a/1156582/56541) and the `for` loop from [the original question](https://stackoverflow.com/q/1156087/56541), at 0.48 μs
5. [Coady's answer](https://stackoverflow.com/a/1157153/56541) using `operator.itemgetter()`, at 0.53 μs
6. Close enough to count as a tie between [Alex Martelli's answer](https://stackoverflow.com/a/1156628/56541) with `ifilter()` and [Anon's answer](https://stackoverflow.com/a/1156128/56541), at 0.67 μs (Alex's is consistently about half a microsecond faster)
7. Another close-enough tie between [jojo's answer](https://stackoverflow.com/a/13588121/56541), mine, [Brandon E Taylor's](https://stackoverflow.com/a/1156145/56541) (which is identical to mine), and [Terence Honles' second suggestion](https://stackoverflow.com/a/1158136/56541) using `any()`, all coming in at 0.81-0.82 μs
8. And then [user27221's answer](https://stackoverflow.com/a/30449870/56541) using nested list comprehensions, at 0.95 μs
Obviously the actual timings are not meaningful on anyone else's hardware, but the differences between them should give some idea of how close the different methods are.
When I use a longer list, things change a bit. I started with the list in the question, with three sublists, and appended another 197 sublists, for a total of 200 sublists each of length two. Using this longer list, here are the results:
1. [RichieHindle's answer](https://stackoverflow.com/a/1156114/56541), at the same 0.22 μs as with the shorter list
2. [Coady's answer](https://stackoverflow.com/a/1157153/56541) using `operator.itemgetter()`, again at 0.53 μs
3. [Terence Honles' first suggestion](https://stackoverflow.com/a/1158136/56541) which creates a list, at 0.36 μs
4. Another virtual tie between [Alex Martelli's answer](https://stackoverflow.com/a/1156628/56541) with `ifilter()` and [Anon's answer](https://stackoverflow.com/a/1156128/56541), at 0.67 μs
5. Again a close-enough tie between my answer, [Brandon E Taylor's](https://stackoverflow.com/a/1156145/56541) identical method, and [Terence Honles' second suggestion](https://stackoverflow.com/a/1158136/56541) using `any()`, all coming in at 0.81-0.82 μs
Those are the ones that keep their original timing when the list is extended. The rest, which don't, are
6. The `for` loop from [the original question](https://stackoverflow.com/q/1156087/56541), at 1.24 μs
7. [Terence Honles' first suggestion](https://stackoverflow.com/a/1158136/56541) which creates a list, at 7.49 μs
8. [Pierre-Luc Bedard's answer (last code block)](https://stackoverflow.com/a/18412156/56541), at 8.12 μs
9. [Markus's answer](https://stackoverflow.com/a/1156582/56541), at 10.27 μs
10. [jojo's answer](https://stackoverflow.com/a/13588121/56541), at 19.87 μs
11. And finally [user27221's answer](https://stackoverflow.com/a/30449870/56541) using nested list comprehensions, at 60.59 μs | Search in lists of lists by given index | [
"",
"python",
"list",
""
] |
In C#, suppose you have an object (say, `myObject`) that is an instance of class `MyClass`.
Using `myObject` only, how would you access a static member of `MyClass`?
```
class MyClass
{
public static int i = 123 ;
}
class MainClass
{
public static void Main()
{
MyClass myObject = new MyClass() ;
myObject.GetType().i = 456 ; // something like this is desired,
// but erroneous
}
}
``` | You'd have to use reflection:
```
Type type = myObject.GetType();
FieldInfo field = type.GetField("i", BindingFlags.Public |
BindingFlags.Static);
int value = (int) field.GetValue(null);
```
I'd generally try to avoid doing this though... it's very brittle. Here's an alternative using normal inheritance:
```
public class MyClass
{
public virtual int Value { get { return 10; } }
}
public class MyOtherClass : MyClass
{
public override int Value { get { return 20; } }
}
```
etc.
Then you can just use `myObject.Value` to get the right value. | If you have control of MyClass and need to do this often, I'd add a member property that gives you access.
```
class MyClass
{
private static int _i = 123;
public virtual int I => _i;
}
``` | C# -- how does one access a class' static member, given an instance of that class? | [
"",
"c#",
"static",
"gettype",
""
] |
While coding python I'm using only 2 spaces to indent, sure [PEP-8](http://www.python.org/dev/peps/pep-0008/) really recommend to have 4 spaces, but historically for me it's unusual.
So, can anyone convince me to use 4 spaces instead of 2? What pros and cons?
P.S. And finally, what's easy way to convert all existing codebase from 2 spaces to 4 spaces?
---
P.P.S. PEP-8 Also srictly recommend not using tabs for indention. [read here](https://stackoverflow.com/questions/120926/why-does-python-pep-8-strongly-recommend-spaces-over-tabs-for-indentation)
---
So, to summarize:
Pros:
* Have more space to arrange when wraping string more than 80 lines long.
* Can copy code from snippets and it just works.
Cons:
* With deeper level of nested statements you have less space for actual code.
Thanks. | Everyone else uses 4 spaces. That is the only reason to use 4 spaces that I've come across and accepted. In my heart, I still want to use tabs (1 indent character per indent, makes sense, no? Separate indent from other whitespace. I don't care that tabs can be *displayed* as different widths, that makes no syntactic difference. The worst that can happen is that some of the comments don't line up. The horror!) but I've accepted that since the python community as a whole uses 4 spaces, I use 4 spaces. This way, I can assemble code from snippets others have written, and it all works. | I like the fact that four space characters nicely indents the inner code of a function, because def + one space makes four characters.
```
def·foo():
····pass
``` | Python: using 4 spaces for indentation. Why? | [
"",
"python",
"indentation",
"conventions",
"pep8",
""
] |
Why shouldn't C# (or .NET) allow us to put a static/shared method inside an interface?
Seemingly duplicate from [Why we can not have Shared(static) function/methods in an interface/abstract class?](https://stackoverflow.com/questions/330318/why-we-can-not-have-sharedstatic-function-methods-in-an-interface-abstract-clas), but my idea is a bit different,;I just want to put a helper for my plugins(interface)
Shouldn't C# at least allow this idea?
```
namespace MycComponent
{
public interface ITaskPlugin : ITaskInfo
{
string Description { get; }
string MenuTree { get; }
string MenuCaption { get; }
void ShowTask(Form parentForm);
void ShowTask(Form parentForm, Dictionary<string, object> pkColumns);
ShowTaskNewDelegate ShowTaskNew { set; get; }
ShowTaskOpenDelegate ShowTaskOpen { set; get; }
// would not compile with this:
public static Dictionary<string, ITaskPlugin> GetPlugins(string directory)
{
var l = new Dictionary<string, ITaskPlugin>();
foreach (string file in Directory.GetFiles(directory))
{
var fileInfo = new FileInfo(file);
if (fileInfo.Extension.Equals(".dll"))
{
Assembly asm = Assembly.LoadFile(file);
foreach (Type asmType in asm.GetTypes())
{
if (asmType.GetInterface("MycComponent.ITaskPlugin") != null)
{
var plugIn = (ITaskPlugin)Activator.CreateInstance(asmType);
l.Add(plugIn.TaskName, plugIn);
}
}
}
}
return l;
} // GetPlugins. would not compile inside an interface
}
/* because of the error above, I am compelled to
put the helper method in a new class. a bit overkill when the method should
be closely coupled to what it is implementing */
public static class ITaskPluginHelper
{
public static Dictionary<string, ITaskPlugin> GetPlugins(string directory)
{
var l = new Dictionary<string, ITaskPlugin>();
foreach (string file in Directory.GetFiles(directory))
{
var fileInfo = new FileInfo(file);
if (fileInfo.Extension.Equals(".dll"))
{
Assembly asm = Assembly.LoadFile(file);
foreach (Type asmType in asm.GetTypes())
{
if (asmType.GetInterface("MycComponent.ITaskPlugin") != null)
{
var plugIn = (ITaskPlugin)Activator.CreateInstance(asmType);
l.Add(plugIn.TaskName, plugIn);
}
}
}
}
return l;
} // GetPlugins
} // ITaskPluginHelper
}
``` | The idea of an interface is to represent a contract, not implementation.
I can't remember offhand whether IL actually *does* allow static methods with implementations in interfaces - I've a sneaky suspicion that it does - but that muddies the concept somewhat.
I can see your point - it's sometimes useful to know what helper methods are available which are connected with an interface (and extension methods are particularly relevant there) but I would personally want to put those in a separate class anyway, just to keep the mental model clean. | I've run into this several times and did some research. The sad part is, IL actually supports this. I got so frustrated with this I wrote a blog post about it. You can find it [here](http://jvdveen.blogspot.com/2008/11/plugins-and-abstract-static-methods-in.html). | Why shouldn't C# (or .NET) allow us to put a static/shared method inside an interface? | [
"",
"c#",
".net",
"interface",
"helper",
"software-design",
""
] |
I am trying to show by example that the prefix increment is more efficient than the postfix increment.
In theory this makes sense: i++ needs to be able to return the unincremented original value and therefore store it, whereas ++i can return the incremented value without storing the previous value.
But is there a good example to show this in practice?
I tried the following code:
```
int array[100];
int main()
{
for(int i = 0; i < sizeof(array)/sizeof(*array); i++)
array[i] = 1;
}
```
I compiled it using gcc 4.4.0 like this:
```
gcc -Wa,-adhls -O0 myfile.cpp
```
I did this again, with the postfix increment changed to a prefix increment:
```
for(int i = 0; i < sizeof(array)/sizeof(*array); ++i)
```
The result is identical assembly code in both cases.
This was somewhat unexpected. It seemed like that by turning off optimizations (with -O0) I should see a difference to show the concept. What am I missing? Is there a better example to show this? | In the *general* case, the post increment will result in a copy where a pre-increment will not. Of course this will be optimized away in a large number of cases and in the cases where it isn't the copy operation will be negligible (ie., for built in types).
Here's a small example that show the potential inefficiency of post-increment.
```
#include <stdio.h>
class foo
{
public:
int x;
foo() : x(0) {
printf( "construct foo()\n");
};
foo( foo const& other) {
printf( "copy foo()\n");
x = other.x;
};
foo& operator=( foo const& rhs) {
printf( "assign foo()\n");
x = rhs.x;
return *this;
};
foo& operator++() {
printf( "preincrement foo\n");
++x;
return *this;
};
foo operator++( int) {
printf( "postincrement foo\n");
foo temp( *this);
++x;
return temp;
};
};
int main()
{
foo bar;
printf( "\n" "preinc example: \n");
++bar;
printf( "\n" "postinc example: \n");
bar++;
}
```
The results from an optimized build (which actually removes a second copy operation in the post-increment case due to RVO):
```
construct foo()
preinc example:
preincrement foo
postinc example:
postincrement foo
copy foo()
```
In general, if you don't need the semantics of the post-increment, why take the chance that an unnecessary copy will occur?
Of course, it's good to keep in mind that a custom operator++() - either the pre or post variant - is free to return whatever it wants (or even do whatever it wants), and I'd imagine that there are quite a few that don't follow the usual rules. Occasionally I've come across implementations that return "`void`", which makes the usual semantic difference go away. | You won't see any difference with integers. You need to use iterators or something where post and prefix really do something different. And you need to turn all optimisations **on**, not off! | i++ less efficient than ++i, how to show this? | [
"",
"c++",
"optimization",
"prefix",
"postfix-operator",
""
] |
What is the simplest way to write a timer in C/C++?
Hi,
What is the simplest way to write a timer, say in C/C++? Previously I used a for loop and a do-while loop. I used the for loop as a counter and the do-while loop as a comparison for "end of time". The program worked as I wanted it to, but consumed too much system resources.
I'm looking for the simplest way to write a timer.
Thank you!
EDIT:
The program works on a set of servers both Linux and Windows, so it's a multiplatform environment. I dont want to use the unsleep or sleep function as I'm trying to write everything from scratch.
The nature of the program: The program counts power time and battery time on systems.
EDIT2:
OK, it seems that this caused some confusion so I'm going to try to explain what I have done so far. I've created a program that runs in the background and powers off the system if it's idle for a certain amount of time, it also checks for the battery life on a specific system and goes to stand by mode if the system has been running on battery for a while. I input the time manually so I need a timer. I want to write it from scratch as it's a part of a personal project I've been working on. | Your best bet is to use an operating system primitive that suspends the program for a given amount of time (like Sleep() in Windows). The environment where the program will run will most likely have some mechanism for doing this or similar thing. That's the only way to avoid polling and consuming CPU time. | If you just want your program to wait a certain amount of time, you can use:
* Sleep (in Windows)
* usleep (in Unix)
* boost::this\_thread::sleep (everywhere)
If you wish to process or display the time going up until elapsed, your approach of using a while() loop is fine, but you should add a small sleep (20ms, for example, but ultimately that depends on the precision you require) in the while loop, as not to hog the CPU. | What is the simplest way to write a timer in C/C++? | [
"",
"c++",
"c",
""
] |
I just start learning to write web services yesterday, kinda fascinating. I created an XML web service, i most program on my Linux box, I want to use the java language or some other language to access this web service. Can you direct me to any tutorial that show how to access the .net web services from another programming language. | Web services should be language/platform independent. That is one of the pillars. So you should access web service written in .net like any other web service. The implementation details shouldn't be visible for customer of the web service. | For an example, you can try [Jquery.get()](http://docs.jquery.com/Ajax/jQuery.get#urldatacallbacktype):
> *Load a remote page using an HTTP GET request.*
>
> This is an easy way to send a simple GET request to a server without having to use the more complex $.ajax function. It allows a single callback function to be specified that will be executed when the request is complete (and only if the response has a successful response code). If you need to have both error and success callbacks, you may want to use $.ajax.
If your web service provides an `XML` response, set the `type` argument to "xml".
Use a `Javascript` snippet from a Jquery example.
A very simple *JQuery* snippet [(from a tutorial)](http://docs.jquery.com/Tutorials:Edit_in_Place_with_Ajax), using `Jquery.post()`, which calls the server with an argument (`t`) and displays the content of the reply as a text alert:
```
$.post("test2.php",{content: t},function(txt){
alert(txt);
});
``` | XML Web Services | [
"",
"c#",
"asp.net",
"xml",
"web-services",
"open-source",
""
] |
Or is there any better suited 3rd party control for this purpose? | I know that [DevExpress XtraGrid](http://www.devexpress.com/Products/NET/Controls/WinForms/Grid/) supports, in theory, Int32.MaxValue rows or columns in the grid. In this case, the limit is the system memory not the grid.
But do you really need to display so much data? | Short answer: Dont do it!
Long answer: Change the FillWeight to 10 or less (default is 100). The limit you are reaching is due to the total FillWeight exceeding 64K x 100 (who knows why that is a limit). | How to add more than 65,535 columns in a data grid view in C# windows application? | [
"",
"c#",
"winforms",
"datagridview",
""
] |
```
String s1 = "The quick brown fox jumps over the lazy dog";
String s2 = "";
boolean b = s1.contains(s2);
System.out.println(b);
```
I run the Java code above, the b return true.
Since s2 is empty, why does s1 contains s2?
I check the Java API, it write:
Returns true if and only if this string contains the specified sequence of char values.
Parameters:
s - the sequence to search for
Returns:
true if this string contains s, false otherwise | Empty is a subset of any string.
Think of them as what is between every two characters.
Kind of the way there are an infinite number of points on any sized line...
(Hmm... I wonder what I would get if I used calculus to concatenate an infinite number of empty strings)
Note that "".equals("") only though. | Similarly:
```
"".contains(""); // Returns true.
```
Therefore, it appears that an empty string is contained in any `String`. | String.contains in Java | [
"",
"java",
"string",
""
] |
I have an object that I instantiate - it's quite nifty as it also extends a superclass and does some stuff in the constructor - in fact all the vital parameters and method calls are handled in the constructor.
After this I never call the object again to do something - I don't pass it to any other objects either - after it's instantiated it does it stuff and all is good. Is this the wrong way to do it? | Yes, doing significant work in the constructor is usually a bad idea.
Could you do this through a static method instead? The static method could create an instance of the superclass and then do whatever it needs to. The only problem with this approach would be if the superclass called virtual methods during *its* constructor, but that's a code smell in itself... | It may be a smell from the superclass, not the subclass.
Why do you need to do that? Is there functionality in the superclass that is publicly accessible only through the constructor? If so then you probably do need to create an instance to access that functionality. But it may be better to hide that behaviour behind a normal method rather than a subclass constructor.
But that's still not as good as fixing the superclass. | Object doesn't do anything after instantiation | [
"",
"java",
"oop",
"design-patterns",
""
] |
How can I convert the following `struct` to `unsigned char*`?
```
typedef struct {
unsigned char uc1;
unsigned char uc2;
unsigned char uc3;
unsigned char uc5;
unsigned char uc6;
} uchar_t;
uchar_t *uc_ptr = new uchar;
unsigned char * uc_ptr2 = static_cast<unsigned char*>(*uc_ptr);
// invalid static cast at the previous line
``` | You can't use a `static_cast` here since there is no relationship between the types. You would have to use `reinterpret_cast`.
Basically, a `static_cast` should be used in most cases, whereas `reinterpret_cast` should probably make you question why you are doing it this way.
Here is a time where you would use `static_cast`:
```
class Base {
};
class Derived : Base {
};
Base* foo = new Derived;
Derived* dfoo = static_cast<Derived*>( foo );
```
Whereas here is where you would probably need a `reinterpret_cast`:
```
void SetWindowText( WPARAM wParam, LPARAM lParam )
{
LPCTSTR strText = reinterpret_cast<LPCTSTR>( lParam );
}
``` | Due to struct packing differences, you can't do this reliably and portably without either using an array to begin with or writing some code that filled a new array one at a time from the struct members by name. A reinterpret\_cast might work on one compiler/platform/version and break on another.
You're better off allocating an array on the heap or stack, and then filling it one by one. | Convert struct to unsigned char * | [
"",
"c++",
"type-conversion",
"static-cast",
""
] |
I currently have two panels within another large panel. The left panel is for navigation and the right is for content. I'm trying to modify the content panel background color so I have made an event that triggers on expandnode, and this is where I am stuck.
My right panel ID is `#panneau-affichage` and I'm trying to modify the `background-color` attribute of the class x-panel-body that lives within. Using:
```
Ext.get('panneau-affichage').setBodyStyle('backgroundColor : #dddddd');
```
Firebug states that there is no such function, and with:
```
Ext.get('panneau-affichage').applyStyle('backgroundColor: #dddddd);
```
This does the job for the div but is overridden by x-panel-body. | Why don't you just set it via CSS? Use Firebug to drill down to panel's body div element. Write your own override using your panel's id. This way it will work without Javascript, and always and even before you start running your scripts.
**Using CSS class names**
If you're not looking into permanent changes and settings it would still be much better to define a CSS class and add/remove the class to panel itself and set panel's body style via CSS. It would be centralised and much better customizable. And it would keep style away from your code, which you should always thy to achieve. Separate code from visuals. | Solution for this:
```
Ext.getCmp('panel-id').body.setStyle('background','lightblue');
``` | How to dynamically change the background color of an ExtJS panel | [
"",
"javascript",
"css",
"extjs",
""
] |
Attached code is an example of how to use Google transliteration
feature in certain html textboxes. I need to enable the same
transliteration feature for a flex application. Is there a way
I could do it?
```
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://www.google.com/jsapi">
</script>
<script type="text/javascript">
// Load the Google Transliteration API
google.load("elements", "1", {
packages: "transliteration"
});
function onLoad() {
var options = {
sourceLanguage: 'en',
destinationLanguage: ['hi','kn','ml','ta','te'],
shortcutKey: 'ctrl+g',
transliterationEnabled: true
};
// Create an instance on TransliterationControl with the required
// options.
var control =
new google.elements.transliteration.TransliterationControl(options);
// Enable transliteration in the textfields with the given ids.
var ids = [ "transl1", "transl2" ];
control.makeTransliteratable(ids);
// Show the transliteration control which can be used to toggle between
// English and Hindi and also choose other destination language.
control.showControl('translControl');
}
google.setOnLoadCallback(onLoad);
</script>
</head>
<body>
<center>Type in Indian languages (Press Ctrl+g to toggle between English and Hindi)</center>
<div id='translControl'></div>
<br>Title : <input type='textbox' id="transl1"/>
<br>Body<br><textarea id="transl2" style="width:600px;height:200px"></textarea>
</body>
</html>
``` | Here is the final working code :
ajax\_api.mxml :
```
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:TextArea x="209" y="139" height="245" width="318" id="text1" fontSize="28"/>
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
import flash.external.*;
public function callWrapper():void {
var s:String;
if (ExternalInterface.available) {
ExternalInterface.addCallback("g", g);
var wrapperFunction:String = "initialize";
ExternalInterface.call(wrapperFunction,text1.text);
} else {
s = "Wrapper not available";
}
trace(s);
}
public function g(str:String):void
{
text1.text = str;
}
]]>
</mx:Script>
<mx:Button x="75" y="50" label="Enter some text and click this button to see the transliteration output" click="callWrapper()" height="37"/>
</mx:Application>
```
HTML Wrapper :
```
<!-- saved from url=(0014)about:internet -->
<html lang="en">
<!--
Smart developers always View Source.
This application was built using Adobe Flex, an open source framework
for building rich Internet applications that get delivered via the
Flash Player or to desktops via Adobe AIR.
Learn more about Flex at http://flex.org
// -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- BEGIN Browser History required section -->
<link rel="stylesheet" type="text/css" href="history/history.css" />
<!-- END Browser History required section -->
<title>ajax_api</title>
<script src="AC_OETags.js" language="javascript"></script>
<!-- BEGIN Browser History required section -->
<script src="history/history.js" language="javascript"></script>
<!-- END Browser History required section -->
<style>
body { margin: 0px; overflow:hidden }
</style>
<script language="JavaScript" type="text/javascript">
<!--
// -----------------------------------------------------------------------------
// Globals
// Major version of Flash required
var requiredMajorVersion = 9;
// Minor version of Flash required
var requiredMinorVersion = 0;
// Minor version of Flash required
var requiredRevision = 28;
// -----------------------------------------------------------------------------
// -->
</script>
</head>
<body scroll="no">
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("language", "1");
function thisMovie(movieName)
{
if(navigator.appName.indexOf("Microsoft")!=-1)
{
alert("microsoft");
return window[movieName];
}
else
{
return document[movieName];
}
}
function initialize(input) {
google.language.transliterate([input], "en", "hi", function(result) {
if (!result.error) {
var container = document.getElementById("transliteration");
if (result.transliterations && result.transliterations.length > 0 &&
result.transliterations[0].transliteratedWords.length > 0) {
output = result.transliterations[0].transliteratedWords[0];
thisMovie("ajax_api").g(output);
}
}
});
}
</script>
<script language="JavaScript" type="text/javascript">
<!--
// Version check for the Flash Player that has the ability to start Player Product Install (6.0r65)
var hasProductInstall = DetectFlashVer(6, 0, 65);
// Version check based upon the values defined in globals
var hasRequestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
if ( hasProductInstall && !hasRequestedVersion ) {
// DO NOT MODIFY THE FOLLOWING FOUR LINES
// Location visited after installation is complete if installation is required
var MMPlayerType = (isIE == true) ? "ActiveX" : "PlugIn";
var MMredirectURL = window.location;
document.title = document.title.slice(0, 47) + " - Flash Player Installation";
var MMdoctitle = document.title;
AC_FL_RunContent(
"src", "playerProductInstall",
"FlashVars", "MMredirectURL="+MMredirectURL+'&MMplayerType='+MMPlayerType+'&MMdoctitle='+MMdoctitle+"",
"width", "100%",
"height", "100%",
"align", "middle",
"id", "ajax_api",
"quality", "high",
"bgcolor", "#869ca7",
"name", "ajax_api",
"allowScriptAccess","sameDomain",
"type", "application/x-shockwave-flash",
"pluginspage", "http://www.adobe.com/go/getflashplayer"
);
} else if (hasRequestedVersion) {
// if we've detected an acceptable version
// embed the Flash Content SWF when all tests are passed
AC_FL_RunContent(
"src", "ajax_api",
"width", "100%",
"height", "100%",
"align", "middle",
"id", "ajax_api",
"quality", "high",
"bgcolor", "#869ca7",
"name", "ajax_api",
"allowScriptAccess","sameDomain",
"type", "application/x-shockwave-flash",
"pluginspage", "http://www.adobe.com/go/getflashplayer"
);
} else { // flash is too old or we can't detect the plugin
var alternateContent = 'Alternate HTML content should be placed here. '
+ 'This content requires the Adobe Flash Player. '
+ '<a href=http://www.adobe.com/go/getflash/>Get Flash</a>';
document.write(alternateContent); // insert non-flash content
}
// -->
</script>
<noscript>
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
id="ajax_api" width="100%" height="100%"
codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
<param name="movie" value="ajax_api.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#869ca7" />
<param name="allowScriptAccess" value="sameDomain" />
<embed src="ajax_api.swf" quality="high" bgcolor="#869ca7"
width="100%" height="100%" name="ajax_api" align="middle"
play="true"
loop="false"
quality="high"
allowScriptAccess="sameDomain"
type="application/x-shockwave-flash"
pluginspage="http://www.adobe.com/go/getflashplayer">
</embed>
</object>
</noscript>
</body>
</html>
``` | ```
The following flex code and javascript wrapper solves the problem.
Still there is one problem. I have to click the transliterate button twice
in order to get the output. Seems like there is some delay from the javascript
function returning the value.
```
flex code:
```
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute">
<mx:TextArea x="209" y="139" height="245" width="318" id="text1" fontSize="28"/>
<mx:Script>
<![CDATA[
import mx.rpc.events.ResultEvent;
import flash.external.*;
public function callWrapper():void {
var s:String;
if (ExternalInterface.available) {
var wrapperFunction:String = "initialize";
s = ExternalInterface.call(wrapperFunction,text1.text);
text1.text = s;
} else {
s = "Wrapper not available";
}
trace(s);
}
]]>
</mx:Script>
<mx:Button x="92" y="118" label="Transliterate" click="callWrapper()"/>
</mx:Application>
```
HTML Wrapper :
```
<!-- saved from url=(0014)about:internet -->
<html lang="en">
<!--
Smart developers always View Source.
This application was built using Adobe Flex, an open source framework
for building rich Internet applications that get delivered via the
Flash Player or to desktops via Adobe AIR.
Learn more about Flex at http://flex.org
// -->
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<!-- BEGIN Browser History required section -->
<link rel="stylesheet" type="text/css" href="history/history.css" />
<!-- END Browser History required section -->
<title></title>
<script src="AC_OETags.js" language="javascript"></script>
<!-- BEGIN Browser History required section -->
<script src="history/history.js" language="javascript"></script>
<!-- END Browser History required section -->
<style>
body { margin: 0px; overflow:hidden }
</style>
<script language="JavaScript" type="text/javascript">
<!--
// -----------------------------------------------------------------------------
// Globals
// Major version of Flash required
var requiredMajorVersion = 9;
// Minor version of Flash required
var requiredMinorVersion = 0;
// Minor version of Flash required
var requiredRevision = 28;
// -----------------------------------------------------------------------------
// -->
</script>
</head>
<body scroll="no">
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load("language", "1");
var output;
function initialize(input) {
google.language.transliterate([input], "en", "hi", function(result) {
if (!result.error) {
if (result.transliterations && result.transliterations.length > 0 &&
result.transliterations[0].transliteratedWords.length > 0) {
output = result.transliterations[0].transliteratedWords[0];
}
}
});
return output;
}
</script>
<script language="JavaScript" type="text/javascript">
<!--
// Version check for the Flash Player that has the ability to start Player Product Install (6.0r65)
var hasProductInstall = DetectFlashVer(6, 0, 65);
// Version check based upon the values defined in globals
var hasRequestedVersion = DetectFlashVer(requiredMajorVersion, requiredMinorVersion, requiredRevision);
if ( hasProductInstall && !hasRequestedVersion ) {
// DO NOT MODIFY THE FOLLOWING FOUR LINES
// Location visited after installation is complete if installation is required
var MMPlayerType = (isIE == true) ? "ActiveX" : "PlugIn";
var MMredirectURL = window.location;
document.title = document.title.slice(0, 47) + " - Flash Player Installation";
var MMdoctitle = document.title;
AC_FL_RunContent(
"src", "playerProductInstall",
"FlashVars", "MMredirectURL="+MMredirectURL+'&MMplayerType='+MMPlayerType+'&MMdoctitle='+MMdoctitle+"",
"width", "100%",
"height", "100%",
"align", "middle",
"id", "ajax_api",
"quality", "high",
"bgcolor", "#869ca7",
"name", "ajax_api",
"allowScriptAccess","sameDomain",
"type", "application/x-shockwave-flash",
"pluginspage", "http://www.adobe.com/go/getflashplayer"
);
} else if (hasRequestedVersion) {
// if we've detected an acceptable version
// embed the Flash Content SWF when all tests are passed
AC_FL_RunContent(
"src", "ajax_api",
"width", "100%",
"height", "100%",
"align", "middle",
"id", "ajax_api",
"quality", "high",
"bgcolor", "#869ca7",
"name", "ajax_api",
"allowScriptAccess","sameDomain",
"type", "application/x-shockwave-flash",
"pluginspage", "http://www.adobe.com/go/getflashplayer"
);
} else { // flash is too old or we can't detect the plugin
var alternateContent = 'Alternate HTML content should be placed here. '
+ 'This content requires the Adobe Flash Player. '
+ '<a href=http://www.adobe.com/go/getflash/>Get Flash</a>';
document.write(alternateContent); // insert non-flash content
}
// -->
</script>
<noscript>
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
id="ajax_api" width="100%" height="100%"
codebase="http://fpdownload.macromedia.com/get/flashplayer/current/swflash.cab">
<param name="movie" value="ajax_api.swf" />
<param name="quality" value="high" />
<param name="bgcolor" value="#869ca7" />
<param name="allowScriptAccess" value="sameDomain" />
<embed src="ajax_api.swf" quality="high" bgcolor="#869ca7"
width="100%" height="100%" name="ajax_api" align="middle"
play="true"
loop="false"
quality="high"
allowScriptAccess="sameDomain"
type="application/x-shockwave-flash"
pluginspage="http://www.adobe.com/go/getflashplayer">
</embed>
</object>
</noscript>
</body>
</html>
``` | Using google transliteration in Flex | [
"",
"javascript",
"ajax",
"apache-flex",
"transliteration",
""
] |
How can I code to share the same instance of a "singletonic" class among processes? | Best is to designate one specific process as owning that instance and dedicated to it; any other process requiring access to that instance obtains it by sending messages to the owning process via a Queue (as supplied by the multiprocessing module) or other IPC mechanisms for message passing, and gets answers back via similar mechanisms. | The whole point of processes is to have different address spaces. If you want to share information between processes you must use some means of [interprocess communication](http://en.wikipedia.org/wiki/Inter-process_communication). | python singleton into multiprocessing | [
"",
"python",
"multiprocessing",
""
] |
I'm a beginner with C#, ASP.NET, SQL Server Express and programming in general. I'm trying to make an online calendar (on a deadline). I'll read all the other posts that are similar to this, but for now I have a question that I hope will set me on my way.
What are the steps to link a calendar to a database? Any examples of where/how this has been done would be greatly appreciated?
I see possible pitfalls when a date has more than one entry by different users, so if anyone knows how this is managed again I'm all ears. | I have wrote you a small example that shows
1. Connecting to a SQL Express server
2. Reading data
3. Selecting multiple dates (i.e. more than one date entry by different users)
Hope this helps!...
```
// The SQL connection object to connect to the database. Takes connection string.
SqlConnection connection =
new SqlConnection(@"Data Source=localhost\SQLEXPRESS;Initial Catalog=Example");
// Idealy you wouldnt pass direct SQL text for injection reasons etc, but
// for example sake I will enter a simple query to get some dates from a table.
// Notice the command object takes our connection object...
SqlCommand command = new SqlCommand("Select [Date] From Dates", connection);
// Open the connection
connection.Open();
// Execute the command
SqlDataReader reader = command.ExecuteReader();
// A list of dates to store our selected dates...
List<DateTime> dates = new List<DateTime>();
// While the SqlDataReader is reading, add the date to the list.
while (reader.Read())
{
dates.Add(reader.GetDateTime(0));
}
// Close the connection!
connection.Close();
// Use the selected dates property of the ASP.NET calendar control, add every
// date that we read from the database...
foreach (DateTime date in dates)
{
Calendar1.SelectedDates.Add(date);
}
```
Good luck! | Dunno if this is of any help but [CodeProject](http://www.codeproject.com/KB/aspnet/EventCalendar.aspx) seems to have some similar solution | Best Practices for a Calendar Database Schema? | [
"",
"c#",
"asp.net",
"calendar",
""
] |
I have a bit of my game which looks like this:
```
public static float Time;
float someValue = 123;
Interlocked.Exchange(ref Time, someValue);
```
I want to change Time to be a Uint32; however, when I try to use `UInt32` instead of `float` for the values, it protests that the type must be a reference type. `Float` is not a reference type, so I know it's technically possible to do this with non-reference types. Is there any practical way to make this work with `UInt32`? | Although ugly, it *is* actually possible to perform an atomic **Exchange** or **CompareExchange** on an enum or other blittable value type of 64 bits or less using `unsafe` C# code:
```
enum MyEnum { A, B, C };
MyEnum m_e = MyEnum.B;
unsafe void example()
{
MyEnum e = m_e;
fixed (MyEnum* ps = &m_e)
if (Interlocked.CompareExchange(ref *(int*)ps, (int)(e | MyEnum.C), (int)e) == (int)e)
{
/// change accepted, m_e == B | C
}
else
{
/// change rejected
}
}
```
The counterintuitive part is that the **ref** expression on the dereferenced pointer *does actually penetrate* through the cast to the address of the enum. I think the compiler would have been within its rights to have generated an invisible temporary variable on the stack instead, in which case this wouldn't work. Use at your own risk.
[edit: for the specific type requested by the OP]
```
static unsafe uint CompareExchange(ref uint target, uint v, uint cmp)
{
fixed (uint* p = &target)
return (uint)Interlocked.CompareExchange(ref *(int*)p, (int)v, (int)cmp);
}
```
[edit: and 64-bit unsigned long]
```
static unsafe ulong CompareExchange(ref ulong target, ulong v, ulong cmp)
{
fixed (ulong* p = &target)
return (ulong)Interlocked.CompareExchange(ref *(long*)p, (long)v, (long)cmp);
}
```
(I also tried using the undocumented C# keyword `__makeref` to achieve this, but this doesn't work because you can't use `ref` on a dreferenced `__refvalue`. It's too bad, because the CLR maps the `InterlockedExchange` functions to a private internal function that operates on `TypedReference` [comment mooted by JIT interception, see below])
---
**[edit: July 2018]** You can now do this more efficiently using the [System.Runtime.CompilerServices.Unsafe](https://www.nuget.org/packages/System.Runtime.CompilerServices.Unsafe/) library package. Your method can use `Unsafe.As<TFrom,TTo>()` to directly reinterpret the type referenced by the target managed reference, avoiding the dual expenses of both **pinning** and transitioning to `unsafe` mode:
```
static uint CompareExchange(ref uint target, uint value, uint expected) =>
(uint)Interlocked.CompareExchange(
ref Unsafe.As<uint, int>(ref target),
(int)value,
(int)expected);
static ulong CompareExchange(ref ulong target, ulong value, ulong expected) =>
(ulong)Interlocked.CompareExchange(
ref Unsafe.As<ulong, long>(ref target),
(long)value,
(long)expected);
```
Of course this works for `Interlocked.Exchange` as well. Here are those helpers for the 4- and 8-byte unsigned types.
```
static uint Exchange(ref uint target, uint value) =>
(uint)Interlocked.Exchange(ref Unsafe.As<uint, int>(ref target), (int)value);
static ulong Exchange(ref ulong target, ulong value) =>
(ulong)Interlocked.Exchange(ref Unsafe.As<ulong, long>(ref target), (long)value);
```
This works for enumeration types also--but only so long as their underlying primitive integer is exactly four or eight bytes. In other words, `int` (32-bit) or `long` (64-bit) sized. The limitation is that these are the only two bit-widths found among the `Interlocked.CompareExchange` overloads. By default, `enum` uses `int` when no underlying type is specified, so `MyEnum` (from above) works fine.
```
static MyEnum CompareExchange(ref MyEnum target, MyEnum value, MyEnum expected) =>
(MyEnum)Interlocked.CompareExchange(
ref Unsafe.As<MyEnum, int>(ref target),
(int)value,
(int)expected);
static MyEnum Exchange(ref MyEnum target, MyEnum value) =>
(MyEnum)Interlocked.Exchange(ref Unsafe.As<MyEnum, int>(ref target), (int)value);
```
I'm not sure whether the 4-byte minimum is a fundamental to .NET, but as far as I can tell it leaves no means of atomically swapping (values of) the smaller 8- or 16-bit primitive types (`byte`, `sbyte`, `char`, `ushort`, `short`) without risking collateral damage to adjacent byte(s). In the following example, `BadEnum` explicitly specifies a size that is too small to be atomically swapped without possibly affecting up to three neighboring bytes.
```
enum BadEnum : byte { }; // can't swap less than 4 bytes on .NET?
```
If you're not constrained by interop-dictated (or otherwise fixed) layouts, a workaround would be to ensure that the memory layout of such enums is always padded to the 4-byte minimum to allow for atomic swapping (as `int`). It seems likely, however, that doing so would defeat whatever purpose there might have been for specifying the smaller width in the first place.
---
**[edit: April 2017]** I recently learned that when `.NET` is running in 32-bit mode (or, i.e. in the [WOW](https://en.wikipedia.org/wiki/Windows_on_Windows) subsystem), the 64-bit `Interlocked` operations are *not* guaranteed to be atomic with respect to **non-**`Interlocked`, "external" views of the same memory locations. In 32-bit mode, the atomic guarantee only applies globablly across QWORD accesses which use the `Interlocked` (and perhaps `Volatile.*`, or `Thread.Volatile*`, TBD?) functions.
In other words, to obtain 64-bit atomic operations in 32-bit mode, ***all*** accesses to those QWORD locations, including reads, must occur through `Interlocked`/`Volatile` in order to preserve the guarantees, so you can't get cute assuming (*e.g.*) that direct (*i.e.*, non-`Interlocked`/`Volatile`) *reads* are protected just because you always use `Interlocked`/`Volatile` functions for *writing*.
Finally, note that the `Interlocked` functions in the `CLR` are specially recognized by, and receive special treatment in, the .NET JIT compiler. See [here](https://referencesource.microsoft.com/#mscorlib/system/threading/interlocked.cs,168) and [here](https://github.com/dotnet/coreclr/blob/master/src/vm/jitinterface.cpp#L6827) This fact may help explain the counter-intuitiveness I mentioned earlier. | There's an overload for `Interlocked.Exchange` specifically for `float` (and others for `double`, `int`, `long`, `IntPtr` and `object`). There isn't one for uint, so the compiler reckons the closest match is the generic `Interlocked.Exchange<T>` - but in that case `T` has to be a reference type. `uint` isn't a reference type, so that doesn't work either - hence the error message.
In other words:
* Your current code works because it calls [`Interlocked.Exchange(ref float, float)`](http://msdn.microsoft.com/en-us/library/5z8f2s39.aspx).
* Changing it to `uint` fails because there's no applicable overload. The exact error message is caused by the compiler guessing that you mean [`Interlocked.Exchange<T>(ref T, T)`](http://msdn.microsoft.com/en-us/library/bb337971.aspx).
As for what to do, the options are any of:
* Potentially use `int` instead, as Marc suggests.
* If you need the extra range, think about using `long`.
* Use `uint` but don't try to write lock-free code
Although obviously `Exchange` works fine with *some* specific value types, Microsoft hasn't implemented it for all the primitive types. I can't imagine it would have been hard to do so (they're just bits, after all) but presumably they wanted to keep the overload count down. | C# Interlocked Exchange | [
"",
"c#",
"interlocked",
""
] |
In Java, is it possible to declare a field/variable whose type is multiple interfaces? For example, I need to declare a `Map` that is also `Serializable`. I want to make sure the variable references a serializable map. The `Map` interface does not extend `Serializable`, but most of `Map`'s implementations are `Serializable`.
I'm pretty sure the answer is no.
**Follow up**: I'm fully aware of creating a new interface that extends both `Map` and `Serializable`. This will not work as existing implementations (such as `HashMap`) do not implement my new interface. | There is no need to declare the field/variable like that. Especially since it can only be tested runtime and not compile time. Create a setter and report an error should the passed Map not implement Serializable.
The answers recommending that you create your own interface are of course not very practical as they will actively prohibit sending in things that are Maps and Serializable but not your special interface. | You can do it with generics, but it's not pretty:
```
class MyClass<T,K,V extends Serializable & Map<K,V>> {
T myVar;
}
``` | Java, declare variable with multiple interfaces? | [
"",
"java",
""
] |
I have a string:
```
"{0:16970861903381446063,length:1}"
```
I tried converting it to an object using the `eval` method, but it also evaluates the string and hence rounds the numerical value, returning:
```
{0:16970861903381447000,length:1}
```
I tried passing the number as a string before calling `eval` on it,
using `16970861903381446063 + ''` as the value when creating the JSON string; checking it with `typeof` shows it as being of type `string`, but it still rounds the number 16970861903381446063 to 16970861903381447000.
Is there a way I can bypass this, or a better way to do this?
Following is the code that generates the json text from an array containing the numbers
```
function simplify(arr){
request = "{";
if (arr.length ==1){
request += 0 + ":" + (arr[0] + '') + "," ;
}
else{
for (var i=0;i<=arr.length-1 ;i++){
request += i + ":" + (arr[i] + '') + ",";
}
}
request += "length" + ":" + arr.length +"}";
return request;
}
``` | You're running up against the precision of an IEEE double-precision float, which uses 53 bits for the mantissa and 11 bits for the exponent.
Javascript numbers, ALL of them, are represented by 64-bit floating point numbers. Floating point numbers in many languages are represented by two parts, a mantissa and an exponent. In Javascript, the mantissa is 53 bits, and the exponent is 11 bits.
When you see numbers expressed as, for example, 3.5346367e+22, the mantissa is 3.5246367, and the exponent is 22.
The numbers you are trying to store are larger than the maximum value of the mantissa, so your numbers get rounded, and larger numbers get an exponent.
Long story short, unless you're doing arithmetic operations with these huge numbers, you should store them as a string.
Lastly, you should expressed JSON Arrays as actual JSON Arrays, and not as objects that pretend to be arrays by defining integer keys and a length property:
```
// Do this
json = '["16970861903381446063"]';
// Not this
json = '{0:"16970861903381446063", length:1}';
``` | Just wrap it in quotes to make a string:
```
{
0: "16970861903381446063",
length: 1
}
```
I'm assuming you're just using this somewhere within the document; or are you planning to use it as an actual number? | Converting JSON string to object with selective evaluation | [
"",
"javascript",
"json",
""
] |
Let's say I have a type, MyType. I want to do the following:
1. Find out if MyType implements the IList interface, for some T.
2. If the answer to (1) is yes, find out what T is.
It seems like the way to do this is GetInterface(), but that only lets you search by a specific name. Is there a way to search for "all interfaces that are of the form IList" (If possible it woudl also be useful if it worked if the interface was a subinterface of IList.)
Related: [How to determine if a type implements a specific generic interface type](https://stackoverflow.com/questions/503263/how-to-determine-if-a-type-implements-a-specific-generic-interface-type) | ```
// this conditional is necessary if myType can be an interface,
// because an interface doesn't implement itself: for example,
// typeof (IList<int>).GetInterfaces () does not contain IList<int>!
if (myType.IsInterface && myType.IsGenericType &&
myType.GetGenericTypeDefinition () == typeof (IList<>))
return myType.GetGenericArguments ()[0] ;
foreach (var i in myType.GetInterfaces ())
if (i.IsGenericType && i.GetGenericTypeDefinition () == typeof (IList<>))
return i.GetGenericArguments ()[0] ;
```
*Edit:* Even if `myType` implements `IDerivedFromList<>` but not directly `IList<>`, `IList<>` will show up in the array returned by `GetInterfaces()`.
**Update:** added a check for the edge case where `myType` is the generic interface in question. | Using reflection (and some LINQ) you can easily do this:
```
public static IEnumerable<Type> GetIListTypeParameters(Type type)
{
// Query.
return
from interfaceType in type.GetInterfaces()
where interfaceType.IsGenericType
let baseInterface = interfaceType.GetGenericTypeDefinition()
where baseInterface == typeof(IList<>)
select interfaceType.GetGenericArguments().First();
}
```
First, you are getting the interfaces on the type and filtering out only for those that are a generic type.
Then, you get the generic type definition for those interface types, and see if it is the same as `IList<>`.
From there, it's a simple matter of getting the generic arguments for the original interface.
Remember, a type can have multiple `IList<T>` implementations, which is why the `IEnumerable<Type>` is returned. | Finding out if a type implements a generic interface | [
"",
"c#",
".net",
"reflection",
""
] |
I would like to copy a relatively short sequence of memory (less than 1 KB, typically 2-200 bytes) in a time critical function. The best code for this on CPU side seems to be `rep movsd`. However I somehow cannot make my compiler to generate this code. I hoped (and I vaguely remember seeing so) using memcpy would do this using compiler built-in intrinsics, but based on disassembly and debugging it seems compiler is using call to memcpy/memmove library implementation instead. I also hoped the compiler might be smart enough to recognize following loop and use `rep movsd` on its own, but it seems it does not.
```
char *dst;
const char *src;
// ...
for (int r=size; --r>=0; ) *dst++ = *src++;
```
Is there some way to make the Visual Studio compiler to generate `rep movsd` sequence other than using inline assembly? | ## Using memcpy with a constant size
What I have found meanwhile:
Compiler will use intrinsic when the copied block size is compile time known. When it is not, is calls the library implementation. When the size is known, the code generated is very nice, selected based on the size. It may be a single mov, or movsd, or movsd followed by movsb, as needed.
It seems that if I really want to use movsb or movsd always, even with a "dynamic" size I will have to use inline assembly or special intrinsic (see below). I know the size is "quite short", but the compiler does not know it and I cannot communicate this to it - I have even tried to use \_\_assume(size<16), but it is not enough.
Demo code, compile with "-Ob1 (expansion for inline only):
```
#include <memory.h>
void MemCpyTest(void *tgt, const void *src, size_t size)
{
memcpy(tgt,src,size);
}
template <int size>
void MemCpyTestT(void *tgt, const void *src)
{
memcpy(tgt,src,size);
}
int main ( int argc, char **argv )
{
int src;
int dst;
MemCpyTest(&dst,&src,sizeof(dst));
MemCpyTestT<sizeof(dst)>(&dst,&src);
return 0;
}
```
## Specialized intrinsics
I have found recently there exists very simple way how to make Visual Studio compiler copy characters using movsd - very natural and simple: using intrinsics. Following intrinsics may come handy:
* [\_\_movsb](http://msdn.microsoft.com/en-us/library/hhta9830%28VS.80%29.aspx)
* [\_\_movsw](http://msdn.microsoft.com/en-us/library/adf7db3x%28VS.100%29.aspx)
* [\_\_movsd](http://msdn.microsoft.com/en-us/library/9d196b9h.aspx) | Several questions come to mind.
First, how do you know movsd would be faster? Have you looked up its latency/throughput? The x86 architecture is full of crufty old instructions that should not be used because they're just not very efficient on modern CPU's.
Second, what happens if you use `std::copy` instead of memcpy? `std::copy` is potentially faster, as it can be specialized at compile-time for the specific data type.
And third, have you enabled intrinsic functions under project properties -> C/C++ -> Optimization?
Of course I assume other optimizations are enabled as well. | Make compiler copy characters using movsd | [
"",
"c++",
"performance",
"visual-studio-2005",
"memcpy",
"intrinsics",
""
] |
With Windows 7 due to be released at the end of 2009, what changes should we expect? What impact will Windows 7 have on the industry? Are we still going to be using .NET (3.5?) to program Windows? Where does 64-bit figure in all this?
We'll definitely be able to use Java for 64-bit stuff, but how is Microsoft going to have us making native 64-bit Windows applications? | IMO, Windows 7 is a better OS than Vista - a much better user experience; but from a coding perspective I'm not sure it will make a big difference.
A better question would probably be related to (for example) the impact of .NET 4.0, Visual Studio 2010 or Silverlight 3.0. And in answer; .NET 4.0 introduces much better (read: easier) support for multi-core programming. This is a big help, given the CPU changes. | Call me old-fashioned, but I'll still be using C/C++ to make both 32-bit and 64-bit applications, just as I have been for years. Windows 7 won't make a big difference to that. | How will Windows 7 be programmed? Will .NET still be king? | [
"",
"c#",
".net",
"windows",
"windows-7",
"64-bit",
""
] |
I am working on a simple invoicing and accounting applications, but I am totally lost on how to represent accounting-transactions(journal-entries) in a database. Using a separate debit and credit column in the database seems like one way, but most of the Open Source Accounting I have seen use a single amount column. This I assume simplifies the mathematics a lot. But then how do I convert debits, and credits to numerical values. [Wikipedia Helped a little](http://en.wikipedia.org/wiki/Double-entry_bookkeeping_system#Examples_of_debits_and_credits), but when i tried to cross check with an accounting system, it doesn't looks how it's done.
[Here's the export](http://sites.google.com/site/abhishiv/Home/transactions.pdf) from that accounting system:
Take a look at journal 326. While the sum of amount in this case = 0, the sum of credits isn't equal to sum of debits (Debiting 29 from Consulting & Accounting(E), Debiting 31.39 from AP(L), and crediting 2.39 to Sales Tax(L)).
However if I look at it as Debiting -31.39 from AP, It does. However I am not sure if we could credit/debit negative values.
Can someone explain how databases and accounting principles go together? | I think the problem of transaction 326 you mentioned about is that it seems you have done on the wrong side of Debit/Credit things.
The correct one should be that :
Debiting 29 from Consulting & Accounting, and
Debiiting 2.39 from Sales Tax. (in case that this is the Tax you have to pay as a consumer)
, then Crediiting 31.39 from AP,
Normally, AP will be on the Credit side, except when you settle down your payment. Then the transaction would be
Debiting xx.xx from AP, then Credit xx.xx from Cash/Bank
Handling these Debit/Credit things in separate columns may cause the database easier to read. By the way, UI that separate these columns is also more communicable with end users. In my point of view, the more we put things in the resemble fashions of what users learned from accouting classes, the less time we need to spend on telling them how to use the software.
We can't use negative value on accounting transactions. But on the DBMS side, we can keep things in the same column if we use + for Debitings, and - for Creditings. Anyhow, you still have to convert them back to absolutely positive value when exporting to accounting reports. | Martin Fowler's ["Analysis Patterns"](https://rads.stackoverflow.com/amzn/click/com/0201895420) has a nice chapter on modeling accounting systems. Maybe it can help you.
I think you'll be better off thinking about the problem in terms of objects rather than trying to map it onto a relational database. Databases are declarative and set-based; objects encapsulate data with operations in components. I think the latter will lend itself better to modeling accounting, especially if you marry it with aspect-oriented programming. Let the database just be the way you persist things and keep the logic in the middle tier. | Accounting System design & databases | [
"",
"sql",
"ruby-on-rails",
"database",
"database-design",
"activerecord",
""
] |
I'm using [Ubuntu 8.10](https://en.wikipedia.org/wiki/Ubuntu_version_history#Ubuntu_8.10_(Intrepid_Ibex)) (Intrepid Ibex) and compiling C++ files with GCC, but when I compile, gcc makes an `a.out` file that is the executable. How can I make Linux executables? | That executable is a "Linux executable" - that is, it's executable on any recent Linux system. You can rename the file to what you want using
```
rename a.out your-executable-name
```
or better yet, tell GCC where to put its output file using
```
gcc -o your-executable-name your-source-file.c
```
Keep in mind that before Linux systems will let you run the file, you may need to set its "executable bit":
```
chmod +x your-executable-name
```
Also remember that on Linux, the extension of the file has very little to do with what it actually is - your executable can be named `something`, `something.out`, or even `something.exe`, and as long as it's produced by GCC and you do `chmod +x` on the file, you can run it as a Linux executable. | To create an executable called `myprog`, you can call *gcc* like this:
```
gcc -c -o myprog something.c
```
You could also just rename the \*.out file *gcc* generates to the desired name. | Build a Linux executable using GCC | [
"",
"c++",
"linux",
"gcc",
"ubuntu",
"executable",
""
] |
I need to write JUnit tests for an old application that's poorly designed and is writing a lot of error messages to standard output. When the `getResponse(String request)` method behaves correctly it returns a XML response:
```
@BeforeClass
public static void setUpClass() throws Exception {
Properties queries = loadPropertiesFile("requests.properties");
Properties responses = loadPropertiesFile("responses.properties");
instance = new ResponseGenerator(queries, responses);
}
@Test
public void testGetResponse() {
String request = "<some>request</some>";
String expResult = "<some>response</some>";
String result = instance.getResponse(request);
assertEquals(expResult, result);
}
```
But when it gets malformed XML or does not understand the request it returns `null` and writes some stuff to standard output.
Is there any way to assert console output in JUnit? To catch cases like:
```
System.out.println("match found: " + strExpr);
System.out.println("xml not well formed: " + e.getMessage());
``` | using [ByteArrayOutputStream](http://java.sun.com/j2se/1.4.2/docs/api/java/io/ByteArrayOutputStream.html) and System.setXXX is simple:
```
private final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
private final ByteArrayOutputStream errContent = new ByteArrayOutputStream();
private final PrintStream originalOut = System.out;
private final PrintStream originalErr = System.err;
@Before
public void setUpStreams() {
System.setOut(new PrintStream(outContent));
System.setErr(new PrintStream(errContent));
}
@After
public void restoreStreams() {
System.setOut(originalOut);
System.setErr(originalErr);
}
```
sample test cases:
```
@Test
public void out() {
System.out.print("hello");
assertEquals("hello", outContent.toString());
}
@Test
public void err() {
System.err.print("hello again");
assertEquals("hello again", errContent.toString());
}
```
I used this code to test the command line option (asserting that -version outputs the version string, etc etc)
**Edit:**
Prior versions of this answer called `System.setOut(null)` after the tests; This is the cause of NullPointerExceptions commenters refer to. | I know this is an old thread, but there is a nice library to do this: [System Rules](https://stefanbirkner.github.io/system-rules)
Example from the docs:
```
public void MyTest {
@Rule
public final SystemOutRule systemOutRule = new SystemOutRule().enableLog();
@Test
public void overrideProperty() {
System.out.print("hello world");
assertEquals("hello world", systemOutRule.getLog());
}
}
```
It will also allow you to trap `System.exit(-1)` and other things that a command line tool would need to be tested for. | JUnit test for System.out.println() | [
"",
"java",
"console",
"junit",
""
] |
I'm manipulating few data with PHP, I have the choice between Json and XML. But I don't know what to choose, I never worked with one of them. So I want the easiest one.
Also I wonder if there's good classes that can make parsing (XML or Json) easier.
I focus mainly on ease of use rather than speed and scale. | [json.org](http://json.org) makes JSON parsing simple. [SimpleXML](https://www.php.net/simplexml) makes XML simple for PHP.
When choosing which one, it really depends on your application. If you will be passing data to JavaScript for processing on the client-side, then I recommend JSON. IMO, XML is better for data interchange between systems because it is very well understood and human readable (making interpreting easier for you). JSON is smaller over the wire, as there are no closing tags. | JSON parsing and generating is natively included in php:
<http://www.php.net/json> | What's better: Json or XML (PHP) | [
"",
"php",
"xml",
"json",
""
] |
Is there a way to make Eclipse break on uncaught exceptions while in debug mode for jUnit? Eclipse breaks fine when executing main(). Is there a command-line switch I can use?
Thanks | If you debug a single method in jUnit, the breakpoints start to work. If an entire class or package is debugged in jUnit, the debugger doesn't work. | From the debug perspective you can filter exactly which exceptions you are interested in.
In the Breakpoints view there is a "J!" button. This opens a window that allows you to choose which exceptions you want to break on.
If the problem only occurs when JUnit tests you need to make sure you are launching the tests in debug mode. The Rerun button in the JUnit will run in "normal" mode.
To run the tests in debug you can right click on the file and select "Debug as -> JUnit Test" from the menu. | Break on Exception in Eclipse using jUnit | [
"",
"java",
"eclipse",
"debugging",
"junit",
""
] |
How to use C# to capture a image of a specific url?
I want to use C# to automatically capture a image of a webpage based on a specific url.
For example, I have a page contains a txtUrl.Text = "<http://www.some.com/index.aspx>" , then I click a button, how can I capture a image of that Url? | I assume you want to do this from ASP.NET (as opposed to from a WinForms application).
In your web project, add a reference to System.Windows.Forms (yes, this is a bad thing to do). In your code-behind, you can then create an object of type System.Windows.Forms.WebBrowser:
```
WebBrowser browser = new WebBrowser();
// this will load up a URL into the web browser:
browser.Navigate(@"http://www.stackoverflow.com");
```
Next, just use the BitBlt API function (sorry, I don't have a link handy) to copy the WebBrowser control's graphical display to a Bitmap (which you can then display or save or whatever). With this function, the WebBrowser's Handle property is one of the parameters to pass.
Update: here's a link to some code that does exactly what you need: <http://www.developerfusion.com/code/4712/generate-an-image-of-a-web-page/> | If you mean a visual of the webpage, one approach is to integrate IE to your application and programmatically taking a screenshot. [This](http://www.alexschultz.co.uk/weblog/2006/05/web_browser_wid.html) (for the integrated web browser) and [this](http://www.geekpedia.com/tutorial181_Capturing-screenshots-using-Csharp.html) (for taking screenshots with C#) may be of use. This is of course IE dependent.
Another option is using the shotserver and shotfactory projects used for [browsershots.org](http://www.browsershots.org/). They can be found [here](http://sourceforge.net/projects/browsershots/files/), though I'm not sure if there's a .NET API for it. | How to use C# to capture a image of a specific url? | [
"",
"c#",
"image",
"url",
"capture",
""
] |
Say I have data like this:
```
<option value="abc" >Test - 123</option>
<option value="def" >Test - 456</option>
<option value="ghi" >Test - 789</option>
```
Using PHP, how would I sort through the HTML tags, returning all text from within the option values. For instance, given the code above, I'd like to return 'Test - 123', 'Test - 456', 'Test - 789'.
Thanks for the help!
**UPDATE:**
So that I'm more clear - I'm using filegetcontents() to get the html from a site. For my purposes, I'd like to be able to sort through the html, find the option values, and output them. In this case, return 'Test - 123', 'Test - 456', etc. | If we're doing regex stuff, I like this perl-like syntax:
```
$test = "<option value=\"abc\" >Test - 123</option>\n" .
"<option value=\"abc\" >Test - 456</option>\n" .
"<option value=\"abc\" >Test - 789</option>\n";
for ($offset=0; preg_match("/<option[^>]*>([^<]+)/",$test, $matches,
PREG_OFFSET_CAPTURE, $offset); $offset=$matches[1][1])
print($matches[1][0] . "\n");'
``` | There are many ways, which one is the best depends on more details than you've provided in your question.
One possibility: [DOMDocument and DOMXPath](http://php.net/dom)
```
<?php
$doc = new DOMDocument;
$doc->loadhtml('<html><head><title>???</title></head><body>
<form method="post" action="?" id="form1">
<div>
<select name="foo">
<option value="abc" >Test - 123</option>
<option value="def" >Test - 456</option>
<option value="ghi" >Test - 789</option>
</select>
</div>
</form>
</body></html>');
$xpath = new DOMXPath($doc);
foreach( $xpath->query('//form[@id="form1"]//option') as $o) {
echo 'option text: ', $o->nodeValue, " \n";
}
```
prints
```
option text: Test - 123
option text: Test - 456
option text: Test - 789
``` | How do I strip data from HTML tags | [
"",
"php",
"html",
"regex",
""
] |
Given a distance (50km) as integer: 50
And a time as string in the following format:00:02:04.05
hh:mm:ss.ms
How would I calculate the avg speed in km/h?
Thanks
Lance | The short answer is:
```
int d = 50;
string time = "00:02:04.05";
double v = d / TimeSpan.Parse(time).TotalHours;
```
This will give you the velocity (`v`) in km/h.
A more object-oriented answer includes defining Value Object classes for Distance and Speed. Just like TimeSpan is a value object, you could encapsulate the concept of distance irrespective of measure in a Distance class. You could then add methods (or operator overloads) than calculates the speed from a TimeSpan.
Something like this:
```
Distance d = Distance.FromKilometers(50);
TimeSpan t = TimeSpan.Parse("00:02:04.05");
Speed s = d.CalculateSpeed(t);
```
If you only need to calculate speed a few places in your code, such an approach would be overkill. On the other hand, if working with distances and velocities are core concepts in your domain, it would definitely be the correct approach. | Here you go:
```
double distanceInKilometres = double.Parse("50");
double timeInHours = TimeSpan.Parse("00:02:04.05").TotalHours;
double speedInKilometresPerHour = distanceInKilometres / timeInHours;
```
As I am not near a compiler, your mileage may vary :) | Calculate Avg Speed | [
"",
"c#",
"vb.net",
""
] |
Is there any Java function or util `class` which does rounding this way: `func(3/2) = 2`
`Math.ceil()` doesn't help, which by name should have done so. I am aware of `BigDecimal`, but don't need it. | `Math.ceil()` will always round up, however you are doing integer division with `3/2`. Thus, since in integer division `3/2 = 1` (not `1.5`) the ceiling of `1` is `1`.
What you would need to do to achieve the results you want is `Math.ceil(3/2.0);`
By doing the division by a double amount (`2.0`), you end up doing floating point division instead of integer division. Thus `3/2.0 = 1.5`, and the `ceil()` of `1.5` is always `2`. | A bit of black magic, and you can do it all with integers:
```
// Divide x by n rounding up
int res = (x+n-1)/n
``` | Is there any Java function or util class which does rounding this way: func(3/2) = 2? | [
"",
"java",
"rounding",
"ceil",
""
] |
I've read that the StringBuilder type has a limit (the default is 16 characters), and when you append some text to it, beyond its limit, a new instance is created with a higher limit and the data is copied to it. I tried that using the following code :
```
StringBuilder test = new StringBuilder("ABCDEFGHIJKLMNOP",16);
test.Append("ABC");
```
And the CIL generated for that was :
```
.maxstack 3
.locals init (class [mscorlib]System.Text.StringBuilder V_0)
IL_0000: nop
IL_0001: ldstr "ABCDEFGHIJKLMNOP"
IL_0006: ldc.i4.s 16
IL_0008: newobj instance void [mscorlib]System.Text.StringBuilder::.ctor(string, int32)
IL_000d: stloc.0
IL_000e: ldloc.0
IL_000f: ldstr "ABC"
IL_0014: callvirt instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(string)
IL_0019: pop
IL_001a: ret
```
Setting the limit to, say, 32 :
```
StringBuilder test = new StringBuilder("ABCDEFGHIJKLMNOP",32);
test.Append("ABC");
```
Generated exactly the same IL code.
What I expect is creating a new instance in the first case, and changing the value of the instance in the second case, which obviously didn't happen, any clue why? | All the fun stuff happens in this line:
```
IL_0014: callvirt instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(string)
```
This is where you make the call to the `Append()` method, but the IL you have posted does not contain the body of that method. Look in the [source code](http://weblogs.asp.net/scottgu/archive/2007/10/03/releasing-the-source-code-for-the-net-framework-libraries.aspx) for the StringBuilder class (it's released under a license that allows you to have a look), and see what happens within the `Append()` method.
**Spoiler alert!** A look at the source code of `Append()` will reveal that the internal buffer is indeed increased whenever the length of the concatenated string exeeds the current size of the buffer. | This C# code
```
using System.Text;
internal class Program
{
internal static void Main(string[] args)
{
StringBuilder test = new StringBuilder("ABCDEFGHIJKLMNOP", 16);
test.Append("ABC");
StringBuilder test2 = new StringBuilder("ABCDEFGHIJKLMNOP", 32);
test2.Append("ABC");
}
}
```
produces the following IL (according to Reflector):
```
.class private auto ansi beforefieldinit Program
extends [mscorlib]System.Object
{
.method public hidebysig specialname rtspecialname instance void .ctor() cil managed
{
.maxstack 8
L_0000: ldarg.0
L_0001: call instance void [mscorlib]System.Object::.ctor()
L_0006: ret
}
.method assembly hidebysig static void Main(string[] args) cil managed
{
.entrypoint
.maxstack 3
.locals init (
[0] class [mscorlib]System.Text.StringBuilder test,
[1] class [mscorlib]System.Text.StringBuilder test2)
L_0000: nop
L_0001: ldstr "ABCDEFGHIJKLMNOP"
L_0006: ldc.i4.s 0x10
L_0008: newobj instance void [mscorlib]System.Text.StringBuilder::.ctor(string, int32)
L_000d: stloc.0
L_000e: ldloc.0
L_000f: ldstr "ABC"
L_0014: callvirt instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(string)
L_0019: pop
L_001a: ldstr "ABCDEFGHIJKLMNOP"
L_001f: ldc.i4.s 0x20
L_0021: newobj instance void [mscorlib]System.Text.StringBuilder::.ctor(string, int32)
L_0026: stloc.1
L_0027: ldloc.1
L_0028: ldstr "ABC"
L_002d: callvirt instance class [mscorlib]System.Text.StringBuilder [mscorlib]System.Text.StringBuilder::Append(string)
L_0032: pop
L_0033: ret
}
}
```
So here, `0x10` and `0x20` are used to initalize `test` and `test2`, which means you probably looked at the wrong IL in your test? | System.Text.StringBuilder limit | [
"",
"c#",
".net",
"performance",
"string",
""
] |
I'm currently using MD5 hashes but I would like to find something that will create a shorter hash that uses just `[a-z][A-Z][0-9]`. It only needs to be around 5-10 characters long.
Is there something out there that already does this?
### Update 1:
I like the *CRC32* hash. Is there a clean way of calculating it in *.NET*?
### Update 2:
I'm using the *CRC32* function from the link *Joe* provided. How can I convert the uInt into the characters defined above? | .NET string object has a GetHashCode() function. It returns an integer.
Convert it into a hex and then to an 8 characters long string.
Like so:
```
string hashCode = String.Format("{0:X}", sourceString.GetHashCode());
```
More on that: <http://msdn.microsoft.com/en-us/library/system.string.gethashcode.aspx>
**UPDATE:** Added the remarks from the link above to this answer:
> The behavior of GetHashCode is dependent on its implementation, which
> might change from one version of the common language runtime to
> another. A reason why this might happen is to improve the performance
> of GetHashCode.
>
> If two string objects are equal, the GetHashCode method returns
> identical values. However, there is not a unique hash code value for
> each unique string value. **Different strings can return the same hash
> code.**
>
> **Notes to Callers**
>
> The value returned by GetHashCode is **platform-dependent**. It differs on
> the 32-bit and 64-bit versions of the .NET Framework. | Is your goal to create a URL shortener or to create a hash function?
If your goal is to create a URL shortener, then you don't need a hash function. In that case, you just want to pre generate a sequence of cryptographically secure random numbers, and then assign each url to be encoded a unique number from the sequence.
You can do this using code like:
```
using System.Security.Cryptography;
const int numberOfNumbersNeeded = 100;
const int numberOfBytesNeeded = 8;
var randomGen = RandomNumberGenerator.Create();
for (int i = 0; i < numberOfNumbersNeeded; ++i)
{
var bytes = new Byte[numberOfBytesNeeded];
randomGen.GetBytes(bytes);
}
```
Using the cryptographic number generator will make it very difficult for people to predict the strings you generate, which I assume is important to you.
You can then convert the 8 byte random number into a string using the chars in your alphabet. This is basically a change of base calculation (from base 256 to base 62). | What's the best way to create a short hash, similar to what tiny Url does? | [
"",
"c#",
".net",
"hash",
"short-url",
""
] |
I'm trying to use jquery to switch between three images once you click on the image. Upon clicking on the third image, it switches it back to the first picture.
Is there a way to adapt the following to switch between more than two pictures, and for it to allow more than it switching once?
**jQuery**
```
$(document).ready(function() {
$("#clickMe").click(function() {
$("#myimage").attr({src : "picture2.png"});
});
});
```
**HTML**
```
<div id="clickMe"><img id="myimage" src="picture1.png" /></div>
```
Thanks. | This should do that:
```
$(document).ready(function() {
$("#clickMe").click(function() {
var src = $('#myimage').attr('src');
//if the current image is picture1.png, change it to picture2.png
if(src == 'picture1.png') {
$("#myimage").attr("src","picture2.png");
//if the current image is picture2.png, change it to picture3.png
} else if(src == "picture2.png") {
$("#myimage").attr("src","picture2.png");
//if the current image is anything else, change it back to picture1.png
} else {
$("#myimage").attr("src","picture2.png");
}
});
});
``` | This works:
```
$(document).ready(function () {
var i = 1; // Used to keep track of which image we're looking at
$("#clickMe").click(function () {
i = i < 3 ? i + 1 : 1;
$("#myimage").html("picture#.png".replace("#", i));
});
});
```
Online demo: <http://jsbin.com/afito> | Jquery switching between several images on click | [
"",
"javascript",
"jquery",
"attributes",
""
] |
I'm running the following SAS command:
```
Proc SQL;
Delete From Server003.CustomerList;
Quit;
```
Which is taking over 8 minutes... when it takes only a few seconds to read that file. What could be cause a delete to take so long and what can I do to make it go faster?
(I do not have access to drop the table, so I can only delete all rows)
Thanks,
Dan
Edit: I also apparently cannot Truncate tables. | This is NOT regular SQL. SAS' Proc SQL does not support the Truncate statement. Ideally, you want to figure out what's going on with the performance of the `delete from`; but if what you really need is truncate functionality, you could always just use pure SAS and not mess with SQL at all.
```
data Server003.CustomerList;
set Server003.CustomerList (obs=0);
run;
```
This effectively performs and operates like a `Truncate` would. It maintains the dataset/table structure but fails to populate it with data (due to the OBS= option). | Try adding this to your `LIBNAME` statement:
```
DIRECT_EXE=DELETE
```
According to [SAS/ACCESS(R) 9.2 for Relational Databases: Reference](http://support.sas.com/documentation/cdl/en/acreldb/63647/HTML/default/viewer.htm#a002589104.htm),
> Performance improves significantly by using DIRECT\_EXE=, because the SQL delete statement is passed directly to the DBMS, instead of SAS reading the entire result set and deleting one row at a time. | Proc SQL Delete takes WAY too long | [
"",
"sql",
"sas",
"proc-sql",
""
] |
I'm working on a media library mock-up and I have a database of songs (over 9,000 tracks) that I want to display and make sortable. I'm not sure which GUI control would be best to use and I am not sure how it would be best to add all of the entries to the control.
Obviously using a listview and adding each entry one at a time takes a *long* time. Currently, the database is returning all of the tracks in an array of media objects (`mediaEntry[]` - a struct I defined). I don't know much about .NET's databinding system and any performance benefit that may bring.
The database is also searchable so I'll be changing the information displayed in the GUI control depending on the search terms. | Something like `DataGridView` or `ListView` in ["virtual mode"](http://msdn.microsoft.com/en-us/library/2b177d6d.aspx) should work well; this avoids the need to process all the data up-front.
**however** - I doubt that `mediaEntry` should be a `struct` - sounds like a `class` to me.
It is *very* rare you write a `struct` in .NET | The Listview control has a virtual mode, where you supply the viewable data on demand. Its actually easier to use than it sounds. Checkout the VirtualMode property and the RetrieveVirtualItem event. | Displaying a Large Amount of Data | [
"",
"c#",
".net",
""
] |
Currently I do the following to listen on any available port on all interfaces:
```
// hints struct for the getaddrinfo call
struct addrinfo hints, *res;
memset(&hints, 0, sizeof hints);
hints.ai_family = AF_INET;
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_PASSIVE;
// Fill in addrinfo with getaddrinfo
if (getaddrinfo(NULL, "0", &hints, &res) != 0) {
cerr << "Couldn't getaddrinfo." << endl;
exit(-1);
}
```
I would like to dynamically bind to only one interface, the non-loopback interface of the system.
How would I go about doing this? | Take a look at SO\_BINDTODEVICE. Tuxology has a [good description](http://tuxology.net/tag/interface/) of this | If you want an excellent book on the matter:
UNIX Network Programming by W. Richard Stevens, in two volumes. Volume one covers sockets.
Also Advanced Programming in the UNIX Environment, also by Stevens and updated in 3rd edition by Rago.
These are widely considered to be classics and standard references for UNIX / Linux / et al | How do I dynamically bind a socket to only one network interface? | [
"",
"c++",
"c",
"sockets",
"bind",
""
] |
With all the hype around MVC (and rightly so) I've decided to give it a go myself and write my first .NET MVC web application. With a few options to choose from I was wondering **which framework MVC do people recommend**.
* [Microsoft ASP.NET MVC](http://www.asp.net/mvc/)
+ The above with alternative view engine
* Castle Project - [MonoRail](http://www.castleproject.org/monorail/)
* [MVC#](http://www.mvcsharp.org/)
* [Maverick.NET](http://mavnet.sourceforge.net/)
It seems like the first two are really the top contenders. Also some DI container is a natural complement to MVC - MonoRail would [come with one](http://www.castleproject.org/container/index.html) already while ASP.NET MVC could perhaps work with something like [Unity](http://www.codeplex.com/unity). | I think the best option would be Microsoft ASP.NET MVC for the following reasons:
* It's official.
* It will have integration with visual studio 2010.
* It was developed by people who work for Microsoft.
* It's free.
* It has a large fan base of developers that swear by it.
* It has lots of documentation and information surrounding it.
* The power of .NET at your fingertips.
* Not limited to developing in one language. | Microsoft ASP.NET MVC
pro : you can take advantage of .net and your experience with asp.net | Pros and cons of different MVC frameworks for .NET | [
"",
"c#",
".net",
"model-view-controller",
""
] |
Can I edit an excel file from a browser using POI?
Something like google docs maybe? But in java?
I've used POI for display only, way way back, but I dont remember it being editable from the browser.
Any suggestions of the best approach to this?
The excel will display a list/table with data, and each row will either be reported as having 'good' or 'bad' data, and the user can then go to a bad row to correct it and edit this and submit this.. | > Can I edit an excel file from a browser using POI?
> No, you can try like google does with their AJAX apps for excel. But I think such an implementation isn't affordable.
You can use java dialogs and let poi create and process excel sheets. But you should suggest a few things if you want to do so:
From my experience:
* POI (Poor Obfuscation Implementation) is a bad and unstable framework. If you want to develop business solid software you have to deal with proprietary software for propreitary data formats like .doc/.xsl/.docx ...
* Think about licencing issues! You have to ensure that every user has a Office licence if you work with automized word versions on the server side (except Open Office UNO..)
The best way? Don't use POI. | There's no reason why you couldn't load data from an MS Office doc in the browser, then push changes back to the file stored on the server (wouldn't be surprised if GDocs works this way). This can be done with a few servlets.
Your real challenge is going to be writing code to display documents in a useful form. | Can I edit an excel file from a browser using POI? | [
"",
"java",
"excel",
"browser",
""
] |
I'm currently working on building a java web app. I've been looking to use Spring and Hibernate so I get some proper exposure to them, but I'm just getting burned out reading and learning about them. If I go ahead and build it with JSP and Servlets on a MySQL back end, what kind of levels of code reuse would I be looking at? I imagine the JSP's and POJO's would be more or less identical, but what about the rest of the code?
Thanks! | If you build using servlets, JDBC DAOs and JSPs, then it would be fairly straightforward to introduce Spring to the application at a later date:
* Replace the servlet code with Spring controllers. This would be doing Spring a bit of a dis-service, since they're capable of being so much more than just servlet replacements, but it's a start.
* In your JDBC DAOs, make use of Spring's JdbcDaoSupport and/or JdbcTemplate support classes. The bulk of your JDBC code would remain unchanged, you'd just be able to remove some of the plumbing and let Spring take the strain.
* If your app makes use of web page forms, you can use Spring's form taglib if you choose, although that would require re-engineering the controllers also. You can just leave the JSPs as they are, if you choose, completely unmodified.
* You can start using your Spring context to start auto-wiring your controllers and DAOs together, reducing manually-written wiring.
You can do any of these steps in any order, one step at a time. Spring is pretty good at being useful for as much as you want it to be, and then getting out of the way.
Hibernate's a different kettle of fish. It's big and complex, and a bit scary to begin with. I suggest getting settled in with Spring first, since Spring makes Hibernate a bit easier to handle. | It's likely that you can reuse the JSPs, assuming that you use JSTL and not scriplet code. You'll add Spring tags.
Hibernate isn't 100% necessary. You can start with Spring JDBC and migrate to Hibernate only if you think it can help you. I'd call that a second step to take after you have the functionality working under Spring.
Spring's pretty good for working alongside other code. It need not be an all or none proposition.
Spring will have you create a service interface. You'll have a persistence layer. The web MVC will isolate all the view concerns. You'll use Spring's front controller servlet to route requests to controllers. The controllers will worry about validation and binding HTTP parameters to objects and passing them to the services to fulfill the request.
You don't talk about security. Spring security will be a bonus. | Is it hard to convert a web app built with Jsp, Servlets & mySQL to one with Spring & Hibernate? | [
"",
"java",
"hibernate",
"spring",
"jsp",
"servlets",
""
] |
Firstly, let me give a brief description of the scenario. I'm writing a simple game where pretty much all of the work is done on the server side with a thin client for players to access it. A player logs in or creates an account and can then interact with the game by moving around a grid. When they enter a cell, they should be informed of other players in that cell and similarly, other players in that cell will be informed of that player entering it. There are lots of other interactions and actions that can take place but it's not worth going in to detail on them as it's just more of the same. When a player logs out then back in or if the server goes down and comes back up, all of the game state should persist, although if the server crashes, it doesn't matter if I lose 10 minutes or so of changes.
I've decided to use NHibernate and a SQLite database, so I've been reading up a lot on NHibernate, following tutorials and writing some sample applications, and am thoroughly confused as to how I should go about this!
The question I have is: what's the best way to manage my sessions? Just from the small amount that I do understand, all these possibilities jump out at me:
* Have a single session that's always opened that all clients use
* Have a single session for each client that connects and periodically flush it
* Open a session every time I have to use any of the persisted entities and close it as soon as the update, insert, delete or query is complete
* Have a session for each client, but keep it disconnected and only reconnect it when I need to use it
* Same as above, but keep it connected and only disconnect it after a certain period of inactivity
* Keep the entities detached and only attach them every 10 minutes, say, to commit the changes
What kind of strategy should I use to get decent performance given that there could be many updates, inserts, deletes and queries per second from possibly hundreds of clients all at once, and they all have to be consistent with each other?
Another smaller question: how should I use transactions in an efficient manner? Is it fine for every single change to be in its own transaction, or is that going to perform badly when I have hundreds of clients all trying to alter cells in the grid? Should I try to figure out how to bulk together similar updates and place them within a single transaction, or is that going to be too complicated? Do I even need transactions for most of it? | I would use a session per request to the server, and one transaction per session. I wouldn't optimize for performance before the app is mature.
Answer to your solutions:
* Have a single session that's always opened that all clients use: You will have performance issues here because the session is not thread safe and you will have to lock all calls to the session.
* Have a single session for each client that connects and periodically flush it: You will have performance issues here because all data used by the client will be cached. You will also see problems with stale data from the cache.
* Open a session every time I have to use any of the persisted entities and close it as soon as the update, insert, delete or query is complete: You won't have any performance problems here. A disadvantage are possible concurrency or corrupt data problems because related sql statements are not executed in the same transaction.
* Have a session for each client, but keep it disconnected and only reconnect it when I need to use it: NHibernate already has build-in connection management and that is already very optimized.
* Same as above, but keep it connected and only disconnect it after a certain period of inactivity: Will cause problems because the amount of sql connections is limited and will also limit the amount of users of your application.
* Keep the entities detached and only attach them every 10 minutes, say, to commit the changes: Will cause problems because of stale data in the detached entities. You will have to track changes yourself, which makes you end up with a piece of code that looks like the session itself.
It would be useless to go into more detail now, because I would just repeat the manuals/tutorials/book. When you use a session per request, you probably won't have problems in 99% of the application you describe (and maybe not at all). Session is a lightweight not threadsafe class, that to live a very short. When you want to know exactly how the session/connection/caching/transaction management works, I recommend to read a manual first, and than ask some more detailed questions about the unclear subjects. | Read the '`ISessionFactory`' on this [page](https://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html/architecture.html) of NHibernate documentation. `ISession`s are meant to be single-threaded (i.e., not thread-safe) which probably means that you shouldn't be sharing it across users. `ISessionFactory` should be created once by your application and `ISession`s should be created for each unit of work. Remember that creating an `ISession`s does not necessarily result in opening a database connection. That depends on how your SessionFactory's connection pooling strategy is configured.
You may also want to look at Hibernate's Documentation on [Session and Transaction](https://www.hibernate.org/42.html). | NHibernate session management? | [
"",
"c#",
"database",
"nhibernate",
"transactions",
"session",
""
] |
I'm a PHP/MySQL developer who hasn't used any form of versioning aside from copy/paste into a backup folder. I develop in a Windows environment as well. Where should I go, and what should I do to start using Versioning and Control software?
I'm curious, do these methods also apply to the databases you're using and their schema's? | Subversion. Its solid, and you can use TortoiseSVN as a client in windows (if you're on windows). Eclipse also has good subversion support.
I don't know enough about database question but at a minimum you could have versioned sql exports.
EDIT: Subversion, and TortoiseSVN are free :-)
There's a similar linux 'port'of TortoiseSVN called Subdiversvn but I haven't used it that much | I you are the only one working on the source I would recommend using git or mercurial. Unlike SVN, there is no need to set up a server. If you are developing on windows, I would recommend mercurial with TortoiseHg. | I need to start using Versioning and Source Control | [
"",
"php",
"mysql",
"version-control",
""
] |
I have a table like this:
name code group
john 12
smith 15
how do I insert group for a specified row?
say for 'smith' I have to insert the group..
i tried to do the following:
```
INSERT INTO table (group)
VALUES ('usher') where code = 15
```
error:
Incorrect syntax near the keyword 'where'.
please help!!
thanks in anticipation!! | ```
UPDATE mytable
SET group = 'usher'
WHERE code = 15
``` | As mentioned in the previous answer you want to perform an UPDATE not an INSERT.
UPDATE is used to change existing rows while INSERT will create new rows. Hence why WHERE can not be used with an INSERT statement. | sql query: using insert and where query together | [
"",
"sql",
""
] |
Today I stumbled upon the possibility to access a DOM element in Javascript simply by its id e.g. like this:
```
elementid.style.backgroundColor = "blue"
```
I tested with a very short snippet if this works in IE, Firefox and Chrome - and it does.
Here is the snippet I used:
```
<html><head>
<script>
function highlight() {
content.style.backgroundColor = "blue";
content.style.color = "white";
}
</script>
</head>
<body>
<div id="content">test content</div>
<div onclick="highlight()">highlight content</div>
</body></html>
```
So I wondered in which cases `document.getElementById('elementid')` should be used (or similar framework replacements like $()) and what are the drawbacks of the direct access.
I was not able to find any useful documentation on this. Everywhere either `getElementById` or framework methods are used. | It is propriety Microsoft gubbins. It doesn't work in lots of browsers — especially in standards mode (and you want standards mode to avoid [quirks mode](http://www.cs.tut.fi/~jkorpela/quirks-mode.html) inconsistencies such as IE getting `width` wrong). | You should also be concerned about name space. Right now you're treating it as if it's a variable in the global name space, and you would have to trust neither you nor any libraries that you include declare any global variables with the same name as DOM id's. The same goes for your highlight function.
Also while id's with dashes are perfectly valid, those would be inaccessible via this method.
e.g. `<div id="container-wrapper"><div id="container"> ... </div></div>`
would become `container-wrapper.style.color` which would then try to subtract wrapper.style.color from container. | What are the drawbacks of accessing DOM elements directly by ID? | [
"",
"javascript",
"dom",
""
] |
Are there any online resources which show the basic steps to access the Microsoft CRM on-premise web service with a client written in Java?
Which web service toolkit should I use?
I tried it with JAXB but there is a conflict in the WSDL element naming which requires a class customization. If I find the correct binding fix, I will post it here. | The Microsoft Dynamics CRM application on premise version uses Active Directory authentication.
Although I never tried referencing the Microsoft Dynamics CRM web services from Java, I am sure it is feasible, as these are standard web services and therefor can be referenced from Java via SOAP, just like any other web service.
```
public class TestCRM {
private static String endpointURL = "http://server:port/MSCrmServices/2007/CrmService.asmx";
private static String userName = "username";
private static String password = "password";
private static String host = "server";
private static int portport = port;
//To make sure you are using the correct domain open ie and try to reach the service. The same domain you entered there is needed here
private static String domain = "DOMAIN";
private static String orgName = "THIS_IS_REQUIRED"; //this does the work....
public static void main(String[] args) {
CrmServiceStub stub;
try {
stub = new CrmServiceStub(endpointURL);
setOptions(stub._getServiceClient().getOptions());
RetrieveMultipleDocument rmd = RetrieveMultipleDocument.Factory.newInstance();
RetrieveMultiple rm = RetrieveMultiple.Factory.newInstance();
QueryExpression query = QueryExpression.Factory.newInstance();
query.setColumnSet(AllColumns.Factory.newInstance());
query.setEntityName(EntityName.######.toString());
//query.setFilter...
rm.setQuery(query);
rmd.setRetrieveMultiple(rm);
//Now this is required. Without it all i got was 401s errors
CrmAuthenticationTokenDocument catd = CrmAuthenticationTokenDocument.Factory.newInstance();
CrmAuthenticationToken token = CrmAuthenticationToken.Factory.newInstance();
token.setAuthenticationType(0);
token.setOrganizationName(orgName);
catd.setCrmAuthenticationToken(token);
boolean fetchNext = true;
while(fetchNext){
RetrieveMultipleResponseDocument rmrd = stub.RetrieveMultiple(rmd, catd, null, null);
RetrieveMultipleResponse rmr = rmrd.getRetrieveMultipleResponse();
BusinessEntityCollection bec = rmr.getRetrieveMultipleResult();
String pagingCookie = bec.getPagingCookie();
fetchNext = bec.getMoreRecords();
ArrayOfBusinessEntity aobe = bec.getBusinessEntities();
BusinessEntity[] myEntitiesAtLast = aobe.getBusinessEntityArray();
for(int i=0; i<myEntitiesAtLast.length; i++){
//cast to whatever you asked for...
### myEntity = (###) myEntitiesAtLast[i];
}
}
}
catch (Exception e) {
e.printStackTrace();
}
}
private static void setOptions(Options options){
HttpTransportProperties.Authenticator auth = new HttpTransportProperties.Authenticator();
List authSchemes = new ArrayList();
authSchemes.add(HttpTransportProperties.Authenticator.NTLM);
auth.setAuthSchemes(authSchemes);
auth.setUsername(userName);
auth.setPassword(password);
auth.setHost(host);
auth.setPort(port);
auth.setDomain(domain);
auth.setPreemptiveAuthentication(false); //it doesnt matter...
options.setProperty(HTTPConstants.AUTHENTICATE, auth);
options.setProperty(HTTPConstants.REUSE_HTTP_CLIENT, "true"); //i think this is good.. not required though
}
``` | Java -> SOAP -> MS CRM 2011 Online : <http://zsvoboda.blogspot.com/2011/03/connecting-to-microsoft-crm-2011-online.html> | Connecting to Microsoft Dynamics CRM on-premise web service with Java? | [
"",
"java",
"web-services",
"dynamics-crm",
""
] |
I have seen other text editors use extensions to allow syntax checkers such as [JSLint](http://www.jslint.com), is this possible with Notepad++? | You may try JSLint Plugin for Notepad++:
<https://sourceforge.net/projects/jslintnpp/> | I have managed to get two lint programs to run using the [notepad++](http://notepad-plus.sourceforge.net/)'s [NppExec](http://sourceforge.net/project/showfiles.php?group_id=189927&package_id=224034) Plugin.
The NppExec plugin is usually installed by default and can be found under plugins -> NppExec. (Using NppExec 0.3 RC1 and Notepad++ 5.1+).
## 1) JSLint
first download the [WSH version of jslint](http://www.jslint.com/wsh/index.html) from <http://www.jslint.com>.
Modify the last part of the file as follows:
```
(function() {
if(!JSLINT(WScript.StdIn.ReadAll(),{passfail:false})) {
var e;
for(var i in JSLINT.errors) {
e=JSLINT.errors[i];
WScript.StdOut.WriteLine('Lint at line '+(e.line+1)+' character '+(e.character+1)+': '+e.reason);
WScript.StdOut.WriteLine(' '+(e.evidence||'').replace(/^\s*(\S*(\s+\S+)*)\s*$/,"$1"));
}
WScript.Quit(1);
}
}());
```
[(Pre-modified version here)](http://lynet.ca/~alumb/jslint/jslint.js)
This causes JSLint to output all of the errors, not just the first one.
Next, Notepad++'s NppExec doesn't allow the use of StdIn so I wrote a [batch file](http://lynet.ca/~alumb/jslint/jslint.bat) to actually execute the command.
This also allowed me to add a config file that is inserted before all javascript files. The options can be seen [here](http://www.jslint.com/lint.html#options).
The batch file looks like this:
```
@copy /b "C:\Program Files\jslint\conf.txt"+%1 "C:\Program Files\jslint\lastoutput.txt" > temp.txt
@cscript /Nologo "C:\Program Files\jslint\jslint.js" < "C:\Program Files\jslint\lastoutput.txt"
```
You may need to modify the paths depending on where you put the jslint.js file.
The [conf.txt](http://lynet.ca/~alumb/jslint/conf.txt) file looks like this:
```
/*jslint forin:true*/
```
Make sure there is no return carriage at the end of this line. If there is a return carriage all the lines counts will be off by one.
Finally, the command I entered into NppExec is:
```
"C:\Program Files\jslint\jslint.bat" "$(FULL_CURRENT_PATH)"
```
## 2) Javascript Lint
[Javascript lint](http://www.javascriptlint.com/) is a slightly less strict parser and was much easier to implement.
First grab a copy of the windows version from <http://www.javascriptlint.com/download.htm> and unzip it.
Then the NppExec command is:
```
"C:\Program Files\JavascriptLint\jsl.exe" -conf "C:\Program Files\JavascriptLint\jsl.default.conf" -process "$(FULL_CURRENT_PATH)"
```
(note: Most instructions for Javascript Lint will say to add "pauseatend" to the end of the command, I found this caused problems in Notepad++ so I left it off)
Hope this helps someone,
Cheers,
Andy. | Using JSLint in Notepad++ | [
"",
"javascript",
"notepad++",
"jslint",
"lint",
""
] |
I have a list of smart pointers. I want some of these smart pointers to act as regular pointers, meaning they are simply a reference to an instance and are not involved in its deallocation. They might for example point to instances allocated on the stack. The other smart pointers in the list should act as regular boost::shared\_ptr.
Here is how the class might look:
```
template<class T> smart_ptr {
private:
T *p;
boost::shared_ptr<T> sp;
public:
smart_ptr(T *p): p(p), shared(0) { } // p will not be deleted
smart_ptr(boost::shared_ptr<T> &sp): p(sp.get()), sp(sp) { }
T *get() const { return p; }
}
```
If there is a boost class that does this, I would prefer to use it instead of writing a class myself. It appears there are none, or am I mistaken? | One constructor for `shared_ptr` takes the destructor method, and you can pass in an empty functor.
[Using Custom Deallocator in boost::shared\_ptr](http://hafizpariabi.blogspot.com/2008/01/using-custom-deallocator-in.html)
(You want just an empty function.) | I've got this little class in my toolbox for this:
```
struct nodelete {
template <typename T>
void operator()( T * ) {}
};
```
Usage:
```
int main() {
SomeClass sc;
boost::shared_ptr<SomeClass> p( &sc, nodelete() );
// ...
}
``` | Is there a boost smart pointer class that can be configured not to delete at destruction? | [
"",
"c++",
"boost",
"smart-pointers",
""
] |
How to rearrange column order in sql server ?
right now my column is showing like below when i physically right click and take properties:
in sql server 2005
```
colA1
colA2
colA3
colA4
colB1
colB2
colB3
colA5
colA6
```
Since i know these columns (colA5,colA6) are created new !
How to make it like this ?
```
colA1
colA2
colA3
colA4
colA5
colA6
colB1
colB2
colB3
``` | You can do this easily enough in the designer (SSMS) - just drag the columns around to the correct order and then save - in the background it will script out and re-create the table.
But why do you need to do it? Order of columns has no impact other than making things look pretty in the designer. | Moving columns involves a lot of DDL, and doesn't actually do anything.
If the table is currently empty, fine... but if it has lots of data, this can be **very** painful. And if the table is currently replicated: even worse.
IMO, you should just handle this in the `SELECT` statement:
```
SELECT colA1, colA2, colA3, colA4, colA5, colA6, colB1, colB2, colB3
FROM TheTable
``` | Rearrage column order in sql server | [
"",
"sql",
"sql-server",
"sql-server-2005",
""
] |
In a nutshell, I'm searching for a **working** autocompletion feature for the Vim editor. I've [argued before](https://stackoverflow.com/questions/24109/c-ide-for-linux/24119#24119) that Vim completely replaces an IDE under Linux and while that's certainly true, it lacks one important feature: autocompletion.
I know about `Ctrl`+`N`, [Exuberant Ctags integration](http://ctags.sourceforge.net/), [Taglist](http://vim-taglist.sourceforge.net/), [cppcomplete](http://www.vim.org/scripts/script.php?script_id=527) and [OmniCppComplete](http://www.vim.org/scripts/script.php?script_id=1520). Alas, none of these fits my description of “working autocompletion:”
* **`Ctrl`+`N`** works nicely (only) if you've forgotton how to spell `class`, or `while`. Oh well.
* **Ctags** gives you the rudiments but has a lot of drawbacks.
* **Taglist** is just a Ctags wrapper and as such, inherits most of its drawbacks (although it works well for *listing* declarations).
* **cppcomplete** simply doesn't work as promised, and I can't figure out what I did wrong, or if it's “working” correctly and the limitations are by design.
* **OmniCppComplete** seems to have the same problems as cppcomplete, i.e. auto-completion doesn't work properly. Additionally, the `tags` file once again needs to be updated manually.
I'm aware of the fact that not even modern, full-blown IDEs offer good C++ code completion. That's why I've accepted Vim's lack in this area until now. But I think a fundamental level of code completion isn't too much to ask, and is in fact required for productive usage. So I'm searching for something that can accomplish at least the following things.
* **Syntax awareness**. cppcomplete promises (but doesn't deliver for me), correct, scope-aware auto-completion of the following:
```
variableName.abc
variableName->abc
typeName::abc
```
And really, anything else is completely useless.
* **Configurability**. I need to specify (easily) where the source files are, and hence where the script gets its auto-completion information from. In fact, I've got a Makefile in my directory which specifies the required include paths. Eclipse can interpret the information found therein, why not a Vim script as well?
* **Up-to-dateness**. As soon as I change something in my file, I want the auto-completion to reflect this. I do *not* want to manually trigger `ctags` (or something comparable). Also, changes should be *incremental*, i.e. when I've changed just one file it's completely *unacceptable* for `ctags` to re-parse the whole directory tree (which may be huge).
Did I forget anything? Feel free to update.
I'm comfortable with quite a lot of configuration and/or tinkering but I don't want to program a solution from scratch, and I'm not good at debugging Vim scripts.
A final note, I'd really like something similar for Java and C# but I guess that's too much to hope for: `ctags` only parses code files and both Java and C# have huge, precompiled frameworks that would need to be indexed. Unfortunately, [developing .NET without an IDE](http://greengoo.de/243/developing-dotnet-without-an-ide) is even more of a PITA than C++. | Try [YouCompleteMe](https://github.com/ycm-core/YouCompleteMe). It uses Clang through the libclang interface, offering semantic C/C++/Objective-C completion. It's much like clang\_complete, but substantially faster and with fuzzy-matching.
In addition to the above, YCM also provides semantic completion for C#, Python, Go, TypeScript etc. It also provides non-semantic, identifier-based completion for languages for which it doesn't have semantic support. | There’s also [**clang\_complete**](https://github.com/Rip-Rip/clang_complete/) which uses the [`clang` compiler](http://clang.llvm.org/) to provide code completion for C++ projects. There’s another question with [troubleshooting hints](https://stackoverflow.com/q/5641001/1968) for this plugin.
The plugin seems to work fairly well as long as the project compiles, but is prohibitively slow for large projects (since it attempts a full compilation to generate the tags list). | Autocompletion in Vim | [
"",
"c++",
"vim",
"ide",
"autocomplete",
""
] |
I created an anagram creating application, by creating an anagram field in my database, with a lower cased alphabetically stored string.
For example, suction becomes cinostu, ear becomes aer, and so on.
What I want to do now is create sub words from the original anagram searched for.
Example: How would you go about pulling the subset words from a search for 'arrest', i.e. 'rest' and 'stare'. | Hey Bork. been trying to adapt your code into PHP, and I have the following:
$LetterCount = array("a" => 1, "b" => 1, "c" => 1, "d" => 1, "e" => 0, "f" => 1, "g" => 1, "h" => 1, "i" => 1, "j" => 1, "k" => 1, "l" => 1, "m" => 1, "n" => 1, "o" => 1, "p" => 1, "q" => 1, "r" => 1, "s" => 1, "t" => 1, "u" => 1, "v" => 1, "w" => 1, "x" => 1, "y" => 1, "z" => 1);
```
$AsciiCodeLowerCaseA = 97;
for ($j = 1; $j < strlen($string); $j++) {
$CurrentLetter = $string[$j];
$AsciiCode = ord($CurrentLetter);
$AlphabetPos = $AsciiCode - $AsciiCodeLowerCaseA + 1;
$LetterCount[$AlphabetPos] = $LetterCount[$AlphabetPos] + 1;
}
```
I hardcoded the array declaration bit to save time.
Anyway, It didnt seem to work and gave me this error: Notice: Undefined offset: 1
Here is a screenshot of the errors I am getting, I have also added echos for each var or array in the loop to see if you can understand what is going on.
<http://i42.tinypic.com/11ryz4g.png>
I think it isnt identifying the aplhabet letter in the array correctly, and thus is adding numbers incorrectly to the end of the array.
Let me know what you think I should do. | Here's an approach I've used before that makes use of your list of alphabetically-sorted words.
1) Take your target word (arrest) and sort it (aerrst).
2) Then from the sorted word generate new strings where each letter is either included or excluded. For a word of N letters this gives 2\*\*N possible strings. (I don't know PHP but can give you pseudocode or eg Python if you would like.)
For your target word we have:
a, e, r, r, s, t, st, rs, rt, rst, rr, rs, rt, rst, rrs, rrt, rrst, er, er, es, et, est, ers, ert, erst, err, ers, ert, erst, errs, errt, errst, ae, ar, ar, as, at, ast, ars, art, arst, arr, ars, art, arst, arrs, arrt, arrst, aer, aer, aes, aet, aest, aers, aert, aerst, aerr, aers, aert, aerst, aerrs, aerrt, aerrst
3) Then check these strings against your sorted list. Those that appear in your sorted list correspond to the subset words you want.
eg aerrst corresponds to full anagrams (arrest, rarest, raster, ...)
eg aerst will be in your sorted list (stare, tears, ...)
eg rrs will not be in your sorted list | How do I create subset words for an anagram application (php)? | [
"",
"php",
"string",
"anagram",
""
] |
Is there any way for an application to determine the parameters and paramter types of a stored procedure at run time? | ADO.Net has this functionality. You'll want to use
`SqlCommandBuilder.DeriveParameters(mySqlCommand)`
This will populate your `SqlCommand` object, "mySqlCommand", with the name and type of the parameters. However, it does require an extra call to the database.
There are a few walkthroughs on the web if you google around for them. 4Guys has one [here](https://web.archive.org/web/20211020131038/https://aspnet.4guysfromrolla.com/articles/092408-1.aspx). | no, but you can get it from information\_schema.parameters
example procedure
```
create procedure prtest
@id int,
@name varchar(200),
@value decimal(20,10)
as
select 'bla'
go
```
now run this query
```
select parameter_name,data_type,* from information_schema.parameters
where specific_name = 'prtest'
order by ordinal_position
```
output
```
@id int
@name varchar
@value decimal
```
you still need to get the sizes from CHARACTER\_MAXIMUM\_LENGTH,NUMERIC\_PRECISION, NUMERIC\_SCALE | How to determine SQL Server stored procedure parmeters at run time in .NET? | [
"",
".net",
"sql",
"sql-server",
""
] |
> **Possible Duplicate:**
> [Why XML-Serializable class need a parameterless constructor](https://stackoverflow.com/questions/267724/why-xml-serializable-class-need-a-parameterless-constructor)
Does anyone know if it is possible to prevent calling of a public constructor from outside a range of assemblies?
What I'm doing is coming up with a class library that has XML serializable classes. These classes make no sense if constructed without setting various properties so I want to prevent that state.
I'm wondering if there is a way to prevent anyone calling my public constructor, and keep it there only for serialization? | Typically, I would create a public constructor with parameters that will make the object valid and create a public parameterless constructor with valid default values.
```
public foo() {
this.bar = -1;
}
public foo(int bar) {
this.bar = bar;
}
```
Private/internal constructor can be used depending on your situation, and you can create a Factory pattern that deals with object creation for external code. | To achieve what you are asking, you should probably make the constructor private, and then use a getInstance method to return the object if the correct assembly calls getInstance. You can do a check inside the getInstance method if you pass the object or assembly that called the function as one of its parameters. | Prevent calling Public constructors except for XML Serializer | [
"",
"c#",
"xml-serialization",
""
] |
How do you I stop my links like this:
```
<a href="#" onClick="submitComment()">
```
From jumping to the top of the page after the click? | Many times you'll see people use the `onclick` attribute, and simply `return false` at the end of it. While this does work reliably, it's a bit ugly and may make your code-base difficult to manage.
```
<a href="#" onClick="submitComment(); return false;">
```
### Seperate your HTML from your JavaScript
It's far better for you, and your project if you separate your markup from your scripting.
```
<a id="submit" href="enableScripts.html">Post Comment</a>
```
With the above HTML, we can find this element and wire up a handler for when the user clicks on the element. We can do all of this from an external .js file so that our HTML remains nice and clean, free from any scripting:
```
if (document.addEventListener) {
document.addEventListener("DOMContentLoaded", setup, false);
} else if (document.attachEvent) {
document.attachEvent("onreadystatechange", setup);
} else {
document.onload = setup;
}
function setup () {
var submit, submitComment;
submit = document.getElementById("submit");
submitComment = function (e) {
e = e || window.event;
e.preventDefault();
alert("You clicked the link!");
};
if (submit.addEventListener) {
submit.addEventListener("click", submitComment, false);
} else if (submit.attachEvent) {
submit.attachEvent("onclick", submitComment);
} else {
submit["onclick"] = submitComment;
}
}
```
There's a lot going on in the above code, but let's run over it from 30,000 feet. We start by figuring out how to best setup our code when the browser loads the page up. Ideally we'd like to do this when the DOM is ready.
After a few conditional checks we manage to instruct the browser to run our function after the DOM is prepared (this way our anchor element exists for us to interact with its behavior).
Our setup function gets a reference to this anchor, creates a function that we'll run when the anchor is clicked, and then finds a way to attach that function call to the click event of the anchor - losing your mind yet? This is the madness JavaScript developers have had to deal with for some time now.
### With jQuery, this is much easier
Perhaps you've heard of jQuery, and wondered why it is so popular. Let's solve the same problem, but this time with jQuery rather than raw vanilla JavaScript. Assuming the following markup:
```
<a id="submit" href="enableScripts.html">Post Comment</a>
```
The only JavaScript we need (thanks to jQuery) is this:
```
$(function(){
$("#submit").on("click", function(event){
event.preventDefault();
submitComment();
});
});
```
That's it - that is all it takes. jQuery handles all of the tests to determine, given your browser, what the best way is to do *this* or *that*. It takes all of the complicated stuff and moves it out of the way so that you are free to be creative. | Add a return false. I believe that without that the page will reload.
```
<a href="#" onClick="submitComment(); return false;">
``` | how to stop # links that call javascript functions from jumping to top of page | [
"",
"javascript",
"html",
""
] |
I am creating a new C# List (`List<double>`). Is there a way, other than to do a loop over the list, to initialize all the starting values to 0? | In addition to the functional solutions provided (using the static methods on the `Enumerable` class), you can pass an array of `double`s in the constructor.
```
var tenDoubles = new List<double>(new double[10]);
```
This works because the default value of an `double` is already 0, and probably performs slightly better. | You can use the initializer:
```
var listInt = new List<int> {4, 5, 6, 7};
var listString = new List<string> {"string1", "hello", "world"};
var listCustomObjects = new List<Animal> {new Cat(), new Dog(), new Horse()};
```
So you could be using this:
```
var listInt = new List<double> {0.0, 0.0, 0.0, 0.0};
```
Otherwise, using the default constructor, the List will be empty. | Auto-initializing C# lists | [
"",
"c#",
".net",
"list",
"collections",
""
] |
I have a Date object ( from Pear) and want to subtract another Date object to get the time difference in seconds.
I have tried a few things but the first just gave me the difference in days, and the second would allow me to convert one fixed time to unix timestamp but not the Date object.
```
$now = new Date();
$tzone = new Date_TimeZone($timezone);
$now->convertTZ($tzone);
$start = strtotime($now);
$eob = strtotime("2009/07/02 17:00"); // Always today at 17:00
$timediff = $eob - $start;
```
\*\* Note \*\* It will always be less than 24 hours difference. | Still gave somewhat wrong values but considering I have an old version of PEAR Date around, maybe it works for you or gives you an hint on how to fix :)
```
<pre>
<?php
require "Date.php";
$now = new Date();
$target = new Date("2009-07-02 15:00:00");
//Bring target to current timezone to compare. (From Hawaii to GMT)
$target->setTZByID("US/Hawaii");
$target->convertTZByID("America/Sao_Paulo");
$diff = new Date_Span($target,$now);
echo "Now (localtime): {$now->format("%Y-%m-%d %H:%M:%S")} \n\n";
echo "Target (localtime): {$target->format("%Y-%m-%d %H:%M:%S")} \n\n";
echo $diff->format("Diff: %g seconds => %C");
?>
</pre>
``` | Are you sure that the conversion of Pear Date object -> string -> timestamp will work reliably? That is what is being done here:
```
$start = strtotime($now);
```
As an alternative you could get the timestamp like this according to the [documentation](http://pear.php.net/package/Date/docs/latest/Date/Date.html#methodgetTime)
```
$start = $now->getTime();
``` | Calculate the difference between date/times in PHP | [
"",
"php",
""
] |
In Java, is there a way to truncate an array without having to make a copy of it? The common idiom is `Arrays.copyOf(foo, n)` (where the new array is n elements long). I don't think there is an alternative, but I'm curious as to whether there is a better approach. | An array's length in Java cannot be altered after initialization, so you're forced to make a copy with the new size. Actually, the length parameter of a Java array is declared as final, so it cannot be changed once it's set.
If you need to change an array's size, I'd use an ArrayList. | I was thinking about it some more... and just for kicks, how about something like the below.
**Note:** This is just a "can it be done?" intellectual exercise in Java hacking. Anybody who attempts to actually use this idea in production code will deserve all the pain that will undoubtedly follow.
```
public class Foo
{
private static byte[] array = new byte[10];
public static void main(String[] arg) throws Exception
{
Field field = Unsafe.class.getDeclaredField("theUnsafe");
field.setAccessible(true);
Unsafe unsafe = (Unsafe) field.get(null);
Field arrayField = Foo.class.getDeclaredField("array");
long ptr = unsafe.staticFieldOffset(arrayField);
// doesn't work... there's gotta be a way though!
unsafe.reallocateMemory(ptr, 5);
System.out.println("New array size is: " + array.length);
}
}
``` | Truncate an array without copying it? | [
"",
"java",
""
] |
I use this to mark code I need to come back to:
```
#warning Do more stuff here
```
However, sometimes these warning don't show up in the Error List window after a build. I can see the warnings in the compiler output window, but only some of them make it into the Error List. If I have the code file open that has these warnings they are always shown. If I have the code file closed, they don't appear most of the time. Is there a setting I can change to adjust this behaviour and always show the warnings in the Error List? | The reason is that, even if a warning occurs, the compiler normally considers this source file to be ok. So in an incremental build, the source file isn't recompiled, and the warning isn't displayed. | They should appear if you do a **rebuild** | "#warning" not always being shown in the Error List | [
"",
"c#",
".net",
""
] |
Can web technologies be used for a desktop application written in a traditional language like C++? I'd guess that they can, though I've not been able to find any evidence of this. I understand Adobe Air can make desktop apps using Flash, but it uses web languages like php etc. What I'd like to do is to be able to build my GUI elements - edit boxes, sliders, menus and so on, using html/CSS - instead of native widgets - in an application that is otherwise built in the conventional way - using Visual Studio for example.
Does anyone know if this has been done, if there's any software that makes it easier, or if there are any objections to this approach? | Qt is moving in this direction, with [CSS-like styling](http://doc.trolltech.com/4.5/stylesheet.html) and a forthcoming ["declarative" UI mechanism](http://labs.trolltech.com/blogs/2009/05/13/qt-declarative-ui/).
In addition, you can drive your app with Javascript via [QtScript](http://doc.trolltech.com/4.5/qtscript.html).
You could also use QtWebKit to provide an HTML based UI, it's possible to bridge between C++ code and Javascript too. | [xul](https://developer.mozilla.org/En/XUL) uses xml and CSS to define the GUI elements. | How can web technology be used for a C++ application GUI? | [
"",
"c++",
"html",
"css",
"user-interface",
"widget",
""
] |
The following example is bad, because it has code repetition. For example, if we later need to `CheckExpirationDate` before drinking, we need to add the function call in multiple places. If we need to add `charley` and `stan` to the party, the code gets huge quickly.
```
if (john != designatedDriver)
{
beer.Open();
john.Drink(beer);
}
if (bob != designatedDriver)
{
cider.Open();
bob.Drink(cider);
}
```
The solution could be to build an array of these objects. That's really easy if you need to operate one object at a time. For example, if everyone is passing around a single bottle of beer:
```
beer.Open();
foreach (Dude i in new Dude[] { john, bob })
{
i.Drink(beer);
}
```
To rewrite the original example, we can use a `KeyValuePair`. Not particularly pretty, but well worth it for more than two dudes or if the drinking procedure is long enough (wine tasting).
```
foreach (KeyValuePair<Dude, Booze> i in KeyValuePair<Dude, Booze>[] {
new KeyValuePair<Dude, Booze>(john, beer),
new KeyValuePair<Dude, Booze>(bob, cider) })
{
if (i.Key != designatedDriver)
{
i.Value.Open();
i.Key.Drink(i.Value);
}
}
```
**But what if we need to operate three or more objects at a time?** For example, john drinks beer *and* eats nachos. We can resort to declaring custom types, but that would make the code dependent on other code somewhere far away. We could put each type in its own array and do a good old `for` loop and access the objects with indexes, but that would mean creating named arrays (`Dude[] dudes = new Dude { john, bob };`).
What I'm asking is, **is there some fancy C# trick that would let me do this very cleanly and compactly?** Anonymous types? Something? | You mentioned anonymous types, this should do the trick:
```
foreach (var i in new[] {
new{Dude=john, Booze=beer, Food=nachos},
new{Dude=bob, Booze=cider, Food=chips}
})
{
if (i.Dude != designatedDriver)
{
i.Booze.Open();
i.Dude.Drink(i.Booze);
i.Dude.Eat(i.Food);
}
}
``` | Well.... assuming you had three separate collections of Dudes, Boozes, and Foods, you could use a LINQ query and create an anonymous type. Then you wouldn't have to worry about creating a new type and any dependencies that might be created by that. Here's an example:
```
// assumes existing collections called "boozes" "dudes" and "foods"
var qry = from booze in boozes
from dude in dudes
from food in foods
select new {
Dude = dude,
Booze = booze,
Food = food
};
foreach(var item in qry)
{
if(!item.Dude.IsDesignatedDriver)
{
item.Booze.Open();
item.Food.Cook();
item.Dude.Drink(item.Booze);
item.Dude.Eat(item.Food);
}
}
```
The drawbacks:
* the anonymous type must be used from within the calling block -- you can't return anonymous types from a method.
* you need pre-existing collections.
* The code listed creates a pairing for every dude, food, and booze option. You may not actually want that. A where clause may help there, however. | Handling a series of named variables of the same type | [
"",
"c#",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.