Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Is there some easy way to handle multiple submit buttons from the same form? For example:
```
<% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %>
<input type="submit" value="Send" />
<input type="submit" value="Cancel" />
<% Html.EndForm(); %>
```
Any idea how to do this in ASP.NET Framework Beta? All examples I've googled for have single buttons in them. | Here is a mostly clean attribute-based solution to the multiple submit button issue based heavily on the post and comments from [Maarten Balliauw](http://blog.maartenballiauw.be/post/2009/11/26/supporting-multiple-submit-buttons-on-an-aspnet-mvc-view.aspx).
```
[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class MultipleButtonAttribute : ActionNameSelectorAttribute
{
public string Name { get; set; }
public string Argument { get; set; }
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
var isValidName = false;
var keyValue = string.Format("{0}:{1}", Name, Argument);
var value = controllerContext.Controller.ValueProvider.GetValue(keyValue);
if (value != null)
{
controllerContext.Controller.ControllerContext.RouteData.Values[Name] = Argument;
isValidName = true;
}
return isValidName;
}
}
```
razor:
```
<form action="" method="post">
<input type="submit" value="Save" name="action:Save" />
<input type="submit" value="Cancel" name="action:Cancel" />
</form>
```
and controller:
```
[HttpPost]
[MultipleButton(Name = "action", Argument = "Save")]
public ActionResult Save(MessageModel mm) { ... }
[HttpPost]
[MultipleButton(Name = "action", Argument = "Cancel")]
public ActionResult Cancel(MessageModel mm) { ... }
```
*Update:* [Razor pages](https://learn.microsoft.com/en-us/aspnet/core/mvc/razor-pages/#using-multiple-handlers) looks to provide the same functionality out of the box. For new development, it may be preferable. | Give your submit buttons a name, and then inspect the submitted value in your controller method:
```
<% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %>
<input type="submit" name="submitButton" value="Send" />
<input type="submit" name="submitButton" value="Cancel" />
<% Html.EndForm(); %>
```
posting to
```
public class MyController : Controller {
public ActionResult MyAction(string submitButton) {
switch(submitButton) {
case "Send":
// delegate sending to another controller action
return(Send());
case "Cancel":
// call another action to perform the cancellation
return(Cancel());
default:
// If they've submitted the form without a submitButton,
// just return the view again.
return(View());
}
}
private ActionResult Cancel() {
// process the cancellation request here.
return(View("Cancelled"));
}
private ActionResult Send() {
// perform the actual send operation here.
return(View("SendConfirmed"));
}
}
```
EDIT:
To extend this approach to work with localized sites, isolate your messages somewhere else (e.g. compiling a resource file to a strongly-typed resource class)
Then modify the code so it works like:
```
<% Html.BeginForm("MyAction", "MyController", FormMethod.Post); %>
<input type="submit" name="submitButton" value="<%= Html.Encode(Resources.Messages.Send)%>" />
<input type="submit" name="submitButton" value="<%=Html.Encode(Resources.Messages.Cancel)%>" />
<% Html.EndForm(); %>
```
and your controller should look like this:
```
// Note that the localized resources aren't constants, so
// we can't use a switch statement.
if (submitButton == Resources.Messages.Send) {
// delegate sending to another controller action
return(Send());
} else if (submitButton == Resources.Messages.Cancel) {
// call another action to perform the cancellation
return(Cancel());
}
``` | How do you handle multiple submit buttons in ASP.NET MVC Framework? | [
"",
"c#",
"html",
"asp.net-mvc",
"http-post",
"form-submit",
""
] |
In javascript you can easily create objects and Arrays like so:
```
var aObject = { foo:'bla', bar:2 };
var anArray = ['foo', 'bar', 2];
```
Are similar things possible in PHP?
I know that you can easily create an array using the array function, that hardly is more work then the javascript syntax, but is there a similar syntax for creating objects? Or should I just use associative arrays?
```
$anArray = array('foo', 'bar', 2);
$anObjectLikeAssociativeArray = array('foo'=>'bla',
'bar'=>2);
```
So to summarize:
Does PHP have javascript like object creation or should I just use associative arrays? | For simple objects, you can use the associative array syntax and casting to get an object:
```
<?php
$obj = (object)array('foo' => 'bar');
echo $obj->foo; // yields "bar"
```
But looking at that you can easily see how useless it is (you would just leave it as an associative array if your structure was that simple). | There was a [proposal to implement this array syntax](http://wiki.php.net/rfc/shortsyntaxforarrays). ~~But it was declined.~~
---
**Update**ย ย ย ย The shortened syntax for arrays has been rediscussed, accepted, and is now on the [way be released with PHP 5.4](https://wiki.php.net/todo/php54).
But there still is no shorthand for objects. You will probably need to explicitly cast to *object*:
```
$obj = (object) ['foo'=>'bla', 'bar'=>2];
``` | Does PHP feature short hand syntax for objects? | [
"",
"php",
"object",
""
] |
I'm trying to match the parts of a version number (Major.Minor.Build.Revision) with C# regular expressions. However, I'm pretty new to writing Regex and even using Expresso is proving to be a little difficult. Right now, I have this:
```
(?<Major>\d*)\.(?<Minor>\d*)\.(?<Build>\d*)\.(?<Revision>\d*)
```
This works, but requires that every part of the version number exists. What I would like to do is also match versions like:
```
2.13
```
In this case, the Build and Revision groups need to return null values. Feel free to suggest a better method if I'm going about this all wrong. | ```
(?<Major>\d*)\.(?<Minor>\d*)(\.(?<Build>\d*)(\.(?<Revision>\d*))?)?
```
Makes the third and fourth parts optional. | I know this isn't a regex, but [System.Version](http://msdn.microsoft.com/en-us/library/system.version.aspx) does all the work for you. | Matching version number parts with regular expressions | [
"",
"c#",
"regex",
"version",
""
] |
I have a table for which I want to select top the 5 rows by some column A. I also want to have a 6th row titled 'Other' which sums the values in column A for all but the top 5 rows.
Is there an easy way to do this? I'm starting with:
```
select top 5
columnB, columnA
from
someTable t
order by
columnA desc
``` | Not tested, but try something like this:
```
select * from (
select top 5
columnB, columnA
from
someTable t
order by
columnA desc
union all
select
null, sum(columnA)
from
someTable t
where primaryKey not in (
select top 5
primaryKey
from
someTable t
order by
columnA desc
)
) a
``` | ```
select top 5 columnB, columnA
from someTable
order by columnA desc
select SUM(columnA) as Total
from someTable
```
Do the subtraction on the client side. | SQL Server 2005 - Select top N plus "Other" | [
"",
"sql",
"sql-server",
""
] |
So I have this code that takes care of command acknowledgment from remote computers, sometimes (like once in 14 days or something) the following line throws a null reference exception:
```
computer.ProcessCommandAcknowledgment( commandType );
```
What really bugs me is that I check for a null reference before it, so I have **no** idea whats going on.
Here's the full method for what its worth:
```
public static void __CommandAck( PacketReader reader, SocketContext context )
{
string commandAck = reader.ReadString();
Type commandType = Type.GetType( commandAck );
Computer computer = context.Client as Computer;
if (computer == null)
{
Console.WriteLine("Client already disposed. Couldn't complete operation");
}
else
{
computer.ProcessCommandAcknowledgment( commandType );
}
}
```
Any clues?
Edit: ProcessCommandAcknowledgment:
```
public void ProcessCommandAcknowledgment( Type ackType )
{
if( m_CurrentCommand.GetType() == ackType )
{
m_CurrentCommand.Finish();
}
}
``` | What are the other thread(s) doing?
Edit: You mention that the server is single threaded, but another comment suggests that *this portion* is single threaded. If that's the case, you could still have concurrency issues.
Bottom line here, I think, is that you either have a multi-thread issue or a CLR bug. You can guess which I think is more likely. | Based on the information you gave, it certainly appears impossible for a null ref to occur at that location. So the next question is "How do you know that the particular line is creating the NullReferenceException?" Are you using the debugger or stack trace information? Are you checking a retail or debug version of the code?
If it's the debugger, various setting combinations which can essentially cause the debugger to **appear** to report the NullRef in a different place. The main on that would do that is the Just My Code setting.
In my experience, I've found the most reliable way to determine the line an exception actually occurs on is to ...
1. Turn off JMC
2. Compile with Debug
3. Debugger -> Settings -> Break on Throw CLR exceptions.
4. Check the StackTrace property in the debugger window | Strange nullreference exception | [
"",
"c#",
".net",
"nullreferenceexception",
""
] |
I want to use dynamic mocks when testing a Silverlight application. I have tried Moq and Rhino but these frameworks assemblies cannot be added to a silverlight project as they are incompatible with the silverlight runtime.
Is there an existing silverlight mock framework (or patch for moq) that will allow me to use mock objects in a silverlight runtime? | The latest release of Moq has a fully supported silverlight version as well... | There is a working version of Rhino Mocks delivered by [Ayende Rahien](http://ayende.com/projects/rhino-mocks/downloads.aspx), I've tried this out over the last week and it works correctly in the Silverlight runtime. Great to see that mock objects are now available in Silverlight. | Is there any C# Dynamic Mock framework available for Silverlight? | [
"",
"c#",
"silverlight",
"unit-testing",
"mocking",
""
] |
Unmanaged languages notwithstanding, is F# really better than C# for implementing math? And if that's the case, why? | I think most of the important points were already mentioned by someone else:
1. F# lets you solve problems in a way mathematicians think about them
2. Thanks to higher-order functions, you can use simpler concepts to solve difficult problems
3. Everything is immutable by default, which makes the program easier to understand (and also easier to parallelize)
It is definitely true that you can use some of the F# concepts in C# 3.0, but there are limitations. You cannot use any recursive computations (because C# doesn't have tail-recursion) and this is how you write primitive computations in functional/mathematical way. Also, writing complex higher order functions (that take other functions as arguments) in C# is difficult, because you have to write types explicitly (while in F#, types are inferred, but also automatically generalized, so you don't have to explicitly make a function generic).
Also, I think the following point from Marc Gravell isn't a valid objection:
> From a maintenance angle, I'm of the view that suitably named properties etc are easier to use (over full life-cycle) than tuples and head/tail lists, but that might just be me.
This is of course true. However, the great thing about F# is that you can start writing the program using tuples & head/tail lists and later in the development process turn it into a program that uses .NET IEnumerables and types with properties (and that's how I believe typical F# programmer works\*). Tuples etc. and F# interactive development tools give you a great way to quickly prototype solutions (and when doing something mathematical, this is essential because most of the development is just experimenting when you're looking for the best solution). Once you have the prototype, you can use simple source code transformations to wrap the code inisde an F# type (which can also be used from C# as an ordinary class). F# also gives you a lot of ways to optimize the code later in terms of performance.
This gives you the benefits of easy to use langauges (e.g. Python), which many people use for prototyping phase. However, you don't have to rewrite the whole program later once you're done with prototyping using an efficient language (e.g. C++ or perhaps C#), because F# is both "easy to use" and "efficient" and you can fluently switch between these two styles.
(\*) I also use this style in my [functional programming book](http://manning.com/petricek/). | F# has many enormous benefits over C# in the context of mathematical programs:
* F# interactive sessions let you run code on-the-fly to obtain results immediately and [even visualize them](http://fsharpnews.blogspot.com/2010/02/f-for-visualization-video-tutorial.html), without having to build and execute a complete application.
* F# supports some features that can provide massive performance improvements in the context of mathematics. Most notably, the combination of `inline` and higher-order functions allow mathematical code to be elegantly factored without adversely affecting performance. C# cannot express this.
* F# supports some features that make it possible to implement mathematical concepts far more naturally than can be obtained in C#. For example, tail calls make it much easier to implement recurrence relations simply and reliably. C# cannot express this either.
* Mathematical problems often require the use of more sophisticated data structures and algorithms. Expressing complicated solutions is vastly easier with F# compared to C#.
If you would like a case study, I converted an implementation of QR decomposition over `System.Double` from 2kLOC of C#. The F# was only 100 lines of code, runs over 10ร faster and is generalized over the type of number so it works not only on `float32`, `float` and `System.Numerics.Complex` but can even be applied to symbolic matrices to obtain symbolic results!
FWIW, I [write books](http://www.ffconsultancy.com/products/fsharp_for_technical_computing/?so) on this subject as well as commercial software. | Is F# really better than C# for math? | [
"",
"c#",
"math",
"f#",
""
] |
I had a Dataset with some data in it. When I tried to write this DataSet into a file, everything was OK. But When I tried to write it into a MemoryStream, the XML file declaration was lost.
The code looks like:
```
DataSet dSet = new DataSet();
//load schema, fill data in
dSet.WriteXML("testFile.xml");
MemoryStream stream = new MemoryStream();
dSet.WriteXML(stream);
stream.Seek(0,SeekOrigin.Begin);
```
When I opened file testFile.xml, I got:
```
<?xml version="1.0" standalone="yes"?>
//balabala
```
But When I open the stream with StreamReader, I only got:
```
//balabala
```
Somebody said I can insert XML file declaration in my stream manually. It works but seems so ugly. Do you know why it dropped the first line and any more simple solution? | It wasn't dropped. Simply not included. Though it is highly recommend the xml declaration is not a required element of the xml specification.
<http://msdn.microsoft.com/en-us/library/ms256048(VS.85).aspx>
You can use XmlWriter.WriteStartDocument to include the xml declaration in the stream like so:
```
MemoryStream stream = new MemoryStream();
var writer = XmlWriter.Create(stream);
writer.WriteStartDocument(true);
dSet.WriteXML(stream);
``` | I try your solution with DataTable and don't work correctly.
```
using (MemoryStream stream = new MemoryStream()) {
using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8)) {
writer.WriteStartDocument(); //<?xml version="1.0" encoding="utf-8"?>
writer.WriteRaw("\r\n"); //endline
writer.Flush(); //Write immediately the stream
dTable.WriteXml(stream);
}
}
``` | Lost XML file declaration using DataSet.WriteXml(Stream) | [
"",
"c#",
"dataset",
""
] |
I've tried figuring out this problem for the last 2 days with no luck. I'm simply trying to create an annotation based JUnit test using the spring framework along with hibernate.
My IDE is netbeans 6.5 and I'm using hibernate 3, spring 2.5.5 and JUnit 4.4.
Here's the error I'm getting:
```
Testcase: testFindContacts(com.mycontacts.data.dao.MyContactHibernateDaoTransactionTest): Caused an ERROR
Failed to load ApplicationContext
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:203)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:255)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:93)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.invokeTestMethod(SpringJUnit4ClassRunner.java:130)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in class path resource [shared-context.xml]: Invocation of init method failed; nested exception is java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1337)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
at java.security.AccessController.doPrivileged(Native Method)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:221)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:423)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:729)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:381)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:84)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:42)
at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:173)
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:199)
Caused by: java.lang.NoSuchMethodError: org.objectweb.asm.ClassWriter.<init>(I)V
at net.sf.cglib.core.DebuggingClassWriter.<init>(DebuggingClassWriter.java:47)
at net.sf.cglib.core.DefaultGeneratorStrategy.getClassWriter(DefaultGeneratorStrategy.java:30)
at net.sf.cglib.core.DefaultGeneratorStrategy.generate(DefaultGeneratorStrategy.java:24)
at net.sf.cglib.core.AbstractClassGenerator.create(AbstractClassGenerator.java:216)
at net.sf.cglib.core.KeyFactory$Generator.create(KeyFactory.java:144)
at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:116)
at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:108)
at net.sf.cglib.core.KeyFactory.create(KeyFactory.java:104)
at net.sf.cglib.proxy.Enhancer.<clinit>(Enhancer.java:69)
at org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.getProxyFactory(CGLIBLazyInitializer.java:117)
at org.hibernate.proxy.pojo.cglib.CGLIBProxyFactory.postInstantiate(CGLIBProxyFactory.java:43)
at org.hibernate.tuple.entity.PojoEntityTuplizer.buildProxyFactory(PojoEntityTuplizer.java:162)
at org.hibernate.tuple.entity.AbstractEntityTuplizer.<init>(AbstractEntityTuplizer.java:135)
at org.hibernate.tuple.entity.PojoEntityTuplizer.<init>(PojoEntityTuplizer.java:55)
at org.hibernate.tuple.entity.EntityEntityModeToTuplizerMapping.<init>(EntityEntityModeToTuplizerMapping.java:56)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:295)
at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:434)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:109)
at org.hibernate.persister.PersisterFactory.createClassPersister(PersisterFactory.java:55)
at org.hibernate.impl.SessionFactoryImpl.<init>(SessionFactoryImpl.java:226)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1294)
at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:859)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.newSessionFactory(LocalSessionFactoryBean.java:814)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:732)
at org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1368)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1334)
``` | The `java.lang.NoSuchMethodError` always indicates that the version of a class that was on your compiler's classpath is different from the version of the class that is on your runtime classpath (had the method been missing at compile-time, the compile would have failed.)
In this case, you had a different version of `org.objectweb.asm.ClassWriter` on your classpath at compile time than is on your runtime classpath. | Definitely you have different versions of your ClassWriter class at runtime than compile time. | No Such Method Error when creating JUnit test | [
"",
"java",
"hibernate",
"spring",
"junit",
"netbeans6.5",
""
] |
I am not trying to make this a preference question, I am really wondering what people's experiences are with using jQuery and Rails or jRails for development. Most rails users including myself up to now have been using Prototype. However, I am mixing in a lot of jQuery plugins since they are so easy to use and extend.
I am now thinking about moving from Prototype to jQuery for a new Rails project. However, I love the Power of Prototype. Protoype is almost a new language that sites ontop of JS whereas I find that jQuery is like a great scripting language with lots of syntax sugar and chaining.
Anyway, your thoughts would be much appreciated. | In Rails it really all comes down to the helper methods. Are you using any prototype helper methods? If so then you must use jRails to switch to jQuery. But if not then it really does not matter. They are both great. I used prototype a lot before and it is great. But I prefer the selector way of doing things with jQuery so I have switched. Another good reason to not use the helper methods is unobtrusive javascript. The rails helper methods creates messy inline code. | jRails is great if you are using rjs templates if you want to maintain a "consistent" codebase between generated and handwritten. However, I personally have seen jRails not know how to really decently handle ajax form generators.
My biggest recommendation is to have jRails for "when you need it", and get more comfortable with writing JavaScript by hand. Prototype and jQuery are really two completely different schools of thought, and they aren't necessarily compatible. At first, I was a huge Prototype advocate, because a ton of my Ruby design knowledge was transferable, however I have learned to use jQuery in a much more robust way, using jQuery to empower more natural JavaScript. | jRails vs. Prototype | [
"",
"javascript",
"jquery",
"ruby-on-rails",
"prototypejs",
""
] |
I have a question about tables in MySQL.
I'm currently making a website where I have files for people to download. Now I want to make a table in MySQL that will store the latest downloads, like if someone downloads file1.zip then it will add a row in the table with the filename and date, so that I can show on the front page "Most recently downloaded files" or something like that.
And since I only need to display like 5-10 items I don't have to store more in the table.
So what I want to know is if it's possible to set a max limit to how many rows there can be in a table. Like if it's set to 10 and there is 10 entries in the table, the next time it tries to add one it will automatically delete the oldest one, so there's always only 10 rows in the table. | Look at [triggers](http://dev.mysql.com/doc/refman/5.0/en/triggers.html) to delete automatically the old rows. | This can be solved by using a trigger (MySQL 5 required) or setting up a cron job or something similar, that periodically checks the number of rows in the tables. | Possible to set max rows in MySQL table? | [
"",
"php",
"mysql",
""
] |
I'm currently considering the use of Reflection classes (ReflectionClass and ReflectionMethod mainly) in my own MVC web framework, because I need to automatically instanciate controller classes and invoke their methods without any required configuration ("convention over configuration" approach).
I'm concerned about performance, even though I think that database requests are likely to be bigger bottlenecks than the actual PHP code.
So, I'm wondering if anyone has any good or bad experience with PHP 5 Reflection from a performance point of view.
Besides, I'd be curious to know if any one of the popular PHP frameworks (CI, Cake, Symfony, etc.) actually use Reflection. | Don't be concerned. Install [Xdebug](http://www.xdebug.org/) and be sure where the bottleneck is.
There is cost to using reflection, but whether that matters depends on what you're doing. If you implement controller/request dispatcher using Reflection, then it's just one use per request. Absolutely negligible.
If you implement your ORM layer using reflection, use it for every object or even every access to a property, and create hundreds or thousands objects, then it might be costly. | I benchmarked these 3 options (the other benchmark wasn't splitting CPU cycles and was 4y old):
```
class foo {
public static function bar() {
return __METHOD__;
}
}
function directCall() {
return foo::bar($_SERVER['REQUEST_TIME']);
}
function variableCall() {
return call_user_func(array('foo', 'bar'), $_SERVER['REQUEST_TIME']);
}
function reflectedCall() {
return (new ReflectionMethod('foo', 'bar'))->invoke(null, $_SERVER['REQUEST_TIME']);
}
```
The absolute time taken for 1,000,000 iterations:
> print\_r(Benchmark(array('directCall', 'variableCall',
> 'reflectedCall'), 1000000));
```
Array
(
[directCall] => 4.13348770
[variableCall] => 6.82747173
[reflectedCall] => 8.67534351
)
```
And the relative time, also with 1,000,000 iterations (separate run):
> ph()->Dump(Benchmark(array('directCall', 'variableCall',
> 'reflectedCall'), 1000000, true));
```
Array
(
[directCall] => 1.00000000
[variableCall] => 1.67164707
[reflectedCall] => 2.13174915
)
```
It seems that the reflection performance was greatly increased in 5.4.7 (from ~500% down to **~213%**).
Here's the `Benchmark()` function I used if anyone wants to re-run this benchmark:
```
function Benchmark($callbacks, $iterations = 100, $relative = false)
{
set_time_limit(0);
if (count($callbacks = array_filter((array) $callbacks, 'is_callable')) > 0)
{
$result = array_fill_keys($callbacks, 0);
$arguments = array_slice(func_get_args(), 3);
for ($i = 0; $i < $iterations; ++$i)
{
foreach ($result as $key => $value)
{
$value = microtime(true);
call_user_func_array($key, $arguments);
$result[$key] += microtime(true) - $value;
}
}
asort($result, SORT_NUMERIC);
foreach (array_reverse($result) as $key => $value)
{
if ($relative === true)
{
$value /= reset($result);
}
$result[$key] = number_format($value, 8, '.', '');
}
return $result;
}
return false;
}
``` | PHP 5 Reflection API performance | [
"",
"php",
"performance",
"reflection",
""
] |
I have already googled for this
```
I have a Table with following structure in SQL 2000
ID ContactName Designation
1 A CEO
2 B ABC
3 C DEF
4 D GHI
```
I need the Output as follows
```
ContactName1 Contactname2 ContactName3 ContactName4
A CEO B ABC C DEF D GHI
```
Any Suggestions ? | It occurs to me that a lot of the examples are for cross tab queries involving aggregation, which yours does not appear to need. While I do not necessarily condone Dynamic SQL, the below should give you the results you want.
```
Create table #Contacts (id int)
Declare @ContactTypes int
Declare @CAD varchar(100)
Declare @I int
Declare @sql nvarchar(4000)
Set @i = 1
Select @ContactTypes =
Sum(sub.Types)
from ( Select Count(1) as Types from contacts
group by ContactName, Designation) as sub
Print @ContactTypes
While @i <= @ContactTypes
Begin
set @sql = 'alter table #Contacts Add ContactName' +
Cast(@I as varchar(10)) + ' varchar(100)'
exec sp_executesql @sql
Set @I = @i + 1
End
Insert into #Contacts (id) values (1)
Set @i = 1
Declare crsPivot cursor
for Select ContactName + ' ' + Designation
from contacts
open crsPivot
Fetch next from crsPivot into @CAD
While (@@Fetch_Status = 0)
Begin
Set @sql = 'Update #Contacts set ContactName'
+ Cast(@I as varchar(10)) +' = ' + quotename(@CAD,'''')
exec sp_executesql @sql
Set @i = @i + 1
Fetch next from crsPivot into @CAD
End
close crsPivot
Deallocate crsPivot
select * From #Contacts
``` | You need to use a [PIVOTED Table](http://msdn.microsoft.com/en-us/library/aa172756.aspx) | Cross Tab Query Required SQL 2000 | [
"",
"sql",
"crosstab",
""
] |
Alright so here is the deal. I am trying to make a application that's a GUI application yet has no GUI. So when the application starts, it has a small form with a login screen (I have done this part).
This the code for the `main()` in which the form runs but as soon as it is closed, I dispose of it.
```
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
//Create an instance of form1
Form1 form1 = new Form1();
Application.Run(form1);
if(form1.isLoggedIn)
{
filename = Path.Combine(Environment.GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData), DateTime.Now.ToString("ddMMyyhhmm") + "-" + form1.username);
Flow palm = new Flow(new FlowArguments(form1.username, filename));
MessageBox.Show("Thankyou, exiting...");
form1.Dispose();
}
}
```
So as you can see after the form is closed, the main continues on the condition if someone is logged in. If you look carefully, there's a instance to the `Flow` class that's created.
This is a very short class and here we go:
```
public class Flow
{
//global variables
FlowArguments FlowArgs;
System.Threading.Timer tm;
//constructor
public Flow(FlowArguments fmg)
{
FlowArgs = fmg;
tm = new System.Threading.Timer(Tick, null,
System.Threading.Timeout.Infinite, 10000);
using(StreamWriter sw = new StreamWriter(FlowArgs.Filename))
{
//sw.writelines that SO doesnt really care for.
}
//enable the timer
tm.Change(0, 100);
}
public void Tick(object State)
{
Console.WriteLine("Hello");
//a bunch of SteamWriter writeline methods that SO doesnt care for.
}
public void WriteProcesses(StreamWriter sw, DateTime dw)
{
var localAll = Process.GetProcesses().Where(o => o.ProcessName.ToLower() != "svchost");
foreach(Process p in localAll)
{
sw.WriteLine("@" + p.ProcessName +
"[" + dw.ToString("ddMMyyhhmm") + "]" +
"[" + FlowArgs.Username + "]");
}
}
}
```
As you can see I do start the timer. But since this uses `System.Threading.Timer` (because I read somewhere that the `Form.Timer` really isn't appropriate) it runs on a threadpool (as per MSDN) but while this is happening the main form has now exited out of `Main()` and hence the program is closed.
What are my possible solutions? This timer will run every 10 minutes (grabbing the processes). After the GUI is closed, I plan on making a system icon tray that the user can use to close the program. | If you want to make the foreground thread wait you can use a WaitHandle.
<http://msdn.microsoft.com/en-us/library/system.threading.waithandle.aspx> | Drop all that thread stuff and do it all in a form that implements the system tray icon. Put your timer in that form and everything you want is done.
Something like
```
LoginForm login = new LoginForm();
if(login.ShowDialog()==DialogResult.OK)
{
Application.Run(new SystemTrayForm());
}
``` | Timer doesn't "loop" | [
"",
"c#",
"timer",
""
] |
I'm trying to change the alt of the image, I'm clicking by
selecting the image's class (***`add_answer`***)
**Note:** ***`.add_answer`*** shows up multiple times inside different containing `div`'s
```
jQuery(function(){ // Add Answer
jQuery(".add_answer").click(function(){
var count = $(this).attr("alt");
count++;
$('.a_type_'+count+'').show();
$(this).parents("div:first").$('.add_answer').attr("alt", count);
});
});
```
This line doesn't seem to be working, how do I select this **`add_answer`** class by way of it's parent `div`
```
$(this).parents("div:first").$('.add_answer').attr("alt", count);
```
Anyone else have an idea?
I'm trying having trouble decreasing the `alt` value on the `.add_answer` image when `.destroy_answer` is clicked
```
jQuery(function(){ // Hide Answer
jQuery(".destroy_answer").click(function(){
$(this).parents("div:first").hide();
var count = $('.add_answer').attr("alt");
count--;
$('.add_answer',$(this).parent('div:first')).attr('alt',count);
});
});
```
Problem line:
```
$('.add_answer',$(this).parent('div:first')).attr('alt',count);
``` | you can use the parent div as the scope:
```
$('.add_answer',$(this).parent('div:first')).attr('alt',count);
``` | This should work:
```
$(this).parent("div").find(".add_answer").attr("alt", count);
``` | jquery select class inside parent div | [
"",
"javascript",
"jquery",
""
] |
I'm writing some unit tests which are going to verify our handling of various resources that use other character sets apart from the normal latin alphabet: Cyrilic, Hebrew etc.
The problem I have is that I cannot find a way to embed the expectations in the test source file: here's an example of what I'm trying to do...
```
///
/// Protected: TestGetHebrewConfigString
///
void CPrIniFileReaderTest::TestGetHebrewConfigString()
{
prwstring strHebrewTestFilePath = GetTestFilePath( strHebrewTestFileName );
CPrIniFileReader prIniListReader( strHebrewTestFilePath.c_str() );
prIniListReader.SetCurrentSection( strHebrewSubSection );
CPPUNIT_ASSERT( prIniListReader.GetConfigString( L"ืืื ืืืจืืืข" ) == L"ืืื ืืฉืืืง") );
}
```
This quite simply doesnt work. Previously I worked around this using a macro which calls a routine to transform a narrow string to a wide string (we use towstring all over the place in our applications so it's existing code)
```
#define UNICODE_CONSTANT( CONSTANT ) towstring( CONSTANT )
wstring towstring( LPCSTR lpszValue )
{
wostringstream os;
os << lpszValue;
return os.str();
}
```
The assertion in the test above then became:
```
CPPUNIT_ASSERT( prIniListReader.GetConfigString( UNICODE_CONSTANT( "ืืื ืืืจืืืข" ) ) == UNICODE_CONSTANT( "ืืื ืืฉืืืง" ) );
```
This worked OK on OS X but now I'm porting to linux and I'm finding that the tests are all failing: it all feels rather hackish as well. Can anyone tell me if they have a nicer solution to this problem? | A tedious but portable way is to build your strings using numeric escape codes. For example:
```
wchar_t *string = L"ืืื ืืืจืืืข";
```
becomes:
```
wchar_t *string = "\x05d3\x05d5\x05e0\x05d3\x05d0\x05e8\x05df\x05de\x05e2";
```
You have to convert all your Unicode characters to numeric escapes. That way your source code becomes encoding-independent.
You can use online tools for conversion, such as [this one](http://rishida.net/tools/conversion/). It outputs the JavaScript escape format `\uXXXX`, so just search & replace `\u` with `\x` to get the C format. | You have to tell GCC which encoding your file uses to code those characters into the file.
Use the option `-finput-charset=charset`, for example `-finput-charset=UTF-8`. Then you need to tell it about the encoding used for those string literals at runtime. That will determine the values of the wchar\_t items in the strings. You set that encoding using `-fwide-exec-charset=charset`, for example `-fwide-exec-charset=UTF-32`. Beware that the size of the encoding (utf-32 needs 32bits, utf-16 needs 16bits) must not exceed the size of `wchar_t` gcc uses.
You can adjust that. That option is mainly useful for compiling programs for `wine`, designed to be compatible with windows. The option is called `-fshort-wchar`, and will most likely then be 16bits instead of 32bits, which is its usual width for gcc on linux.
Those options are described in more detail in `man gcc`, the gcc manpage. | How can I embed unicode string constants in a source file? | [
"",
"c++",
"unit-testing",
"string",
"unicode",
"constants",
""
] |
As far as I am aware there is no inbuilt polygon functionality for Python. I want to create a 3D map and figured that polygons would be the best way to go about it.
Not wanting to reinvent the wheel I did some googling and found that there's a lot of Python stuff out there, but I couldn't find what I wanted. Thus before I reinvent the wheel (or invent it a whole), does anybody know of a Polygon system for Python?
Note that it does need to be 3D (I found quite a few 2D ones). Note also that I am not interested in the displaying of them but in storing them and the datastructure within Python.
Thanks | One of the most complete geography/mapping systems available for Python that I know about is [GeoDjango](http://geodjango.org/). This works on top of the [Django](http://www.djangoproject.com/), an MVC framework. With it comes a large collection of polygon, line and distance calculation tools that can even take into account the curvature of the earth's surface if need be.
With that said, the quickest way I can think of to produce a 3D map is using a height map. Create a two dimensional list of tuples containing (x, y, z) coordinates. Each tuple represents an evenly spaced point on a grid, mapped out by the dimensions of the array. This creates a simple plane along the X and Z axes; the ground plane. The polygons that make up the plane are quads, a polygon with four sides.
Next, to produce the three dimensional height, simply give each point a Y value. This will create peaks and valleys in your ground plane.
How you render this will be up to you, and converting your grid of points into a polygon format that something like OpenGL can understand may take some work, but have a look at [Visual Python](http://vpython.org/), its the simplest 3D library I've seen for Python. | I think you mean Polyhedron, not Polygon .. and you might wanna look at [vpython](http://vpython.org/) | 3D Polygons in Python | [
"",
"python",
"3d",
"polygon",
""
] |
If I open and close a socket by calling for instance
```
Socket s = new Socket( ... );
s.setReuseAddress(true);
in = s.getInputStream();
...
in.close();
s.close();
```
Linux states that this socket is still open or at least the file descriptor for the connection is presen. When querying the open files for this process by lsof, there is an entry for the closed connection:
```
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
java 9268 user 5u sock 0,4 93417 can't identify protocol
```
This entry remains until the program is closed. Is there any other way to finally close the socket?
I'm a little worried that my java application may block to many file descriptors. Is this possible? Or does java keep these sockets to re-use them even is ReuseAdress is set? | If those sockets are all in the TIME\_WAIT state, this is normal, at least for a little while. Check that with netstat; it is common for sockets to hang around for a few minutes to ensure that straggling data from the socket is successfully thrown away before reusing the port for a new socket. | You may also want to check `/proc/<pid>/fd`, the directory will contain all of your currently opened file descriptors. If a file disappears after you closed the socket you will not run into any problems (at least not with your file descriptors :). | Is there a file descriptor leak when using sockets on a linux platform? | [
"",
"java",
"linux",
"sockets",
"file-descriptor",
""
] |
Which method do you think is the "best".
* Use the `System.IO.Packaging` namespace?
* Use interop with the Shell?
* Third party library for .NET?
* Interop with open source unmanaged DLL?
[I can target Framework 3.5; best = easiest to design, implement, and maintain.]
I am mostly interested in why you think the chosen approach is best. | I've always used [SharpZipLib](http://www.icsharpcode.net/OpenSource/SharpZipLib/)
Forgot the why part: Mainly because its been around for a long time. It is well documented, and has an intuitive API. Plus it's open source if you're into that type of thing. | [DotNetZip](http://www.codeplex.com/DotNetZip) is very simple to use. I like it because it is fully-managed - no shell interaction required. The programming model is simpler and cleaner than that for the shell. Also it is simpler than SharpZipLib as well as the Packaging classes added in .NET 3.0. It is free, small, actively maintained.
It is much better than the J# option that one poster offered - J# is a huge runtime and a giant pill to swallow to get just ZIP support. Also J# support is being discontinued. Probably not a good idea to introduce new dependencies on J#.
Example code for DotNetZip:
```
try
{
using (ZipFile zip = new ZipFile(args[0], System.Console.Out))
{
zip.AddDirectory(args[1]); // recurses subdirectories
zip.Save();
}
}
catch (System.Exception ex1)
{
System.Console.Error.WriteLine("exception: " + ex1);
}
```
DotNetZip works with .NET v2.0, 3.0, 3.5 as well as Compact Framework v2.0 and 3.5. It does ZIP files, Unicode filenames, comments, passwords. It does ZIP64 as well as Self-extracting archives. It's FAST. Try it. | What is the best/easiest way to create ZIP archive in .NET? | [
"",
"c#",
".net",
"zip",
""
] |
I'm developing an `ASP.Net MVC` site and on it I list some bookings from a database query in a table with an `ActionLink` to cancel the booking on a specific row with a certain `BookingId` like this:
**My bookings**
```
<table cellspacing="3">
<thead>
<tr style="font-weight: bold;">
<td>Date</td>
<td>Time</td>
<td>Seats</td>
<td></td>
<td></td>
</tr>
</thead>
<tr>
<td style="width: 120px;">2008-12-27</td>
<td style="width: 120px;">13:00 - 14:00</td>
<td style="width: 100px;">2</td>
<td style="width: 60px;"><a href="/Booking.aspx/Cancel/15">cancel</a></td>
<td style="width: 80px;"><a href="/Booking.aspx/Change/15">change</a></td>
</tr>
<tr>
<td style="width: 120px;">2008-12-27</td>
<td style="width: 120px;">15:00 - 16:00</td>
<td style="width: 100px;">3</td>
<td style="width: 60px;"><a href="/Booking.aspx/Cancel/10">cancel</a></td>
<td style="width: 80px;"><a href="/Booking.aspx/Change/10">change</a></td>
</tr>
</table>
```
What would be nice is if I could use the `jQuery Dialog` to popup a message asking if the user is sure he wants to cancel the booking. I have been trying get this to work but I keep getting stuck on how to create a jQuery function that accepts parameters so that I can replace the
`<a href="/Booking.aspx/Cancel/10">cancel</a>`
with
`<a href="#" onclick="ShowDialog(10)">cancel</a>`.
The `ShowDialog` function would then open the dialog and also pass the paramter 10 to the dialog so that if the user clicks yes then It will post the href: `/Booking.aspx/Change/10`
I have created the jQuery Dialog in a script like this:
```
$(function() {
$("#dialog").dialog({
autoOpen: false,
buttons: {
"Yes": function() {
alert("a Post to :/Booking.aspx/Cancel/10 would be so nice here instead of the alert");},
"No": function() {$(this).dialog("close");}
},
modal: true,
overlay: {
opacity: 0.5,
background: "black"
}
});
});
```
and the dialog itself:
```
<div id="dialog" title="Cancel booking">Are you sure you want to cancel your booking?</div>
```
So finally to my question: How can I accomplish this? or is there a better way of doing it? | You could do it like this:
* mark the `<a>` with a class, say "cancel"
* set up the dialog by acting on all elements with class="cancel":
```
$('a.cancel').click(function() {
var a = this;
$('#myDialog').dialog({
buttons: {
"Yes": function() {
window.location = a.href;
}
}
});
return false;
});
```
(plus your other options)
The key points here are:
* make it as unobtrusive as possible
* if all you need is the URL, you already have it in the href.
However, I recommend that you make this a POST instead of a GET, since a cancel action has side effects and thus [doesn't comply with GET semantics](http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html)... | jQuery provides a method which store data for you, no need to use a dummy attribute or to find workaround to your problem.
Bind the click event:
```
$('a[href*=/Booking.aspx/Change]').bind('click', function(e) {
e.preventDefault();
$("#dialog-confirm")
.data('link', this) // The important part .data() method
.dialog('open');
});
```
And your dialog:
```
$("#dialog-confirm").dialog({
autoOpen: false,
resizable: false,
height:200,
modal: true,
buttons: {
Cancel: function() {
$(this).dialog('close');
},
'Delete': function() {
$(this).dialog('close');
var path = $(this).data('link').href; // Get the stored result
$(location).attr('href', path);
}
}
});
``` | Passing data to a jQuery UI Dialog | [
"",
"javascript",
"jquery",
"asp.net-mvc",
"jquery-ui",
"jquery-ui-dialog",
""
] |
In C# 3.0, I have a property which is suppose to contain the version of the class. The version number is simply the date and time of compilation. Right now, I have the following code:
```
public DateTime Version
{
get { return DateTime.UtcNow; }
}
```
Obviously, this is wrong since this property returns me the current date and time. **So, is the precompiler can *print* the DateTime at compile time?** In this case, I could do something similar to below.
```
public DateTime Version
{
get { return new DateTime("PRECOMPILER DATE"); }
}
``` | C# doesn't have the concept of macros; however, you can use other tools in your build script (csproj / NANT / etc) to manipulate the source before it compiles. I use this, for example, to set the revision number to the current SVN revision.
A cheap option is a pre-build event (you can do this via the project properties dialog in VS): essentially a bat file that runs before build; you can then script whatever changes you need. A more sophisticated option is build tasks.
For example, the utility library [here](http://msbuildtasks.tigris.org/) includes a `Time` task and a `FileUpdate` task; it should (in theory) be possible to chain the two together to emulate what you need.
Personally, I'd use the `[AssemblyVersion]` details rather than the time - if you link this to your source-control system, this makes it very easy to find the offending version; so for my SVN version, I then use (in my build proj):
```
<!-- See http://msbuildtasks.tigris.org -->
<Import Project="$(MSBuildExtensionsPath)\MSBuildCommunityTasks\MSBuild.Community.Tasks.Targets"/>
...
<SvnInfo LocalPath=".">
<Output TaskParameter="Revision" PropertyName="BuildRev" />
</SvnInfo>
...
<FileUpdate Files="Path\To\My\AssemblyInfo.cs"
Regex='(\[\s*assembly:\s*AssemblyVersion\(\s*"[^\.]+\.[^\.]+)\.([^\.]+)(\.)([^\.]+)("\)\s*\])'
ReplacementText='$1.$2.$(BuildRev)$5' />
<FileUpdate Files="Path\To\My\AssemblyInfo.cs"
Regex='(\[\s*assembly:\s*AssemblyFileVersion\(\s*"[^\.]+\.[^\.]+)\.([^\.]+)(\.)([^\.]+)("\)\s*\])'
ReplacementText='$1.$2.$(BuildRev)$5' />
```
And now my assembly-version is correct, including the file-version that gets reported by the OS. | You can retreive it from the dll itself ([Source: codinghorror](http://www.codinghorror.com/blog/archives/000264.html))
```
private DateTime RetrieveLinkerTimestamp() {
string filePath = System.Reflection.Assembly.GetCallingAssembly().Location;
const int c_PeHeaderOffset = 60;
const int c_LinkerTimestampOffset = 8;
byte[] b = new byte[2048];
System.IO.Stream s = null;
try {
s = new System.IO.FileStream(filePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
s.Read(b, 0, 2048);
} finally {
if (s != null) {
s.Close();
}
}
int i = System.BitConverter.ToInt32(b, c_PeHeaderOffset);
int secondsSince1970 = System.BitConverter.ToInt32(b, i + c_LinkerTimestampOffset);
DateTime dt = new DateTime(1970, 1, 1, 0, 0, 0);
dt = dt.AddSeconds(secondsSince1970);
dt = dt.AddHours(TimeZone.CurrentTimeZone.GetUtcOffset(dt).Hours);
return dt;
}
``` | How can I get the current DateTime from the Precompiler in C#? | [
"",
"c#",
".net",
"c-preprocessor",
""
] |
What are all the things one needs to be careful about when coding in a multicore environment?
For example, for a singleton class, it is better to create a global object and then return its reference than a static object.
i.e
Rather than having
```
MyClass & GetInstance()
{
static Myclass singleMyclass;
return singleMyclass;
}
```
It is better to have
```
Myclass singleMyclass;
MyClass & GetInstance()
{
return singleMyclass;
}
```
GetInstance() might be called by many threads simultaneously.
**Edit:**
My question was about the hidden constructs of c++ one must be aware of while using them in multithreaded program. In above case static is not thread safe as compiler adds some instructions for static objects, which is not thread safe. I am looking for similar constructs one should be aware of. | My first answer addressed your example of singleton initialisation, but as you emphasised in an edit to your question, you are after more general pit falls of C++ as we move to multi-core and multi-threaded applications. The following is a real surprise when you first encounter it. Though not C++ specific, it definitely affects C++ code.
**Out of order execution and Memory Barriers (or fences):**
One gotcha is out of order execution. It is possible for threads to see operations of other threads executing on different cores out of order due to modern hardware allowing out of order execution optimisation. As a result, multi-threaded coded that runs correctly on a single-core machine may in fact be incorrect on a multi-core machine.
A naive solution to such problems is to increase the scope of critical sections. Another is to use [memory barriers](http://en.wikipedia.org/wiki/Memory_barrier) or lock-free algorithms. | You must be careful with initialisation of statics. The order of initialisation can play havoc in complex system where static objects do lots of things in their constructors.
The first approach is better as singletons are created on demand, but you need some locking to make it thread safe.
The second approach is thread safe as initialisation is done before any threads are created (assuming your static objects do not start threads running), but order or initialisation can be a big problem! What if a static object calls GetInstance() from it's constructor before singleMyclass is instantiated? (Hint: it ain't pretty!)
I would recommend using the first approach, but read up on [Double-checked locking](http://en.wikipedia.org/wiki/Double-checked_locking), but be careful, because it [doesn't actually work](http://www.ddj.com/184405726)
Make sure you read that Dr. Dobb's article. | c++; things to take care in multicore environment | [
"",
"c++",
"multithreading",
""
] |
In the python program I'm writing, I've got a thread which iterates over a large structure in memory and writes it incrementally into a file-like object. I've got another thread which takes a file-like object and writes it to disk. Is there an easy way to connect the two, such that any data input from the first thread will be buffered for the second?
Specifically, I'm trying to pass data to subprocess.Popen(). The process will read from stdin, but you cannot pass a "file-like" object to Popen because it calls stdin.fileno() and blows up unless you have a real file.
Instead, you need to pass the PIPE argument to Popen, which allows you to use proc.stdin as a file-like object. But if you've already got a file-like object, there doesn't seem to be a great way to yolk the two of them together. | Use [`shutil`'s `copyfileobj()`](http://docs.python.org/library/shutil.html#shutil.copyfileobj) function:
```
import shutil
import subprocess
proc = subprocess.Popen([...], stdin=subprocess.PIPE)
my_input = get_filelike_object('from a place not given in the question')
shutil.copyfileobj(my_input, proc.stdin)
```
No need to use threads. | You should use the [Queue](http://docs.python.org/library/queue.html) module for sharing sequential data across threads. You would have to make a file-like Queue subclass, where .read and .write mutually block each other, with a buffer in-between.
OTOH, I wonder why the first thread can't write to the real file in the first place. | Is there a simple way in Python to create a file which can be written to in one thread and read in a different one? | [
"",
"python",
""
] |
I have set the FlushMode property on an NHibernate session to FlushMode.Never, but when I call session.Save(User), a call gets made to the database anyway. Is this how this is supposed to work? I would think that it shouldn't do an insert until I call Flush().
Edit:
I found the issue, I changed the primary key to guid and it worked. Are there any other types (i.e. no guid primary key) that will work? I would rather have a number instead of a guid... | You were using a native generator, right?
The problem with this lies in the fact that, since it's the DB that generates the ID, NHibernate needs a round trip to fetch it. As an example, for Server's identity fields the actual INSERT statement must be executed before SCOPE\_IDENTITY() returns a valid key. And the only way to perform this operation safely is by flushing the session.
As an alternative to guids and identity you can try the "increment" generator to see if it fits your needs:
<http://www.hibernate.org/hib_docs/nhibernate/1.2/reference/en/html/mapping.html#mapping-declaration-id-generator>
You should be aware that this approach won't be feasible if you cluster your app, or you have some other process or application inserting into the same table.
PS: for further reading try <http://unhandled-exceptions.com/blog/index.php/2008/12/11/on-choosing-an-identity-type/> | I found the issue, I was using an identity as the primary key. Changing it to guid worked. | NHibernate FlushMode on Save | [
"",
"c#",
"nhibernate",
""
] |
Consider the following code:
```
private static void WriteProcesses(StreamWriter sw, DateTime d) {
sw.WriteLine("List of processes @ " + d.ToString());
Process[] localAll = Process.GetProcesses().Where(o => o.ProcessName.ToLower() != "svchost");
if(localAll.Length > 0) {
for(int i = 0; i < localAll.Length; i++) {
sw.WriteLine(" " + localAll[i].ProcessName);
}
}
}
```
But i get a red squiggly line saying:
Cannot implicitly convert type System.Collections.Generic.IEnumerable' to 'System.Diagnostics.Process[]'. An explicit conversion exists (are you missing a cast?)
I tried changing the array to a List but didnt work. | Change
```
Process[] localAll = Process.GetProcesses().Where(o => o.ProcessName.ToLower() != "svchost");
```
to
```
Process[] localAll = Process.GetProcesses().Where(o => o.ProcessName.ToLower() != "svchost").ToArray();
```
`Where` is returning an `IEnumerable<Process>` on which you can call `ToArray` to convert to an array of type `Process`.
Alternatively, you can enumerate through the `IEnumerable<Process>` that `Where` returns.
```
var processes = Process.GetProcesses().Where(o => o.ProcessName.ToLower() != "svchost");
foreach (Process process in processes) {
sw.WriteLine(" " + process.ProcessName);
}
``` | I think you'd be better off to just deal with it as an IEnumerable
```
private static void WriteProcesses(StreamWriter sw, DateTime d) {
sw.WriteLine("List of processes @ " + d.ToString());
var localAll = Process.GetProcesses()
.Where(o => o.ProcessName.ToLower() != "svchost");
foreach(Process process in localAll) {
sw.WriteLine(" " + process.ProcessName);
}
}
``` | Correct use of Lambda query | [
"",
"c#",
".net",
"linq",
"lambda",
""
] |
I get the following error:
```
Unhandled Exception: System.IO.IOException: The parameter is incorrect.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.__Error.WinIOError()
at System.Console.set_OutputEncoding(Encoding value)
at (my program)
```
when I run the following line of code:
```
Console.OutputEncoding = Encoding.Unicode;
```
Any idea why? I do not get this error if I set the encoding to UTF8 instead. | Encoding.Unicode is UTF-16 which uses 2 bytes to encode all characters. The ASCII characters (English characters) are the same in UTF-8 (single bytes, same values), so that might be why it works.
My guess is that the Windows Command Shell doesn't fully support Unicode. Funny that the Powershell 2 GUI does support UTF-16 (as far as I know), but the program throws the same exception there.
The following code works which shows that the Console object can have its output redirected and support Encoding.Unicode:
```
FileStream testStream = File.Create("test.txt");
TextWriter writer = new StreamWriter(testStream, Encoding.Unicode);
Console.SetOut(writer);
Console.WriteLine("Hello World: \u263B"); // unicode smiley face
writer.Close(); // flush the output
``` | According to the list of [Code Page Identifiers on MSDN](http://msdn.microsoft.com/en-us/library/dd317756(VS.85).aspx), the UTF-16 and UTF-32 encodings are managed-only:
```
1200 utf-16 Unicode UTF-16, little endian byte order (BMP of ISO 10646); available only to managed applications
1201 unicodeFFFE Unicode UTF-16, big endian byte order; available only to managed applications
12000 utf-32 Unicode UTF-32, little endian byte order; available only to managed applications
12001 utf-32BE Unicode UTF-32, big endian byte order; available only to managed applications
```
For instance, they're not listed in the registry with the other system code pages under HKEY\_LOCAL\_MACHINE\SYSTEM\CurrentControlSet\Control\Nls\CodePage. | "The parameter is incorrect" when setting Unicode as console encoding | [
"",
"c#",
"encoding",
""
] |
I have an object not written by myself that I need to clone in memory. The object is not tagged `ICloneable` or `Serializable` so deep cloning through the interface or serialization will not work. Is there anyway to deep clone this object? A non-safe win32 API call maybe? | FYI Interfaces marked as `ICloneable` are not necessarily deep copied. It is up to the implementer to implement `ICloneable` and there is no guarantee they will have cloned it.
You say the object doesn't implement `ISerializable` but does it have the `Serializable` attribute?
Creating a deep copy via binary serialization is probably one of the easiest methods I know of, since you can clone any complex graph in 3-5 lines of code. Another option would be the `XmlSerializer` if the object can be `XmlSerialized` (You don't specify any attributes for serialization or implement interfaces however if there is an `IDictionary` interface your hosed.
Outside of that I can't really think of anything. If all the data is publicly accessible you could do your own cloning routine. If its not you can still clone it by using reflection to get set the private data. | The "deep" is the tricky bit. For a shallow copy, you could use reflection to copy the fields (assuming none are readonly, which is a big assumption) - but it would be very hard to get this to work (automatically) otherwise.
The other option is to provide the serializer yourself (and serialize to deep-clone) - a "serialization surrogate". [Here's](http://www.codeproject.com/KB/dotnet/Surrogate_Serialization.aspx) a VB example. | Can I deep clone a c# object not tagged ICloneable or Serializable? | [
"",
"c#",
"clone",
""
] |
The last I used was [weka](http://www.cs.waikato.ac.nz/ml/weka/)
. The last I heard java was coming up with an API (JDM) for it. Can anyone share their experiences with the tools. I am mostly interested in using the tools for classification/clustering (weka does a decent job here) and the tool should have good API support. | I have used Weka for text classification. It was nice. The [book](http://www.cs.waikato.ac.nz/~ml/weka/book.html) is also nice. The idea of a framework where you can keep the data representation and modify the algorithm is great. | I am using [RapidMiner](http://rapid-i.com/content/blogcategory/38/69/) (formerly YALE from Univ. of Dortmund). Its a Java-based open source tool and implements most of the popular classifier/clustering methods. And it also ships with algorithms implemented for the Weka toolkit, so there are more options there. Comes with a GUI which is quite easy to use, and a Java-based API. | What data mining application to use? | [
"",
"java",
"data-mining",
""
] |
Does anyone know of a way to issue commands to a hard drive within Java? Does Java even support this kind of hardware interaction?
For example, if I have a SCSI hard drive that I would like to inquiry, is there a pre-existing Java method to do this, or would I have to write my own?
<http://en.wikipedia.org/wiki/SCSI> has some general information on SCSI commands in case you aren't familiar. | Java doesn't support talking directly to hardware like that. However, you can use JNI to call a C/C++ function from Java that can. | Three words "JNI or JNA". I strongly recommend taking a look at the latter to see if it suits your situation, instead of just opting for JNI. | issuing hard drive commands with java | [
"",
"java",
"hard-drive",
"scsi",
""
] |
Hopefully a simple question. Take for instance a Circularly-linked list:
```
class ListContainer
{
private listContainer next;
<..>
public void setNext(listContainer next)
{
this.next = next;
}
}
class List
{
private listContainer entry;
<..>
}
```
Now since it's a circularly-linked list, when a single elemnt is added, it has a reference to itself in it's next variable. When deleting the only element in the list, entry is set to null. Is there a need to set ListContainer.next to null as well for Garbage Collector to free it's memory or does it handle such self-references automagically? | Garbage collectors which rely solely on reference counting are generally vulnerable to failing to collection self-referential structures such as this. These GCs rely on a count of the number of references to the object in order to calculate whether a given object is reachable.
Non-reference counting approaches apply a more comprehensive reachability test to determine whether an object is eligible to be collected. These systems define an object (or set of objects) which are always assumed to be reachable. Any object for which references are available from this object graph is considered ineligible for collection. Any object not directly accessible from this object is not. Thus, cycles do not end up affecting reachability, and can be collected.
See also, the Wikipedia page on [tracing garbage collectors](http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)#Tracing_garbage_collectors). | Circular references is a (solvable) problem if you rely on counting the references in order to decide whether an object is dead. No java implementation uses reference counting, AFAIK. Newer Sun JREs uses a mix of several types of GC, all mark-and-sweep or copying I think.
You can read more about garbage collection in general at [Wikipedia](http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)), and some articles about java GC [here](http://www.javaworld.com/javaworld/jw-08-1996/jw-08-gc.html) and [here](http://blogs.oracle.com/jonthecollector/entry/our_collectors), for example. | How does Java Garbage collector handle self-reference? | [
"",
"java",
"garbage-collection",
""
] |
Here the context for my question:
A common technique is to declare the parameter of a method as a Lambda expression rather than a delegate. This is so that the method can examine the expression to do interesting things like find out the names of method calls in the body of the delegate instance.
Problem is that you lose some of the intelli-sense features of Resharper. If the parameter of the method was declared as a delegate, Resharper would help out when writing the call to this method, prompting you with the x => x syntax to supply as the argument value to this method.
So... back to my question I would like to do the follow:
```
MethodThatTakesDelegate(s => s.Length);
}
private void MethodThatTakesDelegate(Func<string, object> func)
{
//convert func into expression
//Expression<Func<string, object>> expr = "code I need to write"
MethodThatTakesExpression(expr);
}
private void MethodThatTakesExpression(Expression<Func<string, object>> expr)
{
//code here to determine the name of the property called against string (ie the Length)
}
``` | Everywhere that you're using the term "lambda expression" you actually mean "expression tree".
A lambda expression is the bit in source code which is
```
parameters => code
```
e.g.
```
x => x * 2
```
Expression trees are instances of the [System.Linq.Expressions.Expression](http://msdn.microsoft.com/en-us/library/system.linq.expressions.expression.aspx) class (or rather, one of the derived classes) which represent code as data.
Lambda expressions are converted by the compiler into *either* expression trees (or rather, code which generates an expression tree at execution time) *or* delegate instances.
You can compile an instance of [LambdaExpression](http://msdn.microsoft.com/en-us/library/system.linq.expressions.lambdaexpression.aspx) (which is one of the subclasses of Expression) into a delegate, but you can't go the other way round.
In theory it *might* be possible to write such a "decompiler" based on the IL returned by [MethodBase.GetMethodBody](http://msdn.microsoft.com/en-us/library/system.reflection.methodbase.getmethodbody.aspx) in *some* situations, but currently there are various delegates which can't be represented by expression trees. An expression tree represents an *expression* rather than a *statement* or statement block - so there's no looping, branching (except conditionals), assignment etc. I believe this may change in .NET 4.0, though I wouldn't expect a decompilation step from Microsoft unless there's a really good reason for one. | I don't believe it's possible to achieve what you'd like here. From the comments in your code it looks like you are attempting to capture the name of the property which did the assignment in MethodThatTakesExpression. This requires an expression tree lambda expression which captures the contexnt of the property access.
At the point you pass a delegate into MethodThatTakesDelegate this context is lost. Delegates only store a method address not any context about the method information. Once this conversion is made it's not possible to get it back.
An example of why this is not possible is that there might not even be a named method backing a delegate. It's possible to use ReflectionEmit to generate a method which has no name whatsoever and only exists in memory. It is possible though to assign this out to a Func object. | Is it possible to cast a delegate instance into a Lambda expression? | [
"",
"c#",
"lambda",
"resharper",
"expression-trees",
""
] |
What is it best to handle pagination? Server side or doing it dynamically using javascript?
I'm working on a project which is heavy on the ajax and pulling in data dynamically, so I've been working on a javascript pagination system that uses the dom - but I'm starting to think it would be better to handle it all server side.
What are everyone's thoughts? | The right answer depends on your priorities and the size of the data set to be paginated.
**Server side pagination is best for:**
* Large data set
* Faster initial page load
* Accessibility for those not running javascript
**Client side pagination is best for:**
* Small data set
* Faster subsequent page loads
So if you're paginating for primarily cosmetic reasons, it makes more sense to handle it client side. And if you're paginating to reduce initial load time, server side is the obvious choice.
Of course, client side's advantage on subsequent page load times diminishes if you utilize Ajax to load subsequent pages. | Doing it on client side will make your user download all the data at first which might not be needed, and will remove the primary benefit of pagination.
The best way to do so for such kind of AJAX apps is to make AJAX call the server for next page and add update the current page using client side script. | Pagination: Server Side or Client Side? | [
"",
"javascript",
"pagination",
"client-side",
"server-side",
""
] |
I'm pointing the .Net command line WSDL utility that ships with Visual Studio 2005 at a web service implemented in Java (which I have no control over) and it spits out the following error:
```
WSDL : error WSDL1: Unable to cast object of type 'System.Xml.XmlElement'
to type 'System.Web.Services.Description.ServiceDescriptionFormatExtension'.
```
Yet if I point Visual Studio 2005 itself at the service via the Add Web Reference dialog it generates a proxy class for me just fine.
I'm using the WSDL utility to generate all my other service proxies just fine (though an old one does emit a bunch of warnings).
Currently I'm pointing the WSDL utility at the URLs of deployed web services. All of which were developed in Java.
I want to use the WSDL command line utility in the build process to ensure I have the most up-to-date proxy code each time I compile. | Try specifying the option **protocol [SOAP12](http://msdn.microsoft.com/en-us/library/microsoft.web.services3.soap12_properties.aspx)**
/protocol:protocol ([as show on MSDN](http://msdn.microsoft.com/en-us/library/7h3ystb6.aspx))
Specifies the protocol to implement. You can specify SOAP (default), HttpGet, HttpPost, or a custom protocol specified in the configuration file. When using the /parameters option, this value is the element and contains a string.
If that does not help then.......
Visual Studio's "Add Web Reference" calls the WSDL.exe when adding a web reference. Basically there is [no difference](http://bytes.com/groups/net-web-services/427848-wsdl-exe-vs-add-web-reference), other then the control you retain when running the [WSDL.exe](http://msdn.microsoft.com/en-us/library/7h3ystb6.aspx) command from the command line. I would suspect that one of your arguments is incorrect or different then the one Visual Studio is setting.
To test this you would need to compare the output for from the 2 different XSD files that are generated, that will give you more of a clue of what is wrong(as Klathzazt has suggested).
Good Luck | Is this an XSD File? files have dependencies. Download the dependency files and place them side/by/side with the XSD you downloaded.
I would assume visual studio may fetch dependencies.
If this doesn't solve it, please provide more details. | .Net WSDL command line utility error | [
"",
"c#",
".net",
"visual-studio-2005",
"soap",
"wsdl.exe",
""
] |
What is the proper place to explain error handling in a try-catch statement? It seems like you could put explanatory comments at either the beginning of the try block or the catch block.
```
// Possible comment location 1
try
{
// real code
}
// Possible comment location 2
catch
{
// Possible comment location 3
// Error handling code
}
``` | I usually do the following. If there's only one exception being handled, I usually don't bother since it should be self-documenting.
```
try
{
real code // throws SomeException
real code // throws SomeOtherException
}
catch(SomeException se)
{
// explain your error handling choice if it's not obvious
}
catch(SomeOtherException soe)
{
// explain your error handling choice if it's not obvious
}
``` | **"A comment is a lie"**. Work on those variable names and the general logic so you can avoid it. And if you really need to lie, do it inside the catch block. | Commenting try catch statements | [
"",
"c#",
"error-handling",
"comments",
""
] |
How can I find out which FORM an HTML element is contained within, using a simple/small bit of JavaScript? In the example below, if I have already got hold of the SPAN called 'message', how can I easily get to the FORM element?
```
<form name="whatever">
<div>
<span id="message"></span>
</div>
</form>
```
The SPAN might be nested within other tables or DIVs, but it seems too long-winded to iterate around .parentElement and work my way up the tree. Is there a simpler and shorter way?
If it wasn't a SPAN, but an INPUT element, would that be easier? Do they have a property which points back to the containing FORM? Google says no... | **The form a form element belongs to can be accessed through `element.form`.**
When the element you are using as reference is not a form element, you'd still have to iterate through the `parentElement` or use some other kind of selector.
Using prototype, you could simplify this by using [Element.up()](http://www.prototypejs.org/api/element/up):
```
$(element).up('form');
```
[Other](https://stackoverflow.com/questions/465325/finding-the-form-that-an-element-belongs-to-in-javascript#465344) [answers](https://stackoverflow.com/questions/465325/finding-the-form-that-an-element-belongs-to-in-javascript#465346) to this question have pointed out how to do the same in jQuery. | Why not just use:
```
var nodesForm = node.form;
```
?
It works on FF3, FF4, google chrome, Opera, IE9 (I tested myself) | Finding the FORM that an element belongs to in JavaScript | [
"",
"javascript",
"html",
"webforms",
""
] |
We want to be able to create log files from our Java application which is suited for later processing by tools to help investigate bugs and gather performance statistics.
Currently we use the traditional "log stuff which may or may not be flattened into text form and appended to a log file", but this works the best for small amounts of information read by a human.
After careful consideration the best bet has been to store the log events as XML snippets in text files (which is then treated like any other log file), and then download them to the machine with the appropriate tool for post processing.
I'd like to use as widely supported an XML format as possible, and right now I am in the "research-then-make-decision" phase. I'd appreciate any help both in terms of XML format and tools and I'd be happy to write glue code to get what I need.
What I've found so far:
log4j XML format: Supported by chainsaw and Vigilog.
Lilith XML format: Supported by Lilith
Uninvestigated tools:
Microsoft Log Parser: Apparently supports XML.
OS X log viewer:
plus there is a lot of tools on <http://www.loganalysis.org/sections/parsing/generic-log-parsers/>
Any suggestions? | It appears that the Lilith log viewer contains an XML-format which is well suited for dealing with the extra facilities available in logback and not only the log4j things.
It is - for now - the best bet so far :)
---
I adapted the log4j xmllayout class to logback, which works with chainsaw.
---
As I have not been able to find a suitable log viewer capable of visualizing event information (instead of just presenting all events in a table) I have for now decided to create a very terse xml layout containing machine parsable information based on the above which can then be postprocessed by the Microsoft LogParser to any format I need. | Unfortunately, I can't give you the answer you are looking for, but I would like to warn you of something to consider when logging to XML. For example:
```
<log>
<msg level="info">I'm a log message</msg>
<msg level="info">I'm another message</msg>
<!-- maybe you won't even get here -->
<msg level="fatal">My server just ate a flaming death
```
In the above snippet of a potential XML log you can see the biggest drawback of logging to XML. When a catastrophic failure happens, your log format becomes broken because it requires closing tags. However, if you are using a program that parses your primary log output, this shouldn't be too much of a problem. | Best XML format for log events in terms of tool support for data mining and visualization? | [
"",
"java",
"logging",
"visualization",
"data-mining",
"error-logging",
""
] |
It's been ages since I've written a COM dll. I've made a couple of classes now, that inherit from some COM interfaces, but I want to test it out. I know I have to put a GUID somewhere and then register it with regsvr32, but what are the steps involved?
Edit: Sorry, forgot to mention I'm using C++. | To create a new ATL COM project you can proceed as follow:
1. File/New Project
2. Visual C++/ATL/ATL Project
3. Customize it settings, and press finish when done
You have created a new dll, but it is empty, to add a COM object you can do this:
1. Project/Add Class
2. Visual C++/ATL/ATL simple object, press add
3. Give the name you want (like MyObject), and press finish to add it
If you want that an object implement an interface
1. In the class view select the object class (CMyObject)
2. Right click/Add/Implement Interface...
3. You can select which Interface will implement
1. From an .idl file already in your projects files
2. From a .tlb/.dll/.exe which have a type library embedded
3. From an object already registered
4. When done press finish
PS: It is much easier to create a new ATL project with the same name in a different folder, and add the files you have customized. The wizard does several tasks and create several customized files.
For larger projects that are difficult to add file by file, I do the same but instead of adding my files to the new project I start copying the settings from the new projects to the old one, and adding any additional file that the wizard has created and fixing headers like stdafx.h to merge the new settings.
PPS: If you want that your dll to support MFC, instead of selecting ATL Project you have to select MFC/MFC Dll. When you add the ATL Simple Object the wizard will ask to add ATL support to the project. | You need to write a function called [DllGetClassObject](http://msdn.microsoft.com/en-us/library/ms680760(VS.85).aspx) and export it. That function is responsible for allocating a "class factory", which you also have to write, and which is in turn capable of allocating instances of your COM object. It has to implement [IClassFactory](http://msdn.microsoft.com/en-us/library/ms694364(VS.85).aspx).
It's not too hard to do. The alternative is to use ATL (see xhantt's answer) which in theory does this for you, but in practice it's a real mess. Somehow it manages to encapsulate the complexity of COM inside an abstraction layer that is even more complicated. Good luck trying to move an object between DLLs for example.
But you could run the ATL wizard just to see an example of how to declare `DllGetClassObject`. Implementing `IClassFactory` is very easy - just one method that news-up an object.
Then you need to register your DLL - i.e. put keys into the registry. The `regsvr32` tool cannot do this without further help from you. You have to write and export another function called [DllRegisterServer](http://msdn.microsoft.com/en-us/library/ms682162(VS.85).aspx), which does all the hard work. All that `regsvr32` does is load the DLL, look up `DllRegisterServer` and call it.
Again, ATL has a way of implementing this for you, but it does it by reading a kind of script full of registry modification instructions, stored in an .rgs file that gets embedded into your DLL's resources. If you accidentally put any kind of syntax error into this file, the registration fails silently.
So again, you may actually find it simpler to write a few lines of code to tweak the registry yourself. [Here are the details](http://msdn.microsoft.com/en-us/library/ms680055(VS.85).aspx).
If you used C# instead, you wouldn't have any of these problems. Everything is encapsulated very cleanly. It actually works much better than C++ as a tool for developing COM objects. | How do you create a COM DLL in Visual Studio 2008? | [
"",
"c++",
"visual-studio-2008",
"com",
"dll",
"guid",
""
] |
On Unix, I can either use `\r` (carriage return) or `\b` (backspace) to overwrite the current line (print over text already visible) in the shell.
Can I achieve the same effect in a Windows command line from a Python script?
I tried the curses module but it doesn't seem to be available on Windows. | yes:
```
import sys
import time
def restart_line():
sys.stdout.write('\r')
sys.stdout.flush()
sys.stdout.write('some data')
sys.stdout.flush()
time.sleep(2) # wait 2 seconds...
restart_line()
sys.stdout.write('other different data')
sys.stdout.flush()
``` | I know this is old, but i wanted to tell my version (it works on my PC in the cmd, but not in the idle) to override a line in Python 3:
```
>>> from time import sleep
>>> for i in range(400):
>>> print("\r" + str(i), end="")
>>> sleep(0.5)
```
**EDIT:**
It works on Windows and on Ubuntu | How can I overwrite/print over the current line in Windows command line? | [
"",
"python",
"windows",
"command-line",
"overwrite",
"carriage-return",
""
] |
I have this long and complex source code that uses a RNG with a **fix** seed.
This code is a simulator and the parameters of this simulator are the random values given by this RNG.
When I execute the code in the same machine, no matter how many attempts I do the output is the same. But when I execute this code on two different machines and I compare the outputs of both the machines, they are different.
Is it possible that two different machines gives somehow different output using the same random number generator and the same seed?
The compiler version, the libraries and the OS are the same. | It is certainly possible, as the RNG may be combining machine specific data with the seed, such as the network card address, to generate the random number. It is basically implementation specific. | As they do give different results it is obviously possible that they give different results. Easy-to-answer question, next!
Seriously: without knowing the source code to the RNG itโs hard to know whether youโre observing a bug or a feature. But it sounds like the RNG in question is using a second seed from somewhere else, e.g. the current time, or some hardware-dependent value like the network cardโs MAC address. | C++. Is it possible that a RNG gives different random variable in two different machines using the same seed? | [
"",
"c++",
"gcc",
"random",
""
] |
How can i convert this to a decimal in SQL? Below is the equation and i get the answer as 78 (integer) but the real answer is 78.6 (with a decimal) so i need to show this as otherwise the report won't tally up to 100%
```
(100 * [TotalVisit1]/[TotalVisits]) AS Visit1percent
``` | ```
convert(decimal(5,2),(100 * convert(float,[TotalVisit1])/convert(float,[TotalVisits]))) AS Visit1percent
```
Ugly, but it works. | Try This:
```
(100.0 * [TotalVisit1]/[TotalVisits]) AS Visit1percent
``` | How do I calculate percentages with decimals in SQL? | [
"",
"sql",
"decimal",
"sum",
""
] |
I have a database that I used specifically for logging actions of users. The database has a few small tables that are aimed at specific types of actions. This data is rarely searched, but the rowcounts of the tables are starting to climb into multi-millions. I haven't noticed a large slow down, but I want to know if indexing the table for searching will hinder or help the performance of inserts. Inserts are performed constantly but searches don't happen so often, and the tables are just going to keep growing.
Should I create indexes on these tables? Why or why not? | This all depends on your empirical research. Take a copy of the database onto a different environment and run a profiler while running searches and inserts with and without indexes. Measure the performance and see what helps. :) | Rather than indexes, I think you should consider having no indexes on the table where you insert the rows into, and then replicate the table(s) (and possibly apply indexes) to use specifically for querying. | To Index or Not to Index | [
"",
"sql",
"indexing",
"sql-server-2000",
""
] |
I want to declare two beans and instantiate them using Spring dependency injection?
```
<bean id="sessionFactory" class="SessionFactoryImpl">
<property name="entityInterceptor" ref="entityInterceptor"/>
</bean>
<bean id="entityInterceptor" class="EntityInterceptorImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
```
But Spring throws an exception saying "FactoryBean which is currently in creation returned null from getObject"
Why is inter-dependent bean wiring not working here? Should i specify defferred property binding anywhere? | Unfortunately the way container initialization works in Spring, a bean can only be injected in another bean once it is fully initialized. In your case you have a circular dependency that prevents either bean to be initialized because they depend on each other. To get around this you can implement BeanFactoryAware in one of the beans and obtain the reference to the other bean using beanFactory.getBean("beanName"). | neesh is right, Spring doesn't do this out of the box.
Interdependent beans hint at a design problem. The "clean" way to do this is to redesign your services in such a way that there are no such odd dependencies, of course provided that you have control over the implementations. | How to wire Interdependent beans in Spring? | [
"",
"java",
"spring",
"dependency-injection",
""
] |
In PHP, we (at least the good programmers) always start general variable names with a lower-case letter, but class variables/objects with an upper-case letter to distinguish them. In the same way we start general file names with a lower case letter, but files containing Classes with an upper case letter.
E.g.:
```
<?php
$number = 123;
$string = "a string";
$colors_array = array('red', 'blue', 'red');
$Cat = New Cat();
?>
```
Are the conventions the same in Java, i.e., objects starting with upper-case, but the rest with lower case, or does everything start with lower case as I've read in other places? | Generally, all variables will start with lower case:
```
int count = 32;
double conversionFactor = 1.5d;
```
Some people like to put static constants in all case:
```
public static final double KILOGRAM_TO_POUND = 2.20462262;
```
Things get more annoying when you deal with acronyms, and there is no real standard on whether you should use:
```
HTMLHandler myHtmlHandler;
```
or
```
HTMLHandler myHTMLHandler.
```
Now, either way, note that the class names (Object, String, HTMLHandler) always start with a capital letter, but individual object variables start lowercase. | You can find the naming in the [Java Code Conventions](http://java.sun.com/docs/codeconv/html/CodeConventions.doc8.html#367).
A quick summary:
* For classes, use [upper camel case](https://en.wikipedia.org/wiki/Camel_case).
* For class members and local variables use [lower camel case](https://en.wikipedia.org/wiki/Camel_case)
* For packages, use reverse URIs, e.g., *org.acme.project.subsystem*
* For constants, use [uppercase](https://en.wiktionary.org/wiki/uppercase#Adjective). | Variable naming conventions in Java | [
"",
"java",
"naming-conventions",
"oop",
""
] |
I've just found [IPython](http://ipython.scipy.org/) and I can report that I'm in deep love. And the affection was immediate. I think this affair will turn into something lasting, like [the one I have with screen](https://stackoverflow.com/questions/431521/run-a-command-in-a-shell-and-keep-running-the-command-when-you-close-the-session#431570). Ipython and screen happen to be the best of friends too so it's a triangular drama. Purely platonic, mind you.
The reason IPython hits the soft spots with me are very much because I generally like command prompts, and especially \*nix-inspired prompts with inspiration from ksh, csh (yes, chs is a monster, but as a prompt it sport lots of really good features), bash and zsh. And IPython does sure feel like home for a \*nix prompt rider. Mixing the system shell and python is also a really good idea. Plus, of course, IPython helps a lot when solving [the Python Challenge](http://www.pythonchallenge.com/) riddles. Invaluable even.
Now, I love Vim too. Since I learnt vi back in the days there's no turning back. And I'm on Mac when I have a choice. Now I'd like to glue together my IPython + MacVim workflow. What I've done so far is that I start Ipython using:
```
ipython -e "open -a MacVim"
```
Thus when I edit from IPython it starts MacVim with the file/module loaded. Could look a bit like so:
```
In [4]: %run foo #This also "imports" foo anew
hello world
In [5]: edit foo
Editing... done. Executing edited code... #This happens immediately
hello world
In [6]: %run foo
hello SO World
```
OK. I think this can be improved. Maybe there's a way to tie IPython into MacVim too? Please share your experiences. Of course if you use TextMate or some other fav editor I'm interested too. Maybe some of the lessons are general. | I use Linux, but I believe this tip can be used in OS X too. I use [GNU Screen](http://www.gnu.org/software/screen/) to send IPython commands from Vim as recommended by [this tip](http://vim.wikia.com/wiki/IPython_integration). This is how I do it:
First, you should open a terminal and start a screen session called 'ipython' or whatever you want, and then start IPython:
```
$ screen -S ipython
$ ipython
```
Then you should put this in your .vimrc:
```
autocmd FileType python map F5 :w<CR>:!screen -x ipython -X stuff $'\%run %:p:h\n'<CR><CR>
```
Then when you hit F5, it will tell Screen to execute the command '%run file' inside the 'ipython' created previously, where file is your current buffer in Vim.
You can tweak this to execute the command you want inside IPython from Vim. For example I use this:
```
autocmd FileType python map <F5> :w<CR>:!screen -x ipython -X stuff $'\%reset\ny\n\%cd %:p:h\n\%run %:t\n'<CR><CR>
```
This executes %reset (answering yes to the prompt), then change to the directory where the current buffer in vim is located and then %run the file. This is specially useful if you have the %pdb active in IPython.
Don't forget that you need an active Screen session called 'ipython' with IPython running inside.
If you like Emacs. There is [good support](http://ipython.scipy.org/dist/ipython.el) for IPython. | This questions is stale now, but just for reference - if you're using IPython 0.11 with ZeroMQ enabled, take a look at [vim-ipython](https://github.com/ivanov/vim-ipython) (an older version of which shipped with 0.11).
Using this plugin, you can send lines or whole files for IPython to execute, and also get back object introspection and word completions
in Vim, like what you get with: `object?<enter>` and `object.<tab>` in IPython.
Take a look at two screencasts of this plugin in action on [this post](http://pirsquared.org/blog/2011/07/28/vim-ipython/). | Advice regarding IPython + MacVim Workflow | [
"",
"python",
"vim",
"ipython",
""
] |
I often want to define new 'Exception' classes, but need to have an appropriate constructor defined because constructors aren't inherited.
```
class MyException : public Exception
{
public:
MyException (const UString Msg) : Exception(Msg)
{
};
}
```
Typedefs don't work for this, because they are simply aliases, not new classes. Currently, to avoid repeating this trivial boilerplate, I use a #define which does the donkeywork.
```
#define TEXCEPTION(T) class T : public Exception \
{ \
public:\
T(const UString Msg) : Exception(Msg) {}; \
}
...
TEXCEPTION(MyException);
```
But I keep wondering if there's a better way of achieving this - maybe with templates, or some new C++0x feature | If you really want to have new classes derived from Exception, as opposed to having a template parameterized by a parameter, there is no way around writing your own constructor that just delegates the arguments without using a macro. C++0x will have the ability what you need by using something like
```
class MyException : public Exception
{
public:
using Exception::Exception;
};
```
You can read about the details of that (seem to have quite a bit of extra rules) in 12.9 "Inheriting Constructors" in the [latest draft of C++0x](http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2008/n2798.pdf).
In the meantime, i would recommend a policy based design (made small text, because the OP accepted the above, and not this policy stuff):
```
// deriving from Impl first is crucial, so it's built first
// before Exception and its Ctor can be used.
template<typename Impl>
struct ExceptionT : Impl, Exception {
// taking a tuple with the arguments.
ExceptionT(arg_types const& t = arg_types())
:Exception(Impl::Ctor(t)) { }
// taking a string. plain old stuff
ExceptionT(std::string const& s):Exception(Impl::Ctor(s)) { }
};
struct ExceptionDefImpl {
typedef boost::tuple<> arg_types;
// user defined ctor args can be done using a tuple
std::string Ctor(arg_types const& s) {
return std::string();
}
std::string const& Ctor(std::string const& s) {
return s;
}
};
// will inherit Ctor modifier from DefImpl.
struct MemoryLost : ExceptionDefImpl {
typedef boost::tuple<int> arg_types;
std::string Ctor(arg_types const& s) {
std::ostringstream os;
os << "Only " << get<0>(s) << " bytes left!";
return os.str();
}
int getLeftBytes() const { return leftBytes; }
private:
int leftBytes;
};
struct StackOverflow : ExceptionDefImpl { };
// alias for the common exceptions
typedef ExceptionT<MemoryLost> MemoryLostError;
typedef ExceptionT<StackOverflow> StackOverflowError;
void throws_mem() {
throw MemoryLostError(boost::make_tuple(5));
}
void throws_stack() { throw StackOverflowError(); }
int main() {
try { throws_mem(); }
catch(MemoryListError &m) { std::cout << "Left: " << m.getLeftBytes(); }
catch(StackOverflowError &m) { std::cout << "Stackoverflow happened"; }
}
``` | ```
// You could put this in a different scope so it doesn't clutter your namespaces.
template<struct S> // Make S different for different exceptions.
class NewException :
public Exception
{
public:
NewException(const UString Msg) :
Exception(Msg)
{
}
};
// Create some new exceptions
struct MyExceptionStruct; typedef NewException<MyExceptionStruct> MyException;
struct YourExceptionStruct; typedef NewException<YourExceptionStruct> YourException;
struct OurExceptionStruct; typedef NewException<OurExceptionStruct> OurException;
// Or use a helper macro (which kinda defeats the purpose =])
#define MAKE_EXCEPTION(name) struct name##Struct; typedef NewException<name##Struct> name;
MAKE_EXCEPTION(MyException);
MAKE_EXCEPTION(YourException);
MAKE_EXCEPTION(OurException);
// Now use 'em
throw new MyException(":(");
``` | Can I use templates instead of macros for Exception class creation? | [
"",
"c++",
"templates",
"constructor",
""
] |
I am currently playing around with the Asp.Net mvc framework and loving it compared to the classic asp.net way. One thing I am mooting is whether or not it is acceptable for a View to cause (indirectly) access to the database?
For example, I am using the controller to populate a custom data class with all the information I think the View needs to go about doing its job, however as I am passing objects to the view it also can cause database reads.
A quick pseudo example.
```
public interface IProduct
{
/* Some Members */
/* Some Methods */
decimal GetDiscount();
}
public class Product : IProduct
{
public decimal GetDiscount(){ ... /* causes database access */ }
}
```
If the View has access to the Product class (it gets passed an IProduct object), it can call GetDiscount() and cause database access.
I am thinking of ways to prevent this. Currently I am only coming up with multiple interface inheritance for the `Product` class. Instead of implementing just IProduct it would now implement `IProduct` and `IProductView`. IProductView would list the members of the class, IProduct would contain the method calls which could cause database access.
The 'View' will only know about the `IProductView` interface onto the class and be unable to call methods which cause data access.
I have other vague thoughts about 'locking' an object before it is passed to the view, but I can foresee huge scope for side effects with such a method.
So, My questions:
* Are there any best practices regarding this issue?
* How do other people using MVC stop the View being naughty and doing more to objects than they should? | Your view isn't really causing data access. The view is simply calling the GetDiscount() method in a model interface. It's the **model** which is causing data access. Indeed, you could create another implementation of IProduct which wouldn't cause data access, yet there would be no change to the view.
Model objects that do lazy loading invariably cause data access when the view tries to extract data for display.
Whether it's OK is down to personal taste and preference.
However, unless you've got a good reason for lazy loading, I'd prefer to load the data into the model object and then pass that "ready-baked" for the view to display. | > One thing I am mooting is whether or not it is acceptable for a View to cause (indirectly) access to the database?
I've often asked the same question. So many things we access on the Model in Stack Overflow Views can cause implicit database access. It's almost unavoidable. Would love to hear others' thoughts on this. | ASP.Net Mvc - Is it acceptable for the View to call functions which may cause data retrieval? | [
"",
"c#",
"asp.net-mvc",
"model-view-controller",
""
] |
I've looked at [this](https://stackoverflow.com/questions/316007/what-is-the-best-way-to-make-the-output-of-one-stream-the-input-to-another) and it wasn't much help.
I have a Ruby program that puts a question to the cmd line and I would like to write a Python program that can return an answer. Does anyone know of any links or in general how I might go about doing this?
Thanks for your help.
**EDIT**
Thanks to the guys that mentioned *piping*. I haven't used it too much and was glad it was brought up since it forced me too look in to it more. | ```
p = subprocess.Popen(['ruby', 'ruby_program.rb'], stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
ruby_question = p.stdout.readline()
answer = calculate_answer(ruby_question)
p.stdin.write(answer)
print p.communicate()[0] # prints further info ruby may show.
```
The last 2 lines could be made into one:
```
print p.communicate(answer)[0]
``` | If you're on unix / linux you can use piping:
```
question.rb | answer.py
```
Then the output of question.rb becomes the input of answer.py
I've not tried it recently, but I have a feeling the same syntax might work on Windows as well. | How do I take the output of one program and use it as the input of another? | [
"",
"python",
"ruby",
"io",
""
] |
I have a table where one column has duplicate records but other columns are distinct. so something like this
Code SubCode version status
1234 D1 1 A
1234 D1 0 P
1234 DA 1 A
1234 DB 1 P
5678 BB 1 A
5678 BB 0 P
5678 BP 1 A
5678 BJ 1 A
0987 HH 1 A
So in the above table. subcode and Version are unique values whereas Code is repeated. I want to transfer records from the above table into a temporary table. Only records I would like to transfer are where ALL the subcodes for a code have status of 'A' and I want them in the temp table only once.
So from example above. the temporary table should only have
5678 and 0987 since all the subcodes relative to 5678 have status of 'A' and all subcodes for 0987 (it only has one) have status of A. 1234 is ommited because its subcode 'DB' has status of 'P'
I'd appreciate any help! | ```
INSERT theTempTable (Code)
SELECT t.Code
FROM theTable t
LEFT OUTER JOIN theTable subT ON (t.Code = subT.Code AND subT.status <> 'A')
WHERE subT.Code IS NULL
GROUP BY t.Code
```
This should do the trick. The logic is a little tricky, but I'll do my best to explain how it is derived.
The outer join combined with the IS NULL check allows you to search for the *absence* of a criteria. Combine that with the inverse of what you're normally looking for (in this case status = 'A') and the query succeeds when *there are no rows that do not match*. This is the same as ((there are no rows) OR (all rows match)). Since we know that there are rows due to the other query on the table, all rows must match. | It's a little unclear as to whether or not the version column comes into play. For example, do you only want to consider rows with the largest version or if ANY subcde has an "A" should it count. Take 5678, BB for example, where version 1 has an "A" and version 0 has a "B". Is 5678 included because at least one of subcode BB has an "A" or is it because version 1 has an "A".
The following code assumes that you want all codes where every subcode has at least one "A" regardless of the version.
```
SELECT
T1.code,
T1.subcode,
T1.version,
T1.status
FROM
MyTable T1
WHERE
(
SELECT COUNT(DISTINCT subcode)
FROM MyTable T2
WHERE T2.code = T1.code
) =
(
SELECT COUNT(DISTINCT subcode)
FROM MyTable T3
WHERE T3.code = T1.code AND T3.status = 'A'
)
```
Performance may be abysmal if your table is large. I'll try to come up with a query that is likely to have better performance since this was off the top of my head.
Also, if you explain the full extent of your problem maybe we can find a way to get rid of that temp table... ;)
Here are two more possible methods. Still a lot of subqueries, but they look like they will perform better than the method above. They are both very similar, although the second one here had a better query plan in my DB. Of course, with limited data and no indexing that's not a great test. You should try all of the methods out and see which is best for your database.
```
SELECT
T1.code,
T1.subcode,
T1.version,
T1.status
FROM
MyTable T1
WHERE
EXISTS
(
SELECT *
FROM MyTable T2
WHERE T2.code = T1.code
AND T2.status = 'A'
) AND
NOT EXISTS
(
SELECT *
FROM MyTable T3
LEFT OUTER JOIN MyTable T4 ON
T4.code = T3.code AND
T4.subcode = T3.subcode AND
T4.status = 'A'
WHERE T3.code = T1.code
AND T3.status <> 'A'
AND T4.code IS NULL
)
SELECT
T1.code,
T1.subcode,
T1.version,
T1.status
FROM
MyTable T1
WHERE
EXISTS
(
SELECT *
FROM MyTable T2
WHERE T2.code = T1.code
AND T2.status = 'A'
) AND
NOT EXISTS
(
SELECT *
FROM MyTable T3
WHERE T3.code = T1.code
AND T3.status <> 'A'
AND NOT EXISTS
(
SELECT *
FROM MyTable T4
WHERE T4.code = T3.code
AND T4.subcode = T3.subcode
AND T4.status = 'A'
)
)
``` | grouping records in one temp table | [
"",
"sql",
""
] |
Is there a pdf library attached/that can be attached to .NET 3.5 that allows creation of pdf files at runtime i.e opening a new pdf file, writing to it line by line, embedding images, etc and closing the pdf file all in C# code?
What I want is a set of tools and specifications which allow me to implement a customised pdf writer in C# without using Reporting Services' pdf output option. | iTextSharp
<http://itextsharp.sourceforge.net/>
Complex but comprehensive.
[itext7](https://github.com/itext/itext7-dotnet) former iTextSharp | iTextSharp is no longer licensed under the MIT/LGPL license. Versions greater than 4.1.6 are licensed under the Affero GPL, meaning you can't even use it in a SaaS (Software as a Service) scenario without licensing your code under the GPL, or a GPL-compatible license.
Other opensource PDF implementations in native .NET include
* [PDF Clown](http://pdfclown.wordpress.com) (make sure you get the patches to the latest version)
* [PDFSharp](http://www.pdfsharp.net)
* [PDFJet open source edition](http://www.pdfjet.com/os/edition.html) (commercial version also available, and you will need the JDK installed to build this)
There's also a couple of Java PDF libraries (like PDFBox) you can convert to .NET using IKVM. | Creating pdf files at runtime in c# | [
"",
"c#",
"pdf",
""
] |
I'm trying to build my own inversion of control container. Right now I store the objects with their types in a dictionary and resolve a reference when asked. But I want to make it possible to resolve a reference or a new instance. I can create a new instance with the Activator class. But, what if the constructor of the object to resolve takes 1, 2 or any parameters?
For example, I want to be able to say something like:
```
Container.register<IFoo>(new Foo(Proxy));
Container.register<IBar>(new Boo(Proxy, DataThing));
```
and resolve it like
```
IFoo MyFoo = Resolver.resolve<IFoo>();
IBar MyBar = Resolver.resolve<IBar>();
```
where MyFoo gets instanciated with the given parameter *Proxy* and MyBar with *Proxy* and *DataThing*.
What does *resolve* have to do to make that happen? | I decided to split it in to methods. A Resolve, that gives back the instance stored in the container. And a Create that instanciate a new instance.
something like:
```
public T Create<T>()
{
if (registeredTypes.ContainsKey(typeof(T)))
return (T)Activator.CreateInstance(registeredTypes[typeof(T)].
GetType());
else
throw new DependencyResolverException("Can't
create type. Type " + typeof(T) + "
not found.");
}
``` | Checkout <http://funq.codeplex.com>. This is a very tiny Container that uses lambda expressions to define the function to resolve. Handles multiple parameters. | How to resolve instances with constructor parameters in custom IOC Container? | [
"",
"c#",
"dependency-injection",
"inversion-of-control",
"ioc-container",
""
] |
I'm using django and when users go to www.website.com/ I want to point them to the index view.
Right now I'm doing this:
```
(r'^$', 'ideas.idea.views.index'),
```
However, it's not working. I'm assuming my regular expression is wrong. Can anyone help me out? I've looked at python regular expressions but they didn't help me. | What you have should work (it does for me). Make sure it's in the top `urls.py`, and it should also be at the top of the list. | Just put an empty raw regular expression: r''
I tested here and it worked perfectly.
```
urlpatterns = patterns('',
url(r'', include('homepage.urls')),
)
```
Hope it help!
EDIT:
You can also put:
```
urlpatterns = patterns('',
url(r'\?', include('homepage.urls')),
)
```
The question mark makes the bar optional. | What is the regular expression for the "root" of a website in django? | [
"",
"python",
"regex",
"django",
"django-urls",
""
] |
I've some questions .. and I really need your help.
1. I have an application.
First I display a splash screen, a form, and this splash would call another form.
**Problem**: When the splash form is displayed, if I then open another application on the top of the splash, and then minimize this newly opened application window, the splash screen becomes white. How do I avoid this? I want my splash to be displayed clearly and not affected by any application.
2. I'm using a DropDownList but I realized that there is 2 types of it . I found "Dropdown" which makes the text inside the DDL editable, and "DropDownList" which doesn't.
**Problem**: when I tried to use DropDownList control it doesn't allow me to add a default text while DropDown does so I want a DropDownList control which prevent modifying on the text and allow a default text .. what property should I use?
3. Can I add "?" which denotes to Help button to the FormBorder (with the minimization, maximization, and close buttons )
4. Can I change the colour of the Formborder from its default colour (blue) ?
5. One of my application functionality is to copy files from server to phone into a certain folder in memory card.
**Problem** : can I determine the free size of the MMC to notify the user if it's full while copying. | 3) You have to set the "HelpButton" property of the form to true. However the "?" button is only visible if you deactivate the maximize and minimize buttons by setting "MinimizeBox" and "MaximizeBox" to false. | Here are a few...
1) you need to launch the window in another thread so that your app can do what it needs to do to start. When the startup finishes, signal to the splash screen that it can close itself.
2)
```
dropDownList.SelectedIndex = 0;
```
4) I would not recommend doing so. It is based on the system color scheme, which the user sets. I would not like an app to decide for itself which scheme to use. | Five Questions regarding the use of C# / VisualStudio 2005 | [
"",
"c#",
"visual-studio-2005",
""
] |
I am building a basic profiler for an open source project. One requirement is to measure execution time of a method. While this is easy enough, I have to do it without knowing the method or its containing class until runtime. The way to invoke the profiler will be when the user will invoke the profiler from the IDE in an active document. So if class1 is open and the user right clicks on the whitespace in the document, selects profile, then, and only then, is the class is known.
I have this code to use MethodInfo:
```
MethodInfo methodInfo = typeof(t).GetMethod(s);
```
T is just a generic type holder (class X where T : class, is the class signature). s is just a string of the method name.
I have this error, however:
Type name expected, but parameter name found.
The containing method of that line of code has t as a parameter of type T, but moving that out doesn't fix the issue. T is just an object, and if I provide an object name, like the class name, there is no error.
What gives?
EDIT: Maybe an activator can solve this.
Also, could I use the where clause to restrict T to be a static class only?
Thanks | Maybe you need
```
t.GetType().GetMethod(s)
``` | The error is caused because typeof expects a type name or parameter like typeof(int) or typeof(T) where T is a type parameter. It looks like t is an instance of System.Type so there is no need for the typeof.
Do you need a generic type for this? Will this not work?
```
public void DoSomething(object obj, string methodName)
{
MethodInfo method = obj.GetType().GetMethod(methodName);
// Do stuff
}
```
or
```
public void DoSomething(Type t, string methodName)
{
MethodInfo method = t.GetMethod(methodName);
// Do stuff
}
```
Also, there is no way to limit a type parameter to a static class. I'm not sure what use that would be as you cannot have an instance of it and it won't be able to implement any interfaces you can use in a generic method. | Using generics and methodinfo | [
"",
"c#",
".net",
"reflection",
""
] |
What is the best way to block certain input keys from being used in a TextBox with out blocking special keystrokes such as `Ctrl`-`V`/`Ctrl`-`C`?
For example, only allowing the user to enter a subset of characters or numerics such as A or B or C and nothing else. | I would use the keydown-event and use the e.cancel to stop the key if the key is not allowed. If I want to do it on multiple places then I would make a user control that inherits a textbox and then add a property AllowedChars or DisallowedChars that handle it for me. I have a couple of variants laying around that I use for time to time, some allowing money-formatting and input, some for time editing and so on.
The good thing to do it as a user control is that you can add to it and make it to your own killer-text-box. ;) | I used the [Masked Textbox](http://www.c-sharpcorner.com/UploadFile/jibinpan/MaskedTextBoxControl11302005051817AM/MaskedTextBoxControl.aspx) control for winforms. There's a longer explanation about it [here](http://en.csharp-online.net/MaskedTextBox). Essentially, it disallows input that doesn't match the criteria for the field. If you didn't want people to type in anything but numbers, it simply would not allow them to type anything but numbers. | Input handling in WinForm | [
"",
"c#",
"winforms",
"keyboard",
"user-input",
""
] |
I am trying to resolve Euler Problem 18 -> <http://projecteuler.net/index.php?section=problems&id=18>
I am trying to do this with c++ (I am relearning it and euler problems make for good learning/searching material)
```
#include <iostream>
using namespace std;
long long unsigned countNums(short,short,short array[][15],short,bool,bool);
int main(int argc,char **argv) {
long long unsigned max = 0;
long long unsigned sum;
short piramide[][15] = {{75,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
{95,64,0,0,0,0,0,0,0,0,0,0,0,0,0},
{17,47,82,0,0,0,0,0,0,0,0,0,0,0,0},
{18,35,87,10,0,0,0,0,0,0,0,0,0,0,0},
{20,4,82,47,65,0,0,0,0,0,0,0,0,0,0},
{19,1,23,75,3,34,0,0,0,0,0,0,0,0,0},
{88,2,77,73,7,63,67,0,0,0,0,0,0,0,0},
{99,65,4 ,28,6,16,70,92,0,0,0,0,0,0,0},
{41,41,26,56,83,40,80,70,33,0,0,0,0,0,0},
{41,48,72,33,47,32,37,16,94,29,0,0,0,0,0},
{53,71,44,65,25,43,91,52,97,51,14,0,0,0,0},
{70,11,33,28,77,73,17,78,39,68,17,57,0,0,0},
{91,71,52,38,17,14,91,43,58,50,27,29,48,0,0},
{63,66,4,68,89,53,67,30,73,16,69,87,40,31,0},
{4,62,98,27,23,9,70,98,73,93,38,53,60,4,23}};
for (short i = 0;i<15;i++) {
for (short m=0;m<15;m++) {
if (piramide[i][m] == 0)
break;
sum = countNums(i,m,piramide,15,true,true);
if (sum > max)
max = sum;
sum = countNums(i,m,piramide,15,true,false);
if (sum > max)
max = sum;
sum = countNums(i,m,piramide,15,false,true);
if (sum > max)
max = sum;
sum = countNums(i,m,piramide,15,false,false);
if (sum > max)
max = sum;
}
}
cout << max;
return 0;
}
long long unsigned countNums(short start_x,short start_y,short array[][15],short size, bool goright,bool goright2) {
long long unsigned currentSum;
currentSum = array[start_x][start_y];
if (goright) { //go right
if ((start_x + 1) < size)
start_x++;
if ((start_y + 1) < size)
start_y++;
}
else //go down
if ((start_x + 1) < size)
start_x++;
if (goright2) { //still going right
for (short i = start_x, m = start_y;i< size && m < size;i++,m++) {
currentSum += array[i][m];
}
}
else { //still going down
for (short i = start_x;i<size;i++) {
currentSum += array[i][start_y];
}
}
return currentSum;
}
```
The countNums function is used to go either down or diagonally.
I have tested this function like so:
```
short a = 0;
short b = 0;
cout << countNums(a,b,piramide,15,true,true) << endl;
cout << countNums(a,b,piramide,15,true,false) << endl;
cout << countNums(a,b,piramide,15,false,true) << endl;
cout << countNums(a,b,piramide,15,false,false) << endl;
return 0;
```
And it does work (I also changed the function a little so it would print every number it was going through)
But I still don't get the right result. This goes down and to the right and still goes right (adjacent numbers to the right), goes down and keeps going down (adjacent number to the left).
What am I doing wrong here, anyone?
---
Alastair: It's simple
long long unsigned countNums(short start\_x,short start\_y,short array[][15],short size, bool goright,bool goright2);
start\_x and start\_y are the coords of the array
array is the reference to the array
size is just the size of the array (it's always 15)
goright is to know if I am going to go down and right or just down
goright2 is to know if I am going to continue to go down or going left | Ok so first off, I'm a little unclear as to what you think the problem is. I can't parse that second-last sentence at all...
Secondly you might want to re-think your design here. Think about functions that perform a single discrete task and are not intertwined with the rest of the application (ie read up on "tightly coupled and loosely bound"). For me a big warning bell here is the presence of a overly-generic function name `countNums` with a long list of arguments.
I think if you were to divide the problem into smaller, more easily comprehensible, chunks you might find the problems a lot easier to find. I know the approach that I would take here but I'm assuming the whole point of the exercise is to help you practice your programming skills, so I'll just leave it at that... | I've solved this problem. Given the nature of Project Euler is to solve the problem on your own ("photocopying a solved crossword puzzle doesn't mean you solved it") and that I don't want to ruin this for someone else, all I can really say is that your solution looks overly complex.
You can, however, solve this problem as you're reading the file. Solve it this way and problem #69 will be a breeze!
Good luck! | Triangle problem | [
"",
"c++",
"puzzle",
""
] |
I am asking about the best tool that you used before to convert a c# windows forms application into asp.net?
I already [googled](http://www.google.com/search?q=convert+windows+forms+into+asp.net&rls=com.microsoft:en-us&ie=UTF-8&oe=UTF-8&startIndex=&startPage=1) about this topic and found alot of tools but I want someone to recommend the best one based on his usage. | I really wouldn't recommend using a tool to do the conversion. Web applications and WinForms are fundamentally different, and should be *designed* differently. Even with the vast amount of Ajax kicking around these days, you still need to bear in mind the whole stateless HTTP model.
If you don't want to rethink the application, you might want to look into converting it to Silverlight 2.0 instead... | [@Jon Skeet](https://stackoverflow.com/questions/412763/convert-windows-forms-application-into-asp-net#412774) has the best advice. That said, let's examine the results of the Google link you provided. What would happen?
The majority of the on-topic (for the query) results are other programmers asking essentially the same question -- and getting essentially the same answer. Indeed, I only see one tool for this: A sample from [CodeProject](http://www.codeproject.com/KB/cs/winforms2webforms.aspx). In this tool, not only are the generated UIs barren and ugly, but there is the following big disclaimer:
> Please note that it is not the
> intention of this article or the
> accompanying code sample to achieve a
> complete conversion between Windows
> Forms and Web Forms including all
> events and business logic. Due to the
> fundamentally different nature of the
> two programming models, this would be
> a fruitless attempt. Rather, we are
> targeting the user interface
> components themselves, mapping Windows
> Forms controls to appropriate Web
> Forms counterparts.
And therein lies the real rub: All it's doing is generating a (very rudimentary) UI based on your existing UI. All code, logic, flow and even navigation is up to you.
Bottom line: The reason there's isn't a tool that pops up front and center is because such a tool would be nigh-impossible to write, and would churn out (most likely) un-navigable, non-functional sites. While WinForms and WebForms, programmatically, look similar, they are actually quite different under the hood. No tool will be able to generate an entire site for you from nothing but a WinForms app -- the models are more dissimilar than they might appear.
At the end of the day, the best way to take a WinForms app and web-enable it is to have written said app such that all the business logic is encapsulated in its own DLL (or set thereof), and use those DLLs to drive the back-end of a new-from-scratch site. That way all you're developing is the front end and display support. | Convert Windows Forms application into Asp.net | [
"",
"c#",
"asp.net",
"winforms",
""
] |
We wrote a small Windows class library that implements extension methods for some standard types (strings initially). I placed this in a library so that any of our projects would be able to make use of it by simply referencing it and adding using XXX.Extensions.
A problem came up when we wanted to use some of these methods in Silverlight. Although all the code was compatible, a Windows library can't be referenced in Silverlight so we created a Silverlight library that had links to the same class files and put compiler directives into the classes to allow different using declarations and namespaces. This worked fine until today when I added a new class to the Windows extensions library and realised that I would have to remember to link the class into the Silverlight library too.
This isn't ideal and I wondered if anyone might have ideas for a better way of sharing extension methods and other helper code between Windows and Silverlight projects. | You cannot set a reference from a Silverlight assembly to a regular .NET assembly but you can do so the other way round.
So create a shared Silverlight assembly and add your code to that assembly. Now you can set a reference fro both your regular .NET and you other Silverlight assembly to the shared Silverlight assembly.
The restriction is that you can only put code in there that would work on both the .NET and Silverlight CLR but that is no different from sharing code. | Since this question has been answered, there is a new solution from Microsoft, [Portable Class Libraries](http://msdn.microsoft.com/en-us/library/gg597391.aspx). [Here](http://blogs.msdn.com/b/bclteam/archive/2011/01/19/announcing-portable-library-tools-ctp-justin-van-patten.aspx) is the blog post where they announced it.
I'm just about to start playing round with them for sharing code between silverlight and some server side code I'm writing, so can't add too much past the links at the moment. | Sharing C# code between Windows and Silverlight class libraries | [
"",
"c#",
"windows",
"silverlight",
"sharing",
""
] |
I'd like to be able to replace things in a file with a regular expression using the following scheme:
I have an array:
```
$data = array(
'title' => 'My Cool Title',
'content' => ''
)
```
I also have a template (for clarity's sake, we'll assume the below is assigned to a variable *$template*)
```
<html>
<title><% title %></title>
<body><% content %></body>
</html>
```
I'd like to be able to use one regular expression to do the whole thing, so it can be as general as possible; The following is my stab at it (which doesn't work)
```
$endMarkup = preg_replace('/<% ([a-z]+) %>/',$data["\\1"], $template);
```
Is there a clean solution for putting associative array data into a template by array index? | With a little work before hand you can do it with a single `preg_replace` call:
```
$replacements = array();
foreach ($data as $search => $replacement) {
$replacements["/<% $search %>/"] = $replacement;
}
$endMarkup = preg_replace(
array_keys($replacements),
array_values($replacements),
$template);
``` | You could try without regex if you wanted to. The function str\_replace was made for this. If you don't understand regex this will be the best option for you.
Test data:
```
$data = array(
'title' => 'My Cool Title',
'content' => ''
);
$file = <<< EOF
<html>
<title><% title %></title>
<body><% content %></body>
</html>
EOF;
```
Function and example:
```
function replace_template($template, $data)
{
$replace = array_fill(0, count($data), '<%% %s %%>');
$keys = array_map('sprintf', $replace, array_keys($data));
$output = str_replace($keys, $data, $template);
return $output;
}
echo replace_template($file, $data);
``` | Super Basic Templating System | [
"",
"php",
"templates",
""
] |
I have a Python script which takes as input a list of integers, which I need to work with four integers at a time. Unfortunately, I don't have control of the input, or I'd have it passed in as a list of four-element tuples. Currently, I'm iterating over it this way:
```
for i in range(0, len(ints), 4):
# dummy op for example code
foo += ints[i] * ints[i + 1] + ints[i + 2] * ints[i + 3]
```
It looks a lot like "C-think", though, which makes me suspect there's a more pythonic way of dealing with this situation. The list is discarded after iterating, so it needn't be preserved. Perhaps something like this would be better?
```
while ints:
foo += ints[0] * ints[1] + ints[2] * ints[3]
ints[0:4] = []
```
Still doesn't quite "feel" right, though. :-/
**Update:** With the release of Python 3.12, I've changed the accepted answer. For anyone who has not (or cannot) make the jump to Python 3.12 yet, I encourage you to check out the [previous accepted answer](https://stackoverflow.com/questions/434287#answer-434411) or any of the other excellent, backwards-compatible answers below.
Related question: [How do you split a list into evenly sized chunks in Python?](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python) | As of Python 3.12, [the `itertools` module gains a `batched` function](https://docs.python.org/3.12/library/itertools.html#itertools.batched) that specifically covers iterating over batches of an input iterable, where the final batch may be incomplete (each batch is a `tuple`). Per the example code given in the docs:
```
>>> for batch in batched('ABCDEFG', 3):
... print(batch)
...
('A', 'B', 'C')
('D', 'E', 'F')
('G',)
```
---
**Performance notes:**
[The implementation of `batched`](https://github.com/python/cpython/blob/cfa517d5a68bae24cbe8d9fe6b8e0d4935e507d2/Modules/itertoolsmodule.c#L184), like all `itertools` functions to date, is at the C layer, so it's capable of optimizations Python level code cannot match, e.g.
* On each pull of a new batch, it proactively allocates a `tuple` of precisely the correct size (for all but the last batch), instead of building the `tuple` up element by element with amortized growth causing multiple reallocations (the way a solution calling `tuple` on an `islice` does)
* It only needs to look up the `.__next__` function of the underlying iterator once per batch, not `n` times per batch (the way a `zip_longest((iter(iterable),) * n)`-based approach does)
* The check for the end case is a simple C level `NULL` check (trivial, and required to handle possible exceptions anyway)
* Handling the end case is a C `goto` followed by a direct `realloc` (no making a copy into a smaller `tuple`) down to the already known final size, since it's tracking how many elements it has successfully pulled (no complex "create sentinel for use as `fillvalue` and do Python level `if`/`else` checks for each batch to see if it's empty, with the final batch requiring a search for where the `fillvalue` appeared last, to create the cut-down `tuple`" required by `zip_longest`-based solutions).
Between all these advantages, it should *massively* outperform any Python-level solution (even [highly optimized ones that push most or all of the per-item work to the C layer](https://stackoverflow.com/a/34935239/364696)), regardless of whether the input iterable is long or short, and regardless of whether the batch size and the size of the final (possibly incomplete) batch ([`zip_longest`-based solutions using guaranteed unique `fillvalue`s for safety](https://stackoverflow.com/a/34935239/364696) are the best possible solution for almost all cases when `itertools.batched` is not available, but they can suffer in pathological cases of "few large batches, with final batch mostly, not completely, filled", especially pre-3.10 when `bisect` can't be used to optimize slicing off the `fillvalue`s from `O(n)` linear search down to `O(log n)` binary search, but `batched` avoids that search entirely, so it won't experience pathological cases at all). | ```
def chunker(seq, size):
return (seq[pos:pos + size] for pos in range(0, len(seq), size))
```
Works with any sequence:
```
text = "I am a very, very helpful text"
for group in chunker(text, 7):
print(repr(group),)
# 'I am a ' 'very, v' 'ery hel' 'pful te' 'xt'
print('|'.join(chunker(text, 10)))
# I am a ver|y, very he|lpful text
animals = ['cat', 'dog', 'rabbit', 'duck', 'bird', 'cow', 'gnu', 'fish']
for group in chunker(animals, 3):
print(group)
# ['cat', 'dog', 'rabbit']
# ['duck', 'bird', 'cow']
# ['gnu', 'fish']
``` | How to iterate over a list in chunks | [
"",
"python",
"list",
"loops",
"optimization",
"chunks",
""
] |
I want to get myself into programming some serious GUI based applications, but when I look at things like Swing/SWT from Java, I can't help but HATE programming a GUI interface by creating "widget" objects and populating them and calling methods on them.
I think GUI design should be done in a separate text-based file in some markup format, which is read and rendered (e.g. HTML), so that the design of the interface is not tightly coupled with the rest of the code.
I've seen [HTMLayout](http://www.terrainformatica.com/htmlayout/) and I love the idea, but so far it seems be only in C++.
I'm looking for a python library (or even a WIP project) for doing markup-based gui.
**UPDATE**
The reason I can't accept QT's xml is the same reason I hate the programatic approach; you're assembling each widget separately, and specifying each property of it on a separate line. It doesn't provide any advantage over doing it the programatic way. | You can try Mozilla's XUL. It supports Python via XPCOM.
See this project: [pyxpcomext](http://pyxpcomext.mozdev.org/no_wrap/tutorials/pyxulrunner/python_xulrunner_about.html)
XUL isn't compiled, it is packaged and loaded at runtime. Firefox and many other great applications use it, but most of them use Javascript for scripting instead of Python. There are one or 2 using Python though. | You should look into Qt, which you can use from Python using the excellent PyQt interface (why they didn't name it QtPy --- cutiepie, get it ? --- I will never understand).
With Qt, you can have the choice of constructing your GUI's programmatically (which you don't want), or using XML markup. This XML file can either be compiled to code beforehand, or loaded with a short command. The latter is the normal way to work using PyQt.
Qt is versatile, high-quality, cross-platform, and you're likely using it already without knowing it. The official Skype client application is written in Qt if I remember correctly.
**Edit:** Just adding some links so the OP get get some feel for it ...
* [Short intro to Qt programming with C++](http://sector.ynet.sk/qt4-tutorial/my-first-qt-gui-application.html) -- notice the use of the Qt Designer, which outputs .ui files, which is an XML format which I remember was also quite easy to work with by hand. PyQt programming is very similar, except for being in a much easier programming language of course :-)
* [Info about PyQt on the Python wiki](http://wiki.python.org/moin/PyQt4)
* [Online book on PyQt programming](http://www.commandprompt.com/community/pyqt/) | Markup-based GUI for python | [
"",
"python",
"user-interface",
"markup",
""
] |
I'm not quite sure when selecting only a certain number of rows would be better than simply making a more specific select statement. I have a feeling I'm missing something pretty straight forward but I can't figure it out. I have less than 6 months experience with any SQL and it's been cursory at that so I'm sorry if this is a really simple question but I couldn't find a clear answer. | I know of two common uses:
Paging : be sure to specify an ordering. If an ordering isn't specified, many db implementations use whatever is convenient for executing the query. This "optimal" ordering behavior could give very unpredictable results.
```
SELECT top 10 CustomerName
FROM Customer
WHERE CustomerID > 200 --start of page
ORDER BY CustomerID
```
Subqueries : many places that a subquery can be issued require that the result is a single value. top 1 is just faster than max in many cases.
```
--give me some customer that ordered today
SELECT CustomerName
FROM Customer
WHERE CustomerID =
(
SELECT top 1 CustomerID
FROM Orders
WHERE OrderDate = @Today
)
``` | Custom paging, typically. | When is the proper time to use the SQL statement "SELECT [results] FROM [tables] WHERE [conditions] FETCH FIRST [n] ROWS ONLY" | [
"",
"sql",
"select",
""
] |
I am in need of a popupwindow with the option of a radio button. I have tested with [Impromtu](http://en.wikipedia.org/wiki/Impromptu_%28programming_environment%29). Is any easy made Popupwindow plugin available?
My plugin should work in Internetย Explorer, Mozilla and Google Chrome. What would some sample code be? | [jqModal](http://dev.iceburg.net/jquery/jqModal/) is great and easy-to-use for building Modal Popups and the like.
If you want a tutorial on how to build one yourself without jQuery, check out [this tutorial](http://slayeroffice.com/code/custom_alert/). | Check out [Thickbox](http://jquery.com/demo/thickbox/)! You can use a div or so on your page as content (see inline content demo). | PopupWindow in jQuery | [
"",
"javascript",
"jquery",
"popupwindow",
""
] |
I'm having some problems getting my object to gracefully fail out if an invalid parameter is given during instantiation. I have a feeling it's a small syntax thing somewhere that I simply need fresh eyes on. Any help is more than appreciated.
```
class bib {
protected $bibid;
public function __construct($new_bibid) {
if(!$this->bibid = $this->validate_bibid($new_bibid)) {
echo 'me';
return false;
}
//carry on with other stuff if valid bibid
}
private static function validate_bibid($test_bibid) {
//call this method every time you get a bibid from the user
if(!is_int($test_bibid)) {
return false;
}
return (int)$test_bibid;
}
}
```
Note that I have an 'echo me' line in there to demonstrate that it is in fact, returning false. The way that I'm calling this in my PHP is as follows:
```
if(!$bib=new bib('612e436')) {
echo 'Error Message';
} else {
//do what I intend to do with the object
}
```
This outputs the me from above, but then continues on into the else block, doing what I intend to do with a valid object.
Can anyone spot anything I'm doing wrong in there?
Thanks! | You can't return in a constructor in PHP - the object is still created as normal.
You could use a factory or something similar;
```
if(!$bib = Bib_Factory::loadValidBib('612e436')){
echo 'Error Message';
} else {
//do what I intend to do with the object
}
```
Or throw an exception in the constructor and use a try catch instead of the if statement. | I see several problems in this code.
* First of all, I think you want to do something like this:
$myBib=new bib();
if($myBib->validate\_bibid('612e436'))
{ ..do stuff.. }
(or something similar)
remember that \_\_construct is not a normal method. It's a constructor, and it shouldn't return anything. It already implicitly returns a reference to the new instance that you've made.
* Second, your validate\_bibid returns either a boolean or an integer. You won't get immediate problems with that, but I personally don't like the style.
* Third, you've declared a protected member $bibid, but you don't set or reference it anywhere. I'd expect it to be set in the constructor for example. After that you can just call validate\_bibid without any argument.
This piece of code is obviously confusing you because it has some weird constructs and therefore doesn't behave in a normal way. I'd suggest to rethink and rewrite this piece from scratch.
**Update:**
Another issue:
I don't think this line does what you think it does:
```
if(!$this->bibid = $this->validate_bibid($new_bibid)) {
```
You probably mean this:
```
if(!$this->bibid == $this->validate_bibid($new_bibid)) {
// Or even better:
if($this->bibid <> $this->validate_bibid($new_bibid)) {
``` | Class Instantiation Fails | [
"",
"php",
"oop",
"class",
""
] |
I am inserting the HTML response from an AJAX call into my page, but then when I try to access those elements after they have been created, it fails..
This is how i retrieve and insert the HTML:
```
$.ajax({url: 'output.aspx',
data: 'id=5',
type: 'get',
datatype: 'html',
success: function(outData) {$('#my_container').html(outData);}
})
```
The outcome HTML, which is inserted into the `<div>` (id = `my_container`) looks like:
```
<div id="my_container">
<ul>
<li id="578" class="notselected">milk</li>
<li id="579" class="notselected">ice cream</li>
<li id="580" class="selected">chewing gum</li>
</ul>
</div>
```
...and afterwards, when I try to access any of the `<li>` elements using queries like:
`$('#my_container li:first')` or
`$('#my_container ul:first-child')` or similar, nothing gets selected.
I am using the [Listen plugin](http://plugins.jquery.com/project/Listen) to detect any click events on the `<li>`elements and it works... But i couldn't figure out how to detect if the div is populated with the output HTML and accordingly change one of the `<li>`'s class for example...
`$(document).ready` does not work either...
Imagine I need to change the css style of the second `<li>`.. what is the solution to this? | How are you checking to see whether your AJAX call has completed? Because it's asynchronous, the elements will not, of course, be available to the code which executes immediately after your `$.ajax(โฆ)` call.
Try manipulating those elements from within the `success` function or in other code which is called from there โ at that point, you will know that the content is available. | Are you sure your actual request is successful? If nothing is selected, the most probably reason is that nothing was actually inserted into #my\_container in the first place. | Access DOM elements after ajax.load | [
"",
"javascript",
"jquery",
"dom",
"client-side",
""
] |
I have a reference-type variable that is `readonly`, because the reference never change, only its properties. When I tried to add the `volatile` modifier to it the compiled warned me that it wouldn't let both modifiers apply to the same variable. But I think I need it to be volatile because I don't want to have caching problems when reading its properties. Am I missing anything? Or is the compiler wrong?
**Update** As Martin stated in one of the comments below: Both readonly and volatile modifiers apply only to the reference, and not to the object's properties, in the case of reference-type objects. That is what I was missing, so the compiler is right.
```
class C
{
readonly volatile string s; // error CS0678: 'C.s': a field cannot be both volatile and readonly
}
``` | Neither the `readonly` nor `volatile` modifiers are penetrative. They apply to the reference itself, not the object's properties.
The `readonly` keyword assertsโand enforcesโthat a *variable* cannot change after initialization. The variable is the small chunk of memory where the reference is stored.
The `volatile` keyword tells the compiler that the contents of a variable might be changed by multiple threads. This prevents the compiler from using optimizations (such as reading the variable's value into a register and using that value over several instructions) that might cause problems with concurrent access. Again, this only affects the small chunk of memory where the reference is stored.
Applied this way, you can see that they are indeed mutually exclusive. If something is readonly (can only be written to once, at initialization or construction), then it can't also be volatile (can be written to at any time by multiple threads).
---
As for your concern about caching issues, IIRC, there are pretty strict rules about when the compiler can cache the result of a property call. Keep in mind that it **is** a method call, and it's a pretty heavy optimization (from the compiler's stand-point) to cache its value and skip calling it again. I don't think it's something you need to concern yourself with overly much. | A readonly field can only be written when the object is first constructed. Therefore there won't be any caching issue on the CPU because the field is immutable and can't possibly change. | Why readonly and volatile modifiers are mutually exclusive? | [
"",
"c#",
".net",
"multithreading",
"readonly",
"volatile",
""
] |
I am getting an undefined index on my config page and it reads:
> **Notice**: Undefined index: SERVER\_ADDR in **inc/config
> .inc.php** on line **3**
Any idea on how I can fix that? I know its warning, but would still like to get at it. I am using it to check for the address whether to use my local or remote config settings.
I am using it in this context:
```
if ($_SERVER['SERVER_ADDR'] == '127.0.0.1' || $_SERVER['SERVER_NAME'] == 'localhost') {
}
``` | If you haven't done so, make sure you're accessing SERVER\_ADDR using the $\_SERVER array to obtain the value of SERVER\_ADDR, which is an element of this array.
```
$_SERVER['SERVER_ADDR'];
```
If that doesn't work, it may mean that your server doesn't provide that information.
From [PHP.net](http://ca.php.net/manual/en/reserved.variables.server.php "PHP.net"):
> There is no guarantee that every web server will provide any of these; servers may omit some, or provide others not listed here.
Hope that helps. | The accepted answer is correct, but take note that on Windows IIS 7 (and above, to the best of my knowledge) you must use:
```
$_SERVER['LOCAL_ADDR']
```
instead of
```
$_SERVER['SERVER_ADDR']
``` | SERVER_ADDR undefined index | [
"",
"php",
""
] |
Is there a way to check if a ValidationSummary control has its IsValid property set to true using Javascript in the OnClientClick event of a button?
What I'm trying to do is to show a message that says "please wait while your file is uploading" on an upload page, but if I use javascript to show that message, it shows up even when the ValidationSummary has errors, so the message shows up along with the errors underneath, which confuses users. | In case others need something like this, here is my solution:
In the button's OnClientClick event, I'm calling a javascript function called showContent(). In this function, I use setTimeout to call a second function that checks the page's IsValid property:
```
function showContent()
{
setTimeout("delayedShow()", 1);
}
function delayedShow()
{
if (Page_IsValid != null && Page_IsValid == true)
{
document.getElementById('divUploading').style.display = "block";
}
}
```
The `Page_IsValid` returns true in the `OnClientClick` event because the javascript validation runs after this, so the 1 second delay allows the IsValid property to be properly set. | If you have several validation groups on single page then you should check only certain group:
```
var isValid = Page_ClientValidate('GroupName');
``` | Check if ValidationSummary is Valid using OnClientClick | [
"",
"asp.net",
"javascript",
"validation",
"upload",
""
] |
It's quite some time that I'm trying to figure out this problem and from googling around many people have similar problems.
I'm trying to model a User in a Social Network, using Hibernate, and what is more basic to a social network than to map a friendship relation?
Every user in the system should have a list of it's friends and I thought that this might be an incredibly easy task (just use a ManyToMany relation, right?). So I went on to try the following:
```
@Entity
@Table(name="users")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="userid")
protected Long id = null;
@ManyToMany
protected List<User> friends = null
}
```
The problem now is that it tells me I use ManyToMany wrongly by having no clear distinction between friend and befriended. So far so good, I get the error, but how can I do what I want?
Any idea? I've reached the end of my wisdom. | The fact about Many to Many is that it needs a little more configuration, because its imperative that Hibernate generates a relation table.
Try this:
```
@Entity
@Table(name="users")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="userid")
protected Long id = null;
@ManyToMany
@JoinTable(name = "user_friends",
joinColumns = @JoinColumn(name = "user_id"),
inverseJoinColumns = @JoinColumn(name = "friend_id"))
protected List friends = null;
@ManyToMany(mappedBy = "friends")
protected List befriended = null;
}
```
Hope it works =)
EDIT: Also, be very careful with fetch types... you can enter an user fetching out-of-control loop and get all the DB. | The `ManyToMany` annotation has a mappedBy parameter. I guess something like
```
@ManyToMany(mappedBy = "friends")
```
might work. In any case, see the [docs](http://www.hibernate.org/hib_docs/annotations/reference/en/html_single/#eentity-mapping-association-collection-manytomany).
Edit:
It seems as if a many to many relationship needs to be accessible from both ends. Currently yours is only accessible from one end. Maybe you should add the other relation as well:
```
@Entity
@Table(name="users")
public class User {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="userid")
protected Long id = null;
@ManyToMany
protected List<User> friends = null;
@ManyToMany(mappedBy = "friends")
protected List<User> befriended = null;
}
```
If that doesn't work you can always introduce a separate class representing the relation between two users, and let every user have a collection of instances of this class. | Hibernate: Mapping User-Friends relation in Social Networks | [
"",
"java",
"hibernate",
"annotations",
"hibernate-mapping",
""
] |
before posting the whole code, i wanted to make sure I am not missing a simple issue here.
```
var dv = $(myElement);
var pos = dv.offset();
var width = dv.width();
var height = dv.height();
alert(pos);
alert(width);
alert(height);
```
here, width alerts fine, height alerts fine but offset alerts [object Object] (in firefox)
am I missing something here? | that's correct: the `offset()` function returns an object containing two properties, `left` and `top`. (See [the docs](http://docs.jquery.com/CSS/offset)). "[object Object]" is how most objects are converted to strings.
I'd suggest you install Firebug to help you with debugging Javascript like this as it would give you much better information about the variables. | Please also test with console.log() rather then alert() | jQuery offset doesn't produce value | [
"",
"javascript",
"jquery",
"css",
""
] |
In his The C++ Programming Language Stroustrup gives the following example for inc/dec overloading:
```
class Ptr_to_T {
T* p;
T* array ;
int size;
public:
Ptr_to_T(T* p, T* v, int s); // bind to array v of size s, initial value p
Ptr_to_T(T* p); // bind to single object, initial value p
Ptr_to_T& operator++(); // prefix
Ptr_to_T operator++(int); // postfix
Ptr_to_T& operator--(); // prefix
Ptr_to_T operator--(int); // postfix
T&operator*() ; // prefix
}
```
Why prefix operators return by reference while postfix operators return by value?
Thanks. | To understand better, you have to imagine (or look at) how are these operators implemented. Typically, the prefix operator++ will be written more or less like this:
```
MyType& operator++()
{
// do the incrementation
return *this;
}
```
Since `this` has been modified "in-place", we can return a reference to the instance in order to avoid a useless copy.
Now, here's the code for the postfix operator++:
```
MyType operator++(int)
{
MyType tmp(*this); // create a copy of 'this'
++(*this); // use the prefix operator to perform the increment
return tmp; // return the temporary
}
```
As the postfix operator returns a temporary, it has to return it by value (otherwise, you'll get a dangling reference).
The [C++ Faq Lite](http://www.parashift.com/c++-faq-lite/operator-overloading.html#faq-13.14) also has a paragraph on the subject. | The postfix operator returns a copy of the value before it was incremented, so it pretty much has to return a temporary. The prefix operator does return the current value of the object, so it can return a reference to, well, its current value. | overloaded increment's return value | [
"",
"c++",
"operator-overloading",
""
] |
After peeking around the internet it looks like it is possible to interop between C# and Matlab. I am wondering if anyone has had success with it and what they did to do so. If possible somehow pulling it off without the use of COM. Thanks for your time. | Yes, quite possible. Though I ended up using the C interface and calling into that using a mixed-mode DLL (and getting C# to call into that... but that was because I was also interfacing with some other C code). It's quite straightforward. On computers where you want to run your program, you'll need to install Matlab Runtime MCRInstaller.exe.
edit: removed broken link | Beginning with the R2009a release of MATLAB, .NET objects can be accessed from MATLAB:
<http://www.mathworks.com/help/techdoc/matlab_external/brpb5k6.html>
In older versions of MATLAB, it is possible to access .NET objects from MATLAB using CCW:
<http://www.mathworks.com/support/solutions/data/1-5U8HND.html?solution=1-5U8HND>
and the MATLAB engine from .NET:
<http://www.mathworks.com/access/helpdesk/help/techdoc/index.html?/access/helpdesk/help/techdoc/matlab_external/f135590.html#f135616>
You can also use the MATLAB Builder NE to wrap m-code into .NET assemblies.
<http://www.mathworks.com/products/netbuilder/> | Interoperating between Matlab and C# | [
"",
"c#",
".net",
"matlab",
"interop",
"matlab-deployment",
""
] |
SQLAlchemy's `DateTime` type allows for a `timezone=True` argument to save a non-naive datetime object to the database, and to return it as such. Is there any way to modify the timezone of the `tzinfo` that SQLAlchemy passes in so it could be, for instance, UTC? I realize that I could just use `default=datetime.datetime.utcnow`; however, this is a naive time that would happily accept someone passing in a naive localtime-based datetime, even if I used `timezone=True` with it, because it makes local or UTC time non-naive without having a base timezone to normalize it with. I have tried (using [pytz](http://pytz.sourceforge.net/)) to make the datetime object non-naive, but when I save this to the DB it comes back as naive.
Note how datetime.datetime.utcnow does not work with `timezone=True` so well:
```
import sqlalchemy as sa
from sqlalchemy.sql import select
import datetime
metadata = sa.MetaData('postgres://user:pass@machine/db')
data_table = sa.Table('data', metadata,
sa.Column('id', sa.types.Integer, primary_key=True),
sa.Column('date', sa.types.DateTime(timezone=True), default=datetime.datetime.utcnow)
)
metadata.create_all()
engine = metadata.bind
conn = engine.connect()
result = conn.execute(data_table.insert().values(id=1))
s = select([data_table])
result = conn.execute(s)
row = result.fetchone()
```
> (1, datetime.datetime(2009, 1, 6, 0, 9, 36, 891887))
```
row[1].utcoffset()
```
> datetime.timedelta(-1, 64800) # that's my localtime offset!!
```
datetime.datetime.now(tz=pytz.timezone("US/Central"))
```
> datetime.timedelta(-1, 64800)
```
datetime.datetime.now(tz=pytz.timezone("UTC"))
```
> datetime.timedelta(0) #UTC
Even if I change it to explicitly use UTC:
...
```
data_table = sa.Table('data', metadata,
sa.Column('id', sa.types.Integer, primary_key=True),
sa.Column('date', sa.types.DateTime(timezone=True), default=datetime.datetime.now(tz=pytz.timezone('UTC')))
)
row[1].utcoffset()
```
...
> datetime.timedelta(-1, 64800) # it did not use the timezone I explicitly added
Or if I drop the `timezone=True`:
...
```
data_table = sa.Table('data', metadata,
sa.Column('id', sa.types.Integer, primary_key=True),
sa.Column('date', sa.types.DateTime(), default=datetime.datetime.now(tz=pytz.timezone('UTC')))
)
row[1].utcoffset() is None
```
...
> True # it didn't even save a timezone to the db this time | <http://www.postgresql.org/docs/8.3/interactive/datatype-datetime.html#DATATYPE-TIMEZONES>
> All timezone-aware dates and times are stored internally in UTC. They are converted to local time in the zone specified by the timezone configuration parameter before being displayed to the client.
The only way to store it with postgresql is to store it separately. | One way to solve this issue is to always use timezone-aware fields in the database. But note that the same time can be expressed differently depending on the timezone, and even though this is not a problem for computers it is very inconvenient for us:
```
2003-04-12 23:05:06 +01:00
2003-04-13 00:05:06 +02:00 # This is the same time as above!
```
Also Postgresql stores all timezone-aware dates and times internally in UTC. They are converted to local time in the zone specified by the timezone configuration parameter before being displayed to the client.
**Instead, I recommend to use `UTC` timestamps both throughout the app and timezone-naive dates and times in the database, and only convert them to users local timezone before user sees them.**
This strategy lets you have the cleanest code, avoiding any timezone conversions and confusions, and makes your database and app work consistently independent of the "local timezone" differences. For example, you might have your development machine and production server running on cloud in different timezones.
To achieve this, tell Postgresql that you want to see timezones in UTC before initializing the engine.
In SqlAlchemy you do it like this:
```
engine = create_engine(..., connect_args={"options": "-c timezone=utc"})
```
And if you are using tornado-sqlalchemy you can use:
```
factory = make_session_factory(..., connect_args={"options": "-c timezone=utc"})
```
Since we use all UTC timezones everywhere, we simply use timezone-naive dates and times in the model:
```
created_at = Column(DateTime, default=datetime.utcnow)
updated_at = Column(DateTime)
```
And the same in case if you are using alembic:
```
sa.Column('created_at', sa.DateTime()),
sa.Column('updated_at', sa.DateTime()),
```
And in the code use UTC time:
```
from datetime import datetime
...
model_object.updated_at = datetime.now(timezone.utc)
``` | SQLAlchemy DateTime timezone | [
"",
"python",
"postgresql",
"datetime",
"sqlalchemy",
"timezone",
""
] |
What JS/CSS trick can I use to prevent copy&paste of numbers in an ordered list?
```
<OL>
<LI>A
<LI>B
<LI>C
</OL>
```
1. A- B- C
If it's not doable, what alternative are available?
thanks | What about using a table like in
<http://bugzilla.gnome.org/attachment.cgi?id=127131> | The copying of the numbers of an OL is a browser behaviour. I believe some browsers don't but most do.
You could use JavaScript to rewrite the code once the page loads so that it looks the same but isn't underneath. This would fix your copying problem but cause other problems such as accessibility.
Essentially the way to achieve it would be to rewrite the code in Javascript to be 2 columns, 1 with the numbering and 1 with the contents. You could do this with a grids system like [YUI Grids](http://developer.yahoo.com/yui/grids/) or [Blueprint](http://code.google.com/p/blueprintcss). The user would be able to select the second column with the contents in it without selecting the first.
The issue with this is that it ruins the semantic markup for screen reader users and they no longer get the benefit of the ordered list. It might be possible to do it onmousedown so that only when the user tries to select the text you rewrite it. Not that I've tested that idea.
Disclaimer: I work for Yahoo! | Line numbering and copy/paste (HTML/CSS) | [
"",
"javascript",
"html",
"css",
""
] |
I'm looking for a python project to use as example to copy the design of the unit test parts.
The project should have these features:
1. its code is almost fully unit tested
2. the code is distributed in many packages, there are more that one level of packages
3. all the test can be run with a single command, for example with `python test.py`
I need that the project should use the same test convention for all the code contained. I saw the whole python project but the the various packages are tested with different conventions. For example the setuptools packages uses an ad hoc adaption of unittest library while the other packages doesn't.
I need that the project doesn't use a ad-hoc or a highly customized testing framework, because I want reuse its test architecture in my project. | Maybe [Nose](http://code.google.com/p/python-nose/) itself? | [Django](http://www.djangoproject.com/) is a clean project that has a nice range of unit testing.
[Have a look](http://docs.djangoproject.com/en/dev/topics/testing/#topics-testing) at how they propose you test your own projects.
[Have a look](http://code.djangoproject.com/browser/django/trunk/tests) at the unit testing code of the framework itself. | Where is a python real project to be used as example for the unit-test part? | [
"",
"python",
"unit-testing",
""
] |
I want to find all `if` statements and `for` statements which are not followed by curly brackets '`{`'. When you write a single line in an `if` statement you do not mostly enclose it in curly brackets, so I want to find all those `if` and `for` statements.
Please help!
Like I want to capture this statement
```
if (childNode.Name == "B")
return TokenType.Bold;
```
but not these kinds
```
if (childNode.Name == "B")
{
return TokenType.Bold;
}
```
I want to do it with regex. | Since the underlying mathematics disallow a perfect match, you could go for a good heuristic like "find all '`if`' followed by a semicolon without an intervening open brace:
```
/\<if\>[^{]*;/
```
where `\<` and `\>` are begin-of-word and end-of-word as applicable to your regex dialect. Also take care to ignore all newlines in the input, some regex processors need to be told to do that.
---
You might want to look at [StyleCop](http://code.msdn.microsoft.com/sourceanalysis) too. This is a tool which runs a big set of various checks on your source code. This check is already there. | If you want a 100% working solution then a regex will not fit the bill. It's way too easy to trip up a regex with real code. Take for instance the following regex
```
"^\s*if\W[^{]*\n\s*[^{]"
```
This will match a good majority of "if" statements that are not surrounded by braces. However it can easily be broken. Take the following samples. The regex will incorrectly flags these as if statements with braces.
**Example 1**
```
if ( SomeFunction(() => { return 42; }) )
```
**Example 2**
```
/* Big comment
if ( true ) {
*/
```
The list goes on and on.
Bottom line, if you want perfection, a regex will not work. If you are satisfied with a less than perfect solution then the above regex should do the trick. | i want to find all if statements in C# code which are not followed by brackets. Through regex | [
"",
"c#",
"regex",
"code-analysis",
""
] |
I want to know, how sockets are implemented in the Java Virtual Machine.
* Is there a native library included?
* And if, is it a C library?
Where can I find information about this topic?
The [offical Java tutorial on networking](http://java.sun.com/docs/books/tutorial/networking/TOC.html) does not help me there.
Some interesting links would help.
Update:
Are there any official information provided by Sun?
Thanks in advance!
**Edit**
I found a proof, I mark my answer as the correct one. Thanks to Oscar, that was the perfect hint for me!!! THANKS! | In the [network guide of Java 1.4.2](http://java.sun.com/j2se/1.4.2/docs/guide/net/socketOpt.html), an interesting piece of information is provided:
> **The implementation details...**
>
> ...that you don't need to know, unless you
> subclass
> SocketImpl/DatagramSocketImpl. **Every
> \*Socket object has an underlying SocketImpl/DatagramSocketImpl that
> interfaces to native code.** The Impl
> classes implement two methods to
> support options:
>
> void setOption(int optID, Object val)
> throws SocketException; Object
> getOption(int optID) throws
> SocketException;
>
> that *look much like C*. These methods
> act as glue to the native methods, and
> ensure type safety before native
> methods are invoked.
So I think it's proofed: Java uses native libraries for sockets. | Probably using the system-V socket calls exposed by the underlying platform, e.g. system-V under Unix, WinSock under Windows. The specification only dictates how a virtual machine must behave, so implementers are free to do as they wish. | How are sockets implemented in JVM? | [
"",
"java",
"sockets",
"network-programming",
"jvm",
""
] |
I was looking at the System.Net Namespace and it has an IPAddress instance you can use. This has a Parse method which you can use to parse a string into an IPInstance then use the Address property to give you the long value.
However...
The number returned is NOT the true conversion.
e.g. For IP 58.0.0.0 , the System.Net namespace gives me a value of 58...
When in fact, the integer value should be 973078528
Can someone please show me the correct code do convert this?
The formula should be.. (for ip 192.1.20.10).
192 \* (256\*256\*256) + 1 \* (256\*256) + 20 \* (256) + 10
The reason this formula is correct is that the number it returns you can use in a >= and <= query to determine an IP address that falls within a range.
The Address Property (of the IPAddress instance) does not calculate/return this. A bonus point for anyone that knows why the address property does not return what I think is the correct answer...
Other examples from other links did not work either. | This might work, will try it and see.
```
public double IPAddressToNumber(string IPaddress)
{
int i;
string [] arrDec;
double num = 0;
if (IPaddress == "")
{
return 0;
}
else
{
arrDec = IPaddress.Split('.');
for(i = arrDec.Length - 1; i >= 0 ; i = i -1)
{
num += ((int.Parse(arrDec[i])%256) * Math.Pow(256 ,(3 - i )));
}
return num;
}
}
``` | Please see [How to convert an IPv4 address into a integer in C#?](https://stackoverflow.com/questions/461742/how-to-convert-an-ip-address-into-an-integer-in-c) | How do display the Integer value of an IPAddress | [
"",
"c#",
"vb.net",
"ip-address",
""
] |
What would be the easiest way to have a page where it will display a list of directories that the user can click on to open, where there will be more directories or eventually files to download and have it all happen on the same page? | For something basic you are probably better off just adding 'Options +Indexes' to an .htaccess for that folder. However if you want something more complicated and are running on PHP5 you can use the [Directory Iterator](https://www.php.net/manual/en/class.directoryiterator.php) to accomplish this. The most important thing to consider is security.
You **do not** want to just dump the directory path into $\_REQUEST and then blindly let the user load that directory. You need to ensure you have some security in place to prevent, for example, some one from just changing the request and asking to see the entire /var directory. The best way to do this is to only pass the current file/folder relative to the docroot and make sure to strip out any .. so some one can't just say ../../var or something similar. | To remove index.php from the folder and allow directory browsing for that folder and subfolders in htacceess. | PHP list directories and files | [
"",
"php",
"directory",
""
] |
I have this struct:
```
struct Map
{
public int Size;
public Map ( int size )
{
this.Size = size;
}
public override string ToString ( )
{
return String.Format ( "Size: {0}", this.Size );
}
}
```
When using array, it works:
```
Map [ ] arr = new Map [ 4 ] {
new Map(10),
new Map(20),
new Map(30),
new Map(40)};
arr [ 2 ].Size = 0;
```
But when using List, it doesn't compile:
```
List<Map> list = new List<Map> ( ) {
new Map(10),
new Map(20),
new Map(30),
new Map(40)};
list [ 2 ].Size = 0;
```
Why? | The C# compiler will give you the following error:
> Cannot modify the return value of 'System.Collections.Generic.List.this[int]' because it is not a variable
The reason is that structs are value types so when you access a list element you will in fact access an intermediate copy of the element which has been returned by the indexer of the list.
From [MSDN](http://msdn.microsoft.com/en-us/library/wydkhw2c(VS.71).aspx):
> **Error Message**
>
> Cannot modify the return value of
> 'expression' because it is not a
> variable
>
> An attempt was made to modify a value
> type that was the result of an
> intermediate expression. Because the
> value is not persisted, the value will
> be unchanged.
>
> To resolve this error, store the
> result of the expression in an
> intermediate value, or use a reference
> type for the intermediate expression.
Solutions:
1. Use an array. This gives you direct access to the elements (you are not accessing a copy)
2. When you make Map a class you can still use a List to store your element. You will then get a reference to a Map object instead of an intermediate copy and you will be able to modify the object.
3. If you cannot change Map from struct to a class you must save the list item in a temporary variable:
```
List<Map> list = new List<Map>() {
new Map(10),
new Map(20),
new Map(30),
new Map(40)
};
Map map = list[2];
map.Size = 42;
list[2] = map;
``` | Because it is a `struct`, when using the List<T>, you're are creating copies.
When using a struct, it is better to make them immutable. This will avoids effects like this.
When using an array, you have direct access to the memory structures. Using the List<T>.get\_Item you work on a return value, that is, a copy of the structure.
If it was a class, you would get a copy of a pointer to the class, but you would not notice this, since pointers are hidden in C#.
Also using the List<T>.ToArray does not solve it, because it will create a copy of the internal array, and return this.
And this is not the only place where you will get effects like this when using a struct.
The solution provided by Divo is a very good workaround. But you have to remember to work this way, not only when using the List<T> but everywhere you want to change a field inside the struct. | Directly modifying List<T> elements | [
"",
"c#",
".net",
""
] |
I have a chunk of code where it appears that a variable is changing at the end of a pre-processor block of code.
```
int initialKeyCount;
#if(DEBUG)
// int initialKeyCount = _root.CountAllKeys();
initialKeyCount = 20000;
#endif
currNode = currNode.EnsureDegreeKeysPresent(parent); //initialKeyCount = 19969 here
#if(DEBUG)
int currentKeyCount = _root.CountAllKeys();
Debug.Assert(initialKeyCount == currentKeyCount,
string.Format("EnsureDegreeNodesPresent changed the node count from {0} to {1}.", initialKeyCount, currentKeyCount));
#endif
```
When executing this in the debugger initialKeyCount = 19969 after supposedly assigning 20000. I have played around with this a bit and found that assignment to initialKeyCount is correct inside the first pre-processor block, but as soon as the code leaves the first pre-processor block the value magically changes to 19969.
This behavior is the same regardless of whether the variable is declared inside or outside the first pre-processor block. The value remains 19969 inside the second pre-processor block.
Are assignments made in a pre-processor block undefined outside of that block? That seems wrong but appears to be what is happening here. | Sounds like Visual Studio got confused. Try these steps in order
1. Use the Clean command
2. Restart Visual Studio
3. Delete every DLL and EXE that even remotely looks like your program
4. Double check every BIN and OBJ folder to see if you missed anything.
5. Search your whole hard drive for any DLL and EXE that even remotely looks like your program and delete them too
I used to see this once a week at an IT company I worked for. It usually happens when you have multiple copies of the same project, but I've seen it even without that. | This sort of behaviour sounds very much like the debugger is running code that doesn't match the source code you are editing. Are you absolutely sure that your source changes are making it all the way to the code you're running?
The preprocessor blocks are unrelated to the language syntax. So, you're correct in saying that preprocessor blocks do not affect the scope of variable definitions. | Integer value changes when exiting preprocessor block | [
"",
"c#",
"c-preprocessor",
"variable-assignment",
""
] |
I've read on articles and books that the use of `String s = new String("...");` should be avoided pretty much all the time. I understand why that is, but is there any use for using the String(String) constructor whatsoever? I don't think there is, and don't see any evidence otherwise, but I'm wondering if anyone in the SO commmunity knows of a use. | This is a good article: [String constructor considered useless turns out to be useful after all!](http://kjetilod.blogspot.com/2008/09/string-constructor-considered-useless.html)
> It turns out that this constructor can actually be useful in at least one circumstance. If you've ever peeked at the String source code, you'll have seen that it doesn't just have fields for the char array value and the count of characters, but also for the offset to the beginning of the String. This is so that Strings can share the char array value with other Strings, usually results from calling one of the substring() methods. Java was famously chastised for this in jwz' Java rant from years back:
>
> The only reason for this overhead is so that String.substring() can return strings which share the same value array. Doing this at the cost of adding 8 bytes to each and every String object is not a net savings...
>
> Byte savings aside, if you have some code like this:
>
> ```
> // imagine a multi-megabyte string here
> String s = "0123456789012345678901234567890123456789";
> String s2 = s.substring(0, 1);
> s = null;
> ```
>
> You'll now have a String s2 which, although it seems to be a one-character string, holds a reference to the gigantic char array created in the String s. This means the array won't be garbage collected, even though we've explicitly nulled out the String s!
>
> The fix for this is to use our previously mentioned "useless" String constructor like this:
>
> ```
> String s2 = new String(s.substring(0, 1));
> ```
>
> It's not well-known that this constructor actually copies that old contents to a new array if the old array is larger than the count of characters in the string. This means the old String contents will be garbage collected as intended. Happy happy joy joy.
Finally, [Kat Marsen](http://hanuska.blogspot.com/2006/03/how-useful-is-stringstring-constructor.html?showComment=1169976540000#c5481901777730175548) makes these points,
> First of all, string constants are never garbage collected. Second of all, string constants are intern'd, which means they are shared across the entire VM. This saves memory. But it is not always what you desire.
>
> The copy constructor on String allows you to create a private String instance from a String literal. This can be very valuable for constructing meaningful mutex objects (for the purposes of synchronization). | If I remember correctly the only 'useful' case is where the original String is part of a much larger backing array. (e.g. created as a substring). If you only want to keep the small substring around and garbage collect the large buffer, it might make sense to create a new String. | Use of the String(String) constructor in Java | [
"",
"java",
"string",
"coding-style",
""
] |
I'm using **PHP 4.3.9, Apache/2.0.52**
I'm trying to get a login system working that registers DB values in a session where they're available once logged in. **I'm losing the session variables once I'm redirected**.
I'm using the following code to print the session ID/values on my login form page and the redirected page:
```
echo '<font color="red">session id:</font> ' . session_id() . '<br>';
echo '<font color="red">session first name:</font> ' . $_SESSION['first_name'] . '<br>';
echo '<font color="red">session user id:</font> ' . $_SESSION['user_id'] . '<br>';
echo '<font color="red">session user level:</font> ' . $_SESSION['user_level'] . '<br><br>';
```
This is what's printed in my browser from my login page (I just comment out the header redirect to the logged in page). **This is the correct info coming from my DB as well, so all is fine at this point**.
```
session id: 1ce7ca8e7102b6fa4cf5b61722aecfbc
session first name: elvis
session user id: 2
session user level: 1
```
This is what's printed on my redirected/logged in page (when I uncomment the header/redirect). **Session ID is the same**, but I get no values for the individual session variables.
```
session id: 1ce7ca8e7102b6fa4cf5b61722aecfbc
session first name:
session user id:
session user level:
```
I get the following errors:
**Undefined index: first\_name
Undefined index: user\_id
Undefined index: user\_level**
I have a global **header.php** file which my loggedIN.php does NOT call, though loggedOUT.php does - to toast the session):
**header.php**
```
<?php
ob_start();
session_start();
//if NOT on loggedout.php, check for cookie. if exists, they haven't explicity logged out so take user to loggedin.php
if (!strpos($_SERVER['PHP_SELF'], 'loggedout.php')) {
/*if (isset($_COOKIE['access'])) {
header('Location: www.mydomain.com/loggedin.php');
}*/
} else {
//if on loggedout.php delete cookie
//setcookie('access', '', time()-3600);
//destroy session
$_SESSION = array();
session_destroy();
setcookie(session_name(), '', time()-3600);
}
//defines constants and sets up custom error handler
require_once('config.php');
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
some page layout stuff
Login portion is eventually called via include
footer stuff
```
My **loggedIN.php** does nothing but start the session
```
<?php
session_start();
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
```
The **logic of my login script**, the key part being I'm fetching the DB results right into $\_SESSION (about half way down):
```
if (isset($_POST['login'])) {
//access db
require_once(MYSQL);
//initialize an errors array for non-filled out form fields
$errors = array();
//setup $_POST aliases, clean for db and trim any whitespace
$email = mysql_real_escape_string(trim($_POST['email']), $dbc);
$pass = mysql_real_escape_string(trim($_POST['pass']), $dbc);
if (empty($email)) {
$errors[] = 'Please enter your e-mail address.';
}
if (empty($pass)) {
$errors[] = 'Please enter your password.';
}
//if all fields filled out and everything is OK
if (empty($errors)) {
//check db for a match
$query = "SELECT user_id, first_name, user_level
FROM the rest of my sql here, blah blah blah";
$result = @mysql_query($query, $dbc)
OR trigger_error("Query: $query\n<br />MySQL Error: " . mysql_error($dbc));
if (@mysql_num_rows($result) == 1) { //a match was made, OK to login
//register the retrieved values into $_SESSION
$_SESSION = mysql_fetch_array($result);
mysql_free_result($result);
mysql_close($dbc);
/*
setcookie('access'); //if "remember me" not checked, session cookie, expires when browser closes
//in FF you must close the tab before quitting/relaunching, otherwise cookie persists
//"remember me" checked?
if(isset($_POST['remember'])){ //expire in 1 hour (3600 = 60 seconds * 60 minutes)
setcookie('access', md5(uniqid(rand())), time()+60); //EXPIRES IN ONE MINUTE FOR TESTING
}
*/
echo '<font color="red">cookie:</font> ' . print_r($_COOKIE) . '<br><br>';
echo '<font color="red">session id:</font> ' . session_id() . '<br>';
echo '<font color="red">session first name:</font> ' . $_SESSION['first_name'] . '<br>';
echo '<font color="red">session user id:</font> ' . $_SESSION['user_id'] . '<br>';
echo '<font color="red">session user level:</font> ' . $_SESSION['user_level'] . '<br><br>';
ob_end_clean();
session_write_close();
$url = BASE_URL . 'loggedin_test2.php';
header("Location: $url");
exit();
} else {
//wrong username/password combo
echo '<div id="errors"><span>Either the e-mail address or password entered is incorrect or you have not activated your account. Please try again.</span></div>';
}
//clear $_POST so the form isn't sticky
$_POST = array();
} else {
//report the errors
echo '<div id="errors"><span>The following error(s) occurred:</span>';
echo '<ul>';
foreach($errors as $error) {
echo "<li>$error</li>";
}
echo '</ul></div>';
}
} // end isset($_POST['login'])
```
**if I comment out the header redirect on the login page, I can echo out the $\_SESSION variables with the right info from the DB. Once redirected to the login page, however, they're gone/unset.**
Anyone have any ideas? I've spent nearly all day on this and can't say I'm any closer to figuring it out.
BTW, I recently made 2 simple test pages, one started a session, set some variables on it, had a form submit which redirected to a second page which did nothing but read/output the session vars. It all seems to work fine, I'm just having issues with something I'm doing in my main app. | I don't see a `session_start()` in your login script. If you aren't starting the session I don't think php will save any data you place in the `$_SESSION` array. Also to be safe I'd explicitly place variables into the `$_SESSION` array instead of just overwriting the whole thing with `$_SESSION = mysql_fetch_array($result);`. | Try doing a
```
session_regenerate_id(true);
```
before the
```
session_write_close();
```
Also. The best way IMO to do a login script is this:
Let the login logic be handled within the mainpage the user is trying to access.
1. If the user is not authenticated, he is thrown back to the login page
2. If the user is authenticated, he gets an $\_SESSION["auth"] or something
3. Then when the user is browsing the main page or other pages that need auth, they just check if the $\_SESSION["auth"] is set.
Then you wont have the trouble of session not saving just before a redirect | PHP session variables not carrying over to my logged in page, but session ID is | [
"",
"php",
"session",
"redirect",
"variables",
""
] |
I've been doing a project at work recently focused on an almost entirely client-driven web site. Obviously Javascript is used heavily, and I've been using jQuery on top of it which has turned out to be an absolute pleasure to work with.
One of the things that has surprised me in this is how much I like the JSON object syntax and it's use within javascript (highlighted by jQuery, which uses it everywhere). for those that aren't familiar with it, consider this brief example:
```
function add(params) {
params.result(params.a, params.b);
}
add({
a: 1,
b: 2,
result: function(value) {
alert(value);
}
});
```
Of course, this example is extremely contrived but it illustrates the basic usage. The JSON describes an object on the fly, passed in this case as a parameter to the function, and even defines a function within it for use as a callback. I personally find this methodology very easy to use, understand, and produce APIs with (though I know there are those that would disagree with me.)
So my question is, is this type of syntax unique to javascript? I know that many languages have JSON parsers (and have used several) but they don't allow for this sort of inlined declaration. And granted, much of what you can do with this syntax can be duplicated via named parameters in various languages and lambda expressions or function pointers (Python jumps to mind), but I still don't find that quite as elegant.
Just curious, thanks for any replies! | The canonical example is Lisp: in Lisp, the language isn't even defined in terms of text, it is defined in terms of data structures. There really is not difference between code and data: code is just a list whose first element is interpreted as an operation and the rest as operands.
Writing a program is just writing lists. | Lua uses "tables" which are pretty much identical to javascript objects. | Language with similar object use to Javascript/JSON | [
"",
"javascript",
"json",
""
] |
I have this code below and the "if ((DateTime)DataReader[0] > DateTime.Now)" condition returns false even if the datetime in the database is greater than the datetimenow.
I used this code before and it use to work I never changed any thing.
So the question is why does the condition return false?
Thanks,
Simon
```
Boolean active = false;
SqlConnectionUniqueInstance.Instance.Open();
SqlCommand Command = SqlConnectionUniqueInstance.Instance.Connection.CreateCommand();
Command.CommandText = String.Format(@"SELECT [LogoutDateTime] FROM [dbo].[sessions] WHERE [sessionID] = {0}", sessionId.ToString());
SqlDataReader DataReader = Command.ExecuteReader();
while (DataReader.Read())
{
if ((DateTime)DataReader[0] > DateTime.Now)
active = true;
}
DataReader.Close();
if (active)
UpdateTime(sessionId);
Command.Dispose();
return active;
``` | This is the actual answer:
You do not need/have/should to compare DateTime with >, <, == or != operators. Instead you can use the Compare and CompareTo methods of the DateTime class.
[Compare](http://msdn.microsoft.com/en-us/library/system.datetime.compare.aspx): Compares two instances of DateTime and returns an integer that indicates whether the first instance is earlier than, the same as, or later than the second instance.
[CompareTo](http://msdn.microsoft.com/en-us/library/system.datetime.compareto.aspx): Overloaded. Compares the value of this instance to a specified DateTime value and indicates whether this instance is earlier than, the same as, or later than the specified DateTime value.
<http://msdn.microsoft.com/en-us/library/system.datetime_members.aspx> | First of all it is a bad practice to work with DateTime that way. You should store value of DateTime.ToUniversalTime in the database and convert loaded DateTime to local time using DateTime.ToLocalTime method. Also it is not clear how much records will be returned from DB i.e. you can rewrite active several times. Just show us values of (DateTime)DataReader[0] and DateTime.Now (including DateTime.Kind property)
Also program logic looks obscure - why logout time is in future? | I have a condition comparing DateTime in C# using the < operator and it return's false even if it should not. Why? | [
"",
"c#",
""
] |
Having implemented CLogClass to make decent logging I also defined macro, but it works only with one parameter...
```
class CLogClass
{
public:
static void DoLog(LPCTSTR sMessage, ...);
};
#define DebugLog(sMessage, x) ClogClass::DoLog(__FILE__, __LINE__, sMessage, x)
```
Well, it fails when called with more than 2 parameters :( ... Is it possible at all to avoid it? Can it be translated to templates somehow?
EDIT: Variadic macros were introduced in VS 2005 (But i'm currently in VS 2003...). Any advices? | You could have a MYLOG macro returning a custom functor object which takes a variable number of arguments.
```
#include <string>
#include <cstdarg>
struct CLogObject {
void operator()( const char* pFormat, ... ) const {
printf( "[%s:%d] ", filename.c_str(), linenumber );
va_list args;
va_start( args, pFormat );
vfprintf( stderr, pFormat, args );
va_end( args );
}
CLogObject( std::string filename, const int linenumber )
: filename( filename ), linenumber( linenumber )
{}
std::string filename;
int linenumber;
};
#define MYLOG CLogObject( __FILE__, __LINE__ )
int _tmain(int argc, _TCHAR* argv[])
{
MYLOG( "%s, %d", "string", 5 );
return 0;
}
```
Note that it's not so hard to step over to the type-safe variant touched by [this answer](https://stackoverflow.com/questions/419559/is-this-possible-use-ellipsis-in-macro-can-it-be-converted-to-template#419828): you don't need any variadic arguments due to the chaining effect of `operator<<`.
```
struct CTSLogObject {
template< typename T >
std::ostream& operator<<( const T& t ) const {
return std::cout << "[" << filename << ":" << linenumber << "] ";
}
CTSLogObject( std::string filename, const int linenumber )
: filename( filename ), linenumber( linenumber )
{}
std::string filename;
int linenumber;
};
#define typesafelog CTSLogObject( __FILE__, __LINE__ )
int _tmain(int argc, _TCHAR* argv[])
{
typesafelog << "typesafe" << ", " << 5 << std::endl;
return 0;
}
``` | Your questions actually appeals to two answers. You want to do the universal logging function, that works like printf but can be fully customise. So you need:
* macro taking a variable number of arguments
* function taking a variable number of arguments
Here is your code example adatapted:
```
#include <stdio.h>
#include <stdarg.h>
class CLogClass
{
public:
static void DoLogWithFileLineInfo( const char * fmt, ... )
{
va_list ap;
va_start( ap, fmt );
vfprintf( stderr, fmt, ap );
va_end( ap );
}
};
#define MYLOG(format, ...) CLogClass::DoLogWithFileLineInfo("%s:%d " format , __FILE__, __LINE__, __VA_ARGS__)
int main()
{
MYLOG("Hello world!\n", 3); // you need at least format + one argument to your macro
MYLOG("%s\n", "Hello world!");
MYLOG("%s %d\n", "Hello world!", 3);
}
```
Variadic macros have been introduced in C99, so it will work on compilers supporting C99 or C++0x . I tested it successfully with gcc 3.4.2 and Visual Studio 2005.
Variadic arguments to functions have been there forever so no worry about compability here.
It's probably possible to do it with some template meta-programmaing but I don't see the interest of it given the simplicity of the code above.
As a last note, why use a static method in an empty class instead of a function ? | Is this possible use ellipsis in macro? Can it be converted to template? | [
"",
"c++",
"visual-c++",
"logging",
"c-preprocessor",
""
] |
We are looking to implement Optimistic locking in our WCF/WPF application. So far the best way I've come up with doing this is to implement a generic Optimistic which will store a copy of the original and any changes (so it will store two copies: the original and modified) of any value object that can be modified. Is this the best way of doing it?
For example: a UserVO will be wrapped by the generic as a Optimistic. When a change is made to the Optimistic, the change will be made to the modified copy stored in the Optimistic while the original also stored in the Optimistic will remain intact. The main issue seems to be that it will use up twice the space and hence bandwidth.
Thanks
**EDIT** The solution needs to be database independent, and it would be useful to be able to specify an conflict resolution policy per value object. (eg. A user object might try and merge if the updated rows weren't changed, but a transaction object would always require user intervention). | If you are using SQL server you can use a timestamp column. The timestamp column is changed anytime a row is modified. Essentially when your updating the DB you can check if the timestamp column is the same as when the client first got the data, if so no one has modified the data.
# Edit
If you want to minimize the bandwidth, you could emulate the timestamp concept by adding a version number on each object. So for example:
1. Client 1 requests object, sever returns Object V1
2. Client 2 requests object, server returns Object v2
3. Client 1 modifies object sending it back to server as V1
4. Server compares the version and see's v1=v1 so it commits the change
5. Server increments the version of the object so now its v2
6. Client 2 modifis object sending it back to server as v1
7. Server compares the version and see's v1!=v2 so it performs whatever your policy is
For configuring your policy, you could define in a configuration a specific object that will handle Policy failures depending on the type of root object. You could whip up a IOptomisticCheckFailurePolicy interface, and you could probally use one of the DI libraries like structure map to create the object when you need it (Although you could just as easily load it up using reflection) | One way of implementing optimistic locking logic is to base it on a last modified timestamp of a row. So the update will look as follows:
UPDATE .... WHERE id = x AND last\_updated = t
x: record id.
t: the last updated timestamp of the row when it was loaded from the database (i.e. before modifications).
Note that one of the fields that must be updated directly or indirectly is the timestamp to be set to now (or UtcNow).
This way the update will fail in case the record was modified in the background. Once the update failed, you can issue further queries to detect the cause of the failure. For example,
1. Record has been deleted.
2. Record has been modified.
This simple approach provides row level optimistic locking, it is not column based and has no conflict resolution. | Change Tracking Structure | [
"",
"c#",
".net",
"wpf",
"wcf",
"concurrency",
""
] |
I want to add a "Select One" option to a drop down list bound to a `List<T>`.
Once I query for the `List<T>`, how do I add my initial `Item`, not part of the data source, as the FIRST element in that `List<T>` ? I have:
```
// populate ti from data
List<MyTypeItem> ti = MyTypeItem.GetTypeItems();
//create initial entry
MyTypeItem initialItem = new MyTypeItem();
initialItem.TypeItem = "Select One";
initialItem.TypeItemID = 0;
ti.Add(initialItem) <!-- want this at the TOP!
// then
DropDownList1.DataSource = ti;
``` | Use the [Insert](http://msdn.microsoft.com/en-us/library/sey5k5z4.aspx) method:
```
ti.Insert(0, initialItem);
``` | Since .NET 4.7.1, you can use the side-effect free [`Prepend()`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.prepend?view=netframework-4.8&viewFallbackFrom=netframework-4.7) and [`Append()`](https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.append?view=netframework-4.8). The output is going to be an IEnumerable.
```
// Creating an array of numbers
var ti = new List<int> { 1, 2, 3 };
// Prepend and Append any value of the same type
var results = ti.Prepend(0).Append(4);
// output is 0, 1, 2, 3, 4
Console.WriteLine(string.Join(", ", results));
```
---
Edit:
If you want to explicitly mutate your given list:
```
// Creating an array of numbers
var ti = new List<int> { 1, 2, 3 };
// mutating ti
ti = ti.Prepend(0).ToList();
```
but at that point just use [`Insert(0, 0)`](https://learn.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.insert?view=net-7.0) | How to add item to the beginning of List<T>? | [
"",
"c#",
"drop-down-menu",
"generic-list",
""
] |
In [this answer](https://stackoverflow.com/questions/452517/does-this-entity-repository-service-example-fit-into-domain-driven-design#452564) to a [recent question](https://stackoverflow.com/questions/452517), I was advised to
> "be wary of making every property in your domain model have public getters and setters. That can lead you to an anemic domain model."
However I then encounter the problem that an entity with private setters, like this:
```
public class Phrase
{
public int PhraseId { get; private set; }
public string PhraseText { get; private set; }
}
```
cannot be JSON-serialized from a View to a controller (using ASP.NET MVC). This is due to the private setter.
How would you allow serialization with private setters? | I don't know if you can override the deserialization process with MVC, but note that `DataContractSerializer` supports non-public accessors, and there is a JSON version: [`DataContractJsonSerializer`](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.json.datacontractjsonserializer.aspx) - maybe worth a look?
Personally, though, I'd just accept the public setter in this case... this is a pretty common feature of .NET DTOs and .NET-based serializations. The immutable/factory pattern, while common in java, hasn't really taken as much hold in .NET; I can't say I mind overly. | You can always override the serialization or just write your own JSON deserialize method. I personally think it's not worth the effort. Just make the setter public and be done with it. What is the setter being private really buying you? | Conflict between avoiding anemic model and allowing serialization | [
"",
"c#",
"json",
"serialization",
""
] |
As far as I know, there's no way to use {% include %} within a dynamic JS file to include styles. But I don't want to have to make another call to the server to download styles.
Perhaps it would be possible by taking a stylesheet and injecting it into the head element of the document...has anyone does this before? | In your JS file:
```
var style = document.createElement('link');
style.setAttribute('rel', 'stylesheet');
style.setAttribute('type', 'text/css');
style.setAttribute('href', 'style.css');
document.getElementsByTagName('head')[0].appendChild(style);
```
Hope that helps. | With jquery...
```
$('head').append($('<link rel="stylesheet" type="text/css" href="style.css">'))
``` | Is it possible to use Django to include CSS (here's the tricky part) from a JS file? | [
"",
"javascript",
"css",
"django",
"dom",
""
] |
For part of a web application the user needs to import some data from a spreadsheet. Such as a list of names and email addresses. Currently we do this by asking the user to browse for and upload a CSV file.
Unfortunately, this isn't always possible as various corporate IT systems only allow users to access files from document management systems and they have no privileges to save these to a local drive or network share.
The solution we have is to allow the user to cut and paste the entire sheet (CSV) into a text area and submit that. On doing this you get a nice tab delimited list of the data that is easily parsed as below.
```
Lorem ipsum dolor sit amet
consectetur adipiscing elit Vivamus fermentum
Vivamus et diam eu eros
egestas rutrum Morbi id neque
id enim molestie tincidunt Nullam
```
Unfortunately, various cells could produce unexpected results. In the set below you can see a " within the word prerium, a tab with the word Suspendisse and a line break within the word sollicitudin.
```
bibendum ante molestie lectus Sed
pret"ium "Susp endisse" "sollic
itudin" nisi at
urna Sed sit amet odio
eu neque egestas tincidunt Nunc
metus Curabitur at nibh Nulla
```
In this case I cannot just split on tabs and line breaks without a more enhance mechanism to deal with the tabs, quotes and line breaks within the actual data.
Does anyone know of any code that can handle this reliably? Or even if excel and the clipboard like this can be relied upon to produce consistant results?
I am working in Asp.net 3.5 using C#.
The users excel version may vary but should always be Windows 2000/XP/Vista and IE 6/7. | This looks like a "delimited values" list to me, so basically the same as CSV with TAB as the field delimiter and line break as the row delimiter. You could try it with the [CSV Reader library from CodeProject](http://www.codeproject.com/KB/database/CsvReader.aspx), it should be handle to handle different delimiters, not just comma. | try find something helpful in [System.Windows.Forms.Clipboard members](http://msdn.microsoft.com/en-us/library/system.windows.forms.clipboard_members.aspx) | How to parse a "cut n paste" from Excel | [
"",
"c#",
"asp.net",
"excel",
""
] |
I've got a form with a bunch of textboxes that are disabled by default, then enabled by use of a checkbox next to each one.
When enabled, the values in these textboxes are required to be a valid number, but when disabled they don't need a value (obviously). I'm using the jQuery Validation plugin to do this validation, but it doesn't seem to be doing what I expect.
When I click the checkbox and disable the textbox, I still get the invalid field error despite the `depends` clause I've added to the rules (see code below). Oddly, what actually happens is that the error message shows for a split second then goes away.
Here is a sample of the list of checkboxes & textboxes:
```
<ul id="ItemList">
<li>
<label for="OneSelected">One</label><input id="OneSelected" name="OneSelected" type="checkbox" value="true" />
<input name="OneSelected" type="hidden" value="false" />
<input disabled="disabled" id="OneValue" name="OneValue" type="text" />
</li>
<li>
<label for="TwoSelected">Two</label><input id="TwoSelected" name="TwoSelected" type="checkbox" value="true" />
<input name="TwoSelected" type="hidden" value="false" />
<input disabled="disabled" id="TwoValue" name="TwoValue" type="text" />
</li>
</ul>
```
And here is the jQuery code I'm using
```
//Wire up the click event on the checkbox
jQuery('#ItemList :checkbox').click(function(event) {
var textBox = jQuery(this).siblings(':text');
textBox.valid();
if (!jQuery(this).attr("checked")) {
textBox.attr('disabled', 'disabled');
textBox.val('');
} else {
textBox.removeAttr('disabled');
textBox[0].focus();
}
});
//Add the rules to each textbox
jQuery('#ItemList :text').each(function(e) {
jQuery(this).rules('add', {
required: {
depends: function(element) {
return jQuery(element).siblings(':checkbox').attr('checked');
}
},
number: {
depends: function(element) {
return jQuery(element).siblings(':checkbox').attr('checked');
}
}
});
});
```
Ignore the hidden field in each `li` it's there because I'm using asp.net MVC's `Html.Checkbox` method. | Using the "ignore" option (<http://docs.jquery.com/Plugins/Validation/validate#toptions>) might be the easiest way for you to deal with this. Depends on what else you have on the form. For i.e. you wouldn't filter on disabled items if you had other controls that were disabled but you still needed to validate for some reason. However, if that route doesn't work, using an additional class to filter on (adding and removing with your checkboxes) should get you to where you want to go, but easier.
I.e.
```
$('form').validate({
ignore: ":disabled",
...
});
``` | Usually when doing this, I skip 'depends' and just use the `required` jQuery Validate rule and let it handle the checking based on the given selector, as opposed to splitting the logic between the validate rules and the checkbox click handler. I put together a [quick demo](http://www.command-tab.com/demos/checkbox_validate/) of how I accomplish this, using your markup.
Really, it boils down to **`required:'#OneSelected:checked'`**. This makes the field in question required only if the expression is true. In the demo, if you submit the page right away, it works, but as you check boxes, the form is unable to submit until the checked fields are filled with some input. You could still put a `.valid()` call in the checkbox click handler if you want the entire form to validate upon click.
(Also, I shortened up your checkbox toggling a bit, making use of jQuery's wonderful chaining feature, though your "caching" to `textBox` is just as effective.) | Using depends with the jQuery Validation plugin | [
"",
"javascript",
"jquery",
"jquery-validate",
""
] |
I have a class which has many small functions. By small functions, I mean functions that doesn't do any processing but just return a literal value. Something like:
```
string Foo::method() const{
return "A";
}
```
I have created a header file "Foo.h" and source file "Foo.cpp". But since the function is very small, I am thinking about putting it in the header file itself. I have the following questions:
1. Is there any performance or other issues if I put these function definition in header file? I will have many functions like this.
2. My understanding is when the compilation is done, compiler will expand the header file and place it where it is included. Is that correct? | If the function is small (the chance you would change it often is low), and if the function can be put into the header without including myriads of other headers (because your function depends on them), it is perfectly valid to do so. If you declare them extern inline, then the compiler is required to give it the same address for every compilation unit:
*headera.h*:
```
inline string method() {
return something;
}
```
Member functions are implicit inline provided they are defined inside their class. The same stuff is true for them true: If they can be put into the header without hassle, you can indeed do so.
Because the code of the function is put into the header and visible, the compiler is able to inline calls to them, that is, putting code of the function directly at the call site (not so much because you put inline before it, but more because the compiler decides that way, though. Putting inline only is a hint to the compiler regarding that). That can result in a performance improvement, because the compiler now sees where arguments match variables local to the function, and where argument doesn't alias each other - and last but not least, function frame allocation isn't needed anymore.
> My understanding is when the compilation is done, compiler will expand the header file and place it where it is included. Is that correct?
Yes, that is correct. The function will be defined in every place where you include its header. The compiler will care about putting only one instance of it into the resulting program, by eliminating the others. | Depending on your compiler and it's settings it may do any of the following:
* It may ignore the inline keyword (it
is just a hint to the compiler, not a
command) and generate stand-alone
functions. It may do this if your
functions exceed a compiler-dependent
complexity threshold. e.g. too many
nested loops.
* It may decide than your stand-alone
function is a good candidate for
inline expansion.
In many cases, the compiler is in a much better position to determine if a function should be inlined than you are, so there is no point in second-guessing it. I like to use implicit inlining when a class has many small functions only because it's convenient to have the implementation right there in the class. This doesn't work so well for larger functions.
The other thing to keep in mind is that if you are exporting a class in a DLL/shared library (not a good idea IMHO, but people do it anyway) you need to be really careful with inline functions. If the compiler that built the DLL decides a function should be inlined you have a couple of potential problems:
1. The compiler building the program
using the DLL might decide to not
inline the function so it will
generate a symbol reference to a
function that doesn't exist and the
DLL will not load.
2. If you update the DLL and change the
inlined function, the client program
will still be using the old version
of that function since the function
got inlined into the client code. | Writing function definition in header files in C++ | [
"",
"c++",
"performance",
"header-files",
""
] |
I am using an application in c++ that uses a special dprintf function to print information, this is an example:
```
dprintf(verbose, "The value is: %d", i);
```
What is doing is when I define verbose for test purposes then I print the information and when I am working in normal execution I do not define it and I do not see useless information in the screen. My question is how can I do that function or implement the same idea?. | I try to avoid using var-arg c-style functions for two main reasons:
* They are not type-safe, can't use operator<<
* They don't recognize when too few or many arguments were provided
I've made a way that works using `boost::fusion`, which is given arguments in a type-safe way. It iterates over those arguments, printing out them when a `%` is encountered. If too few or too many arguments were given, an exception is thrown.
There is one problem still: Variadic macros are not yet standard in C++. So, i have made two versions. One that work with current C++. You have to invoke it using
```
dprintf("name: %, value: %\n", ("foo", 42));
```
Then. The other version, using variadic macros, can be used by defining a preprocessor symbol, which enables you to write
```
dprintf("name: %, value: %\n", "foo", 42);
```
Here is the code. The [`boost.fusion`](http://www.boost.org/doc/libs/1_37_0/libs/fusion/doc/html/index.html) provides more details for this:
```
#include <boost/fusion/include/sequence.hpp>
#include <boost/fusion/include/make_vector.hpp>
#include <boost/fusion/include/next.hpp>
#include <stdexcept>
#include <iostream>
template<typename IterS, typename IterSeqE>
void print_vec(IterS b, IterS e, IterSeqE, IterSeqE) {
while(b != e) {
if(*b == '%') {
if(++b != e && *b == '%') {
std::cout << '%';
} else {
throw std::invalid_argument("too many '%'");
}
} else {
std::cout << *b;
}
++b;
}
}
template<typename IterS, typename IterSeqB, typename IterSeqE>
void print_vec(IterS b, IterS e, IterSeqB seqb, IterSeqE seqe) {
while(b != e) {
if(*b == '%') {
if(++b != e && *b == '%') {
std::cout << '%';
} else {
std::cout << *seqb;
return print_vec(b, e, next(seqb), seqe);
}
} else {
std::cout << *b;
}
++b;
}
throw std::invalid_argument("too few '%'");
}
template<typename Seq>
void print_vec(std::string const& msg, Seq const& seq) {
print_vec(msg.begin(), msg.end(), begin(seq), end(seq));
}
#ifdef USE_VARIADIC_MACRO
# ifdef DEBUG
# define dprintf(format, ...) \
print_vec(format, boost::fusion::make_vector(__VA_ARGS__))
# else
# define dprintf(format, ...)
# endif
#else
# ifdef DEBUG
# define dprintf(format, args) \
print_vec(format, boost::fusion::make_vector args)
# else
# define dprintf(format, args)
# endif
#endif
// test, using the compatible version.
int main() {
dprintf("hello %, i'm % years old\n", ("litb", 22));
}
``` | ```
#ifdef DEBUG
#define dprintf(format, ...) real_dprintf(format, __VA_ARGS__)
#else
#define dprintf
#endif
```
Here real\_dprintf() is the "real" function that is invoked, and dprintf() is just a macro wrapping the call. | Print information in "test mode" but not in "normal execution" | [
"",
"c++",
"testing",
"printing",
""
] |
I am implementing a small queue to handle which process gets to run first. I am using a table in a database to do this. Here is the structure of the table (I'm mocking it up in SQLite):
```
"id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL ,
"identifier" VARCHAR NOT NULL ,
"priority_number" INTEGER DEFAULT 15,
"timestamp" DATETIME DEFAULT CURRENT_TIMESTAMP,
"description" VARCHAR
```
I am trying to write SQL to give me the row of which process can run next. Here is some sample data:
```
id identifier priority_number timestamp description
1 test1 15 2009-01-20 17:14:49 NULL
2 test2 15 2009-01-20 17:14:56 NULL
3 test3 10 2009-01-20 17:15:03 NULL
4 test4 15 2009-01-20 17:15:08 NULL
5 test5 15 2009-01-20 17:32:23 NULL
6 test6 14 2009-01-20 17:32:30 NULL
7 test7 7 2009-01-20 17:32:38 NULL
8 test8 20 2009-01-20 17:32:57 NULL
9 test9 7 2009-01-21 13:47:30 NULL
10 test10 15 2009-01-21 13:50:52 NULL
```
If I use this SQL, I can get the data in the proper order:
```
select * from queue_manager order by priority_number, timestamp;
```
This will give me the item with the lowest priority number (most important) at the top, and in those priority numbers, the earliest into the queue (by timestamp) at the top.
I could run this query, and only take the first row, but I would rather do this with a SQL query that would give me the one row of the process that is at the top of the queue (in the example data above, the row with id=7).
I tried doing self joins and sub queries, but I must be having a mental block - I just can't seem to get it right.
Thanks in advance!
**EDIT**
I forgot to mention that I am looking for a database-independent query. I am mocking this up in SQlite, but there is a good possibility I will implement this in DB2 or Oracle. I had thought to use a "limit 1" type operator on my query, but that is different between different database engines. | See if this works:
```
select * from queue_manager where priority_number =
(select min(priority_number) from queue_manager) and
timestamp = (select min(timestamp)
from queue_manager qm2
where qm2.priority_number = queue_manager.priority_number)
``` | ```
select * from queue_manager order by priority_number, timestamp LIMIT 1;
```
As for such called "database independency", it's a myth for most real world tasks. As a rule, you cannot even create schema in database-independent way. | Working out the SQL to query a priority queue table | [
"",
"sql",
"queue",
"priority-queue",
"queue-table",
""
] |
What garbage collectors are there available for C++? Are you using any of them? With what results? | The [Boost](http://www.boost.org/) library includes some shared\_ptr stuff that basically acts as a reference counting garbage collector. If you embrace the [RAII](http://en.wikipedia.org/wiki/Resource_acquisition_is_initialization) principle of C++ design, that and auto\_ptr will fill your need for a "garbage collector". | Several C++ GC are listed [on wikipedia](http://en.wikipedia.org/wiki/Garbage_collection_(computer_science)#External_links).
However, I don't use any, RAII is also my friend. | What garbage collectors are there available for C++? | [
"",
"c++",
"garbage-collection",
""
] |
I have a script that did double inserts into the database with the same data. Is there a good way to do this (without scanning through, inserting every record into an array, and then deleting duplicate array entries)? | MySQL supports multi-table DELETE which is really cool and can help here. You can do a self-join on the equality of all columns except the `id`, and then delete the matching row with the greater `id`.
```
DELETE t2
FROM mytable t1 JOIN mytable t2
USING (column1, column2, column3) -- this is an equi-join
WHERE t1.id < t2.id;
``` | ```
DELETE
FROM t
WHERE ID IN (
SELECT MAX(ID)
FROM t
GROUP BY {Your Group Criteria Here}
HAVING COUNT(*) > 1
)
``` | How do I delete two rows that differ only by ID | [
"",
"sql",
"mysql",
""
] |
**EDIT**: This issue has been fixed by google in gtest 1.4.0; [see the original bug report](http://code.google.com/p/googletest/issues/detail?id=114) for more information.
I've recently switched to gtest for my C++ testing framework, and one great feature of it which I am presently unable to use is the ability to generate JUnit-style XML test reports, which could then be read in by our hudson build server.
The XML output generated by the gtest test suite all looks legit:
```
<?xml version="1.0" encoding="UTF-8"?>
<testsuite tests="370" failures="0" disabled="0" errors="0" time="45.61" name="AllTests">
<testsuite name="application" tests="7" failures="0" disabled="0" errors="0" time="8.953">
<testcase name="zero_tasks_on_bootup" status="run" time="0" classname="application" />
...etc.
</testsuite>
</testsuite>
```
I've also tried adding a JUnitReport task to my ant build script, which works fine, and generates XML like so:
```
<?xml version="1.0" encoding="UTF-8"?>
<testsuite tests="370" failures="0" disabled="0" errors="0" time="45.61" name="AllTests">
<testsuite name="application" tests="7" failures="0" disabled="0" errors="0" time="8.953">
<testcase name="zero_tasks_on_bootup" status="run" time="0" classname="application" />
...etc.
</testsuite>
</testsuite>
```
The problem is, whenever I tell ant to publish the JUnit test results, and then point it to either the raw test result XML, or the compiled result generated in the ant JUnitReport task, hudson always complains about finding no test results there.
I'm not a java guy, so I can't tell what's going on here, and I can't find an example of how the JUnit XML ought to look like. Can someone help to point me in the right direction? | **Edit**: Google test has fixed this issue, which is included in the gtest 1.4.0 release. [See the original bug report](http://code.google.com/p/googletest/issues/detail?id=114) for more info.
Bah! I've finally found the cause of this problem -- it's because gtest produces one giant XML file for all test results, and hudson expects one XML test report per class. I've written [a perl script as a workaround for this issue](http://www.teragon.org/stuff/SO/gtest-hudson.pl). To use it, you would make a target in your ant xml script which looks something like this:
```
<target name="runtests">
<exec executable="wherever/${ant.project.name}Test" failonerror="false" dir="tests">
<arg value="--gtest_output=xml:${build.dir}\reports\${ant.project.name}.xml"/>
</exec>
<!-- Workaround for broken gtest output -->
<mkdir dir="${build.dir}/reports/output"/>
<exec executable="perl" failonerror="false" dir="tests">
<arg value="gtest-hudson.pl"/>
<arg value="${build.dir}/reports/${ant.project.name}.xml"/>
<arg value="${build.dir}/reports/output"/>
</exec>
</target>
```
For some reason, gtest also doesn't like the wrong style of slashes being passed to it from ant, so I made my exec for windows only, as my hudson is running on a windows server. Change to '/' for unix, obviously.
I've also [filed an issue for this on the gtest page](http://code.google.com/p/googletest/issues/detail?id=114), and also one on [hudson's issue tracker](https://hudson.dev.java.net/issues/show_bug.cgi?id=3007), so hopefully one of the two teams will pick up on the issue, as I don't have enough time to jump in and make a patch myself.... though if this doesn't get fixed in the near future, I might just have to. ;) | Here's how I do it:
```
<target name="junit" depends="compile-tests" description="run all unit tests">
<mkdir dir="${reports}"/>
<junit haltonfailure="false">
<jvmarg value="-Xms128m"/>
<jvmarg value="-Xmx128m"/>
<classpath>
<path refid="project.classpath"/>
</classpath>
<formatter type="xml"/>
<batchtest fork="yes" todir="${reports}">
<fileset dir="${test}/classes">
<include name="**/*Test*.class"/>
</fileset>
</batchtest>
</junit>
</target>
<target name="generate-reports" depends="junit" description="create JUnit test HTML reports">
<mkdir dir="${reports}"/>
<junitreport todir="${reports}">
<fileset dir="${reports}">
<include name="TEST-*.xml"/>
</fileset>
<report format="frames" todir="${reports}"/>
</junitreport>
</target>
``` | Unable to get hudson to parse JUnit test output XML | [
"",
"c++",
"junit",
"hudson",
"googletest",
""
] |
Like every other web developer on the planet, I have an issue with users double clicking the submit button on my forms. My understanding is that the conventional way to handle this issue, is to disable the button immediately after the first click, however when I do this, **it doesn't post**.
I did do some research on this, god knows there's enough information, but other questions like [Disable button on form submission](https://stackoverflow.com/questions/106509/disable-button-on-form-submission), disabling the button appears to work. The original poster of [Disable button after submit](https://stackoverflow.com/questions/286149/disable-button-after-submit) appears to have had the same problem as me, but there is no mention on how/if he resolved it.
Here's some code on how to repeat it (tested in IE8 Beta2, but had same problem in IE7)
My aspx code
```
<%@ Page Language="C#" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!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">
<script language="javascript" type="text/javascript">
function btn_onClick()
{
var chk = document.getElementById("chk");
if(chk.checked)
{
var btn = document.getElementById("btn");
btn.disabled = true;
}
}
</script>
<body>
<form id="form1" runat="server">
<asp:Literal ID="lit" Text="--:--:--" runat="server" />
<br />
<asp:Button ID="btn" Text="Submit" runat="server" />
<br />
<input type="checkbox" id="chk" />Disable button on first click
</form>
</body>
</html>
```
My cs code
```
using System;
public partial class _Default : System.Web.UI.Page
{
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
btn.Click += new EventHandler(btn_Click);
btn.OnClientClick = "btn_onClick();";
}
void btn_Click(object sender, EventArgs e)
{
lit.Text = DateTime.Now.ToString("HH:mm:ss");
}
}
```
Notice that when you click the button, a postback occurs, and the time is updated. But when you check the check box, the next time you click the button, the button is disabled (as expected), but never does the postback.
WHAT THE HECK AM I MISSING HERE???
Thanks in advance. | I think you're just missing this tag:
```
UseSubmitBehavior="false"
```
Try it like this:
```
<asp:Button ID="btnUpdate" runat="server" UseSubmitBehavior="false" OnClientClick="if(Page_ClientValidate()) { this.disabled = true; } else {return false;}" Text = "Update" CssClass="button" OnClick="btnUpdate_Click" ValidationGroup="vgNew"/>
```
[Explanation](http://rumandcode.wordpress.com/2008/06/20/single-click-aspnet-button/) | `UseSubmitBehavior="false"` converts submit button to normal button (`<input type="button">`). If you don't want this to happen, you can hide submit button and immediately insert disabled button on its place. Because this happens so quickly it will look as button becoming disabled to user. Details are at [the blog of Josh Stodola](http://web.archive.org/web/20090210030547/http://blog.josh420.com/archives/2008/02/how-to-disable-the-submit-button-ofweb-form.aspx).
Code example (jQuery):
```
$("#<%= btnSubmit.ClientID %>").click(function()
{
$(this)
.hide()
.after('<input type="button" value="Please Wait..." disabled="disabled" />');
});
``` | Why doesn't my form post when I disable the submit button to prevent double clicking? | [
"",
"asp.net",
"javascript",
"client-side",
"double-submit-prevention",
""
] |
I've created an ASP.Net user control that will get placed more than once inside of web page. In this control I've defined a javascript object such as:
```
function MyObject( options )
{
this.x = options.x;
}
MyObject.prototype.someFunction=function someFunctionF()
{
return this.x + 1;
}
```
In the code behind I've created MyObject in a startup script --
```
var opts = { x: 99 };
var myObject = new MyObject( opts );
```
When a certain button in the control is pressed it will call myObject.someFunction(). Now lets say the value of x will be 99 for one control but 98 for another control. The problem here is that the var myObject will be repeated and only the last instance will matter. Surely there's a way to make the var myObject unique using some concept I've haven't run across yet. Ideas?
Thanks,
Craig | Your Javascript like this:-
```
function MyObject(options) { this.x = options.x; }
MyObject.prototype.someFunction = function() { return this.x + 1; }
MyObject.create(id, options) {
if (!this._instances) this._instances = {};
return this._instances[id] = new MyObject(options);
}
MyObject.getInstance(id) { return this._instances[id]; }
```
Your startup javascript like this:-
```
MyObject.create(ClientID, {x: 99});
```
Other code that needs to use an instance (say in the client-side onclick event)
```
String.Format("onclick=\"MyObject.getInstance('{0}').someFunction()\", ClientID);
```
Note the low impact on the clients global namespace, only the MyObject identifier is added to the global namespace, regardless of how many instances of your control are added to the page. | Excellent solution Anthony. The other solutions offered were as good and I did consider them but I was looking for something a little more elegant like this solution.
Thanks! | Ideas on making a javascript object name unique in ASP.Net? | [
"",
"asp.net",
"javascript",
"function",
"prototype",
"unique",
""
] |
How to make this work in Opera? I found this piece of code for Opera, but it doesn't work for me:
```
function AddToFavorites(title, url) {
if (window.sidebar) { // Mozilla Firefox Bookmark
window.sidebar.addPanel(title, url,"");
return false;
}
else if( window.external ) { // IE Favorite
window.external.AddFavorite( url, title);
return false;
}
else if(window.opera && window.print) { // Opera Hotlist
var elem = document.createElement('a');
elem.setAttribute('href',url);
elem.setAttribute('title',title);
elem.setAttribute('rel','sidebar');
elem.click();
return false;
}
}
```
The Dragonfly error console is silent, no errors are occuring. | *If* you insist on it, then do it without dynamically generated redundant links:
```
<a href="http://real.url.example.com" title="Bookmark me, pleaeease!"
rel="sidebar"
onclick="return !addToFav(this.href,this.title)">
```
but please, just don't do it.
As Opera user I will be grateful for not pushing that fad โ I can easily drag'n'drop tab to bookmarks bar/panel/speedial if I choose to. | ***Opera enforces the same user-event requirement*** to allow bookmarking, thus the code you have won't work, because the user never clicked on the link you just created.
You need something more like this:
```
function AddToFavorites(obj, title, url){
if(window.sidebar){
// Mozilla Firefox Bookmark
window.sidebar.addPanel(title, url,"");
return false;
} else if(window.external){
// IE Favorite
window.external.AddFavorite( url, title);
return false;
} else if(window.opera && window.print){
//Opera Hotlist
obj.setAttribute('href',url);
obj.setAttribute('title',title);
obj.setAttribute('rel','sidebar');
obj.click();
return false;
}
}
```
CAll with
```
<a href="#" onclick="AddToFavorites(this, 'your title', 'your url');">Bookmark This Page</a>
```
(feel free to make more unobtrusive, I just wanted to indicate the user-event requirement) | "Add to favorites" with JavaScript in Opera | [
"",
"javascript",
"opera",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.