Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Now I have a file with many data in it.
And I know the data I need begins at position (long)x and has a given size sizeof(y)
How can I get this data? | Use the `seek` method:
```
ifstream strm;
strm.open ( ... );
strm.seekg (x);
strm.read (buffer, y);
``` | You should use fseek() to change your "current position" in the file to the desired offset. So, if "f" is your FILE\* variable and offset is the offset this is how the call should look like (modulo my leaky memory):
```
fseek(f, offset, SEEK_SET);
``` | C++ How to read in objects with a given offset? | [
"",
"c++",
"ifstream",
"fileinputstream",
""
] |
I'm writing an iterator that needs to pass around a mutable integer.
```
public IEnumerable<T> Foo(ref int valueThatMeansSomething)
{
// Stuff
yield return ...;
}
```
This nets me "Error 476 Iterators cannot have ref or out parameters".
What I need is this integer value to be modified in the iterator and usable by the caller of the iterator. In other words, whatever calls `Foo()` above wants to know the end value of `valueThatMeansSomething` and `Foo()` may use it itself. Really, I want an integer that is a reference type not a value type.
Only thing I can think of is to write a class that encapsulates my integer and permits me to modify it.
```
public class ValueWrapper<T>
where T : struct
{
public ValueWrapper(T item)
{
this.Item = item;
}
public T Item { get; set; }
}
```
So:
```
ValueWrapper<int> w = new ValueWrapper<int>(0);
foreach(T item in Foo(w))
{
// Do stuff
}
if (w.Item < 0) { /* Do stuff */ }
```
**Is there any class or mechanism to handle this already in the BCL?** Any flaws with `ValueWrapper<T>` proposed above?
(My actual use is more complicated than the example above so handling the variable inside my `foreach` loop that calls `Foo()` is not an option. Period.) | Nope, I'm pretty confident there's nothing existing in the BCL that can do this. Your best option is precisely what you have proposed I think. The implementation of `ValueWrapper` really need not be any more complicated than what you have proposed.
Of course, it's not guaranteed to be thread-safe, but if you need that you can simply convert the automatic property into a standard one with a backing variable and mark the field as [`volatile`](http://msdn.microsoft.com/en-us/library/x13ttww7.aspx) (to insure the value is up-to-date at all times). | If you only need to write the value then another technique would be:
```
public IEnumerable<whatever> Foo(Action<int> setter) { ... }
int value = 0;
foreach(var x in Foo(x => {value=x;}) { ... }
```
Coincidentally, I'll be doing a series on the reasons why there are so many goofy restrictions on iterator blocks in my blog in July. "Why no ref parameters?" will be early in the series.
<http://blogs.msdn.com/ericlippert/archive/tags/Iterators/default.aspx> | Mutable wrapper of value types to pass into iterators | [
"",
"c#",
".net-3.5",
"iterator",
"value-type",
"reference-type",
""
] |
let's say I have a list
```
a = [1,2,3]
```
I'd like to increment every item of that list in place. I want to do something as syntactically easy as
```
for item in a:
item += 1
```
but in that example python uses just the value of `item`, not its actual reference, so when I'm finished with that loop `a` still returns [1,2,3] instead of [2,3,4]. I know I could do something like
```
a = map(lambda x:x+1, a)
```
but that doesn't really fit into my current code and I'd hate to have to rewrite it :-\ | Here ya go:
```
# Your for loop should be rewritten as follows:
for index in xrange(len(a)):
a[index] += 1
```
Incidentally, item IS a reference to the `item` in `a`, but of course you can't assign a new value to an integer. For any mutable type, your code would work just fine:
```
>>> a = [[1], [2], [3], [4]]
>>> for item in a: item += [1]
>>> a
[[1,1], [2,1], [3,1], [4,1]]
``` | In python integers (and floats, and strings, and tuples) are immutable so you have the actual object (and not a copy), you just can't change it.
What's happening is that in the line: `item += 1` you are creating a new integer (with a value of `item + 1`) and binding the name `item` to it.
What you want to do, is change the integer that `a[index]` points to which is why the line `a[index] += 1` works. You're still creating a new integer, but then you're updating the list to point to it.
As a side note:
```
for index,item in enumerate(a):
a[index] = item + 1
```
... is slightly more idiomatic than the answer posted by Triptych. | How do I operate on the actual object, not a copy, in a python for loop? | [
"",
"python",
""
] |
I'm trying to setup a Flex project using the Spring + BlazeDS integration by working through the refcard kindly posted by James Ward on refcards.dzone.com.
Some problems/challenges are sticking their heads out. The Tomcat deployment is going well, all the files are on the server and I can summon main.swf through the browser.
I get the following ActionScript exception when trying to make the AMF request to Spring/BlazeDS:
> RPC Fault faultString="Send failed"
> faultCode="Client.Error.MessageSend"
> faultDetail="Channel.Connect.Failed
> error NetConnection.Call.Failed: HTTP:
> Failed: url:
> '<http://localhost:8080/blazeds/spring/messagebroker/amf>'"
When placing the "Failed: url:" URL directly in the browser, Tomcat displays the following error message:
> HTTP Status 404 - Servlet Spring MVC
> Dispatcher Servlet is not available
I've setup all the files like James Ward instructed on his refcard, application-config.xml, web.xml and services-config.xml are all in order as far as I can see.
Any ideas as to what I'm messing up?
PS: I'm noticing small changes in terms of James' refcard and the stable release of the integration. Is there something that changed after the M2 release that might be biting me in the behind? | I'm going to answer my own question, it all boils down to me being the dummy. There where some .jars that I did not include in my WEB-INF/lib folder. I copied them accross from the blazeds+spring integration testdrive and that fixed my problem! | I have the same problem and I fixed it by adding backport-util-concurrent.jar and cfgatewayadapter.jar from test-drive-sample of flex-spring integration , thank you josamoto for your post , finally the integration works good .
regards | Servlet spring-servlet is not available (Spring+BlazeDS Integration) | [
"",
"java",
"apache-flex",
"spring",
"blazeds",
""
] |
I have what I believe should be simple two-way databinding in WPF setup, but the listbox (target) is not updating as the collection changes.
I'm setting this ItemsSource of the ListBox programmatically:
```
lstVariable_Selected.ItemsSource = m_VariableList;
```
And the ListBox is declared as follows:
```
<ListBox Margin="5" Name="lstVariable_Selected">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<VirtualizingStackPanel Orientation="Horizontal"/>
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
<ListBox.ItemTemplate>
<DataTemplate>
<Border BorderBrush="Gray" BorderThickness="1" Margin="0">
<TextBlock FontSize="25" Text="{Binding Path=Name}" />
</Border>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
```
When I initially set the ItemsSource, the ListBox (which is not visible at the time) gets its items set. However, if I go view the ListBox, updates seem to stop at that point.
I can then remove an item from the m\_VariableList collection, and it does not disappear from the ListBox. Likewise, if I add one, it doesn't appear.
What gives? | Is your m\_VariableList implementing [INotifyCollectionChanged](http://msdn.microsoft.com/en-us/library/system.collections.specialized.inotifycollectionchanged.aspx)? If it's not an ObservableCollection, then changes to it's contents will not automatically be reflected in the UI. | The problem is not in the XAML that you have provided. I used the same XAML successfully in a test application; however, I was able to replicate the issue you are experiencing by re-instantiating the m\_VariableList variable.
When the m\_VariableList is given a new instance, or pointed to a new object, it is not reflected in the ListBox because the control has its own reference to the data. This may not be the cause of your problem, but I'd recommend looking over your code-behind to ensure that the variable is not getting re-instantiated. | WPF ListBox not updating with the ItemsSource | [
"",
"c#",
".net",
"wpf",
"data-binding",
"listbox",
""
] |
I have a situation in which I need to convert a text data into date.
I have used the following code to do so!
---
```
string s = textBox1.Text;
if (String.IsNullOrEmpty(s))
{
textBox2.Text = "Please enter any date.";
}
else
{
DateTime dt = DateTime.Parse(s);
string day = dt.Day.ToString();
string month = dt.Month.ToString();
string year = dt.Year.ToString();
s = day + "/" + month + "/" + year;
textBox2.Text = s;
}
```
---
This will change only the following formats of data.
---
10/10/09 or 10/10/2009----converted date------10/10/2009
12/13/2009 or 12/13/9----converted date-------12/13/2009
10/16----converted date-----------------------16/10/2009
2009/12/10----converted date------------------10/12/2009
---
The following formats are not getting changed to dd/mm/yyyy
---
16/10-dd/mm
060209 or 06022009 ddmmyyyy
13122009 mmddyyyy
20091213 yyyymmdd
20091312 yyyyddmm
20.07.2009/20.07.2009/20-07-2009/20-07-09
---
Can anyone help me out with this.
I am very new to c# | Thanks for all the support and guidance which you ppl gave.
I have found out the solution to my query
A new textbox is created explicitly and using ParseExact function the DateTime value is made to convert.
Below is the form which was used.[alt text http://img146.imageshack.us/img146/2107/form.jpg](http://img146.imageshack.us/img146/2107/form.jpg)
The Code is written below
---
```
private void button1_Click(object sender, EventArgs e)
{
string s = textBox1.Text;
string DFF = textBox3.Text;
//To check whether field is empty
if (String.IsNullOrEmpty(s))
{
MessageBox.Show("Please enter correct date");
textBox2.Text = "Enter correct date";
}
else
{
DateTime dt = DateTime.ParseExact(s, DFF, null);
textBox2.Text = dt.ToShortDateString();
}
}
```
---
This code will give output for all date types:
dd.mm.yyyy or dd-mm-yyyy or dd\mm\yyyy
mm.dd.yyyy or mm-dd-yyyy or mm\dd\yyyy
yyyy.mm.dd or yyyy-mm-dd or yyyy\mm\dd
yyyy.dd.mm or yyyy-dd-mm or yyyy-mm-dd
ddmmyy or mmddyy or yyddmm
dd\mm or mm\dd or dd.mm or mm.dd | Parsing dates is a bit more complicated than that, I'm afraid. It will depend on you culture/country settings. Look at the overloads for [DateTime.Parse](http://msdn.microsoft.com/en-us/library/system.datetime.parse.aspx)...
Also note that when you output your date, you could/should also use [String.Format](http://msdn.microsoft.com/en-us/library/system.string.format.aspx), like so:
```
String.Format("{0:dd/MM/yyyy}", dt)
``` | Conversion of text data into date | [
"",
"c#",
"string-formatting",
""
] |
I'm getting an error I don't know how to fix so I wondering if I could get some help.
This is the error
```
Fatal error: process_form() [<a href='function.process-form'>function.process-form</a>]: The script tried to execute a method or access a property of an incomplete object. Please ensure that the class definition "Template" of the object you are trying to operate on was loaded _before_ unserialize() gets called or provide a __autoload() function to load the class definition in /home/twinmeddev/html/template_add.php on line 44
```
I get this error in the process\_form() function. So what I get out of this is that, its thinking I didn't load the class for the template. Which in fact I did up at the top. The include 'inc/item.class.php'; Do I have to re-include it in the function?
Here's the code for the particular page with the error. You can see I have everything included like it should be. Where have I gone wrong?
```
<?php
include 'inc/prep.php';
include 'inc/header.class.php';
include 'inc/item.class.php';
include 'inc/template.class.php';
include 'inc/formhelper.class.php';
include 'inc/formvalidator.class.php';
include_once( 'inc/config/config.php' ) ;
include_once( 'inc/DBE.class.php' ) ;
include_once( 'inc/GenFuncs.php' ) ;
include_once( 'inc/Search.class.php' ) ;
session_start();
//Verify that user is logged in.
VerifyLogin($_SERVER['PHP_SELF'] . "?" . $_SERVER['QUERY_STRING']);
if(array_key_exists('_submit',$_POST)) {
if($fv_errors = validate_form()) {
show_form($fv_errors);
} else {
process_form();
}
}
else {
// The form wasn't submitted or preview was selected, so display
show_form();
}
function validate_form(){
}
function process_form(){
global $mysqli;
echo var_dump($_SESSION);
$Template = $_SESSION['template'];
$Template->name = $_POST['name'];
$Template->descript = $_POST['descript'];
$Template->user = $_SESSION['User'];
$Template->customer = $_SESSION['CustID'];
$Template->status = $_POST['status'];
$Template->insert();
//header("Location: template.php");
}
``` | It's missing the serialize/unserialize of your template class.
Take a look here for an [working example](https://stackoverflow.com/questions/1038830/php-session-confusion/1039044#1039044) I gave on another question of yours.
For instance, you probably want this:
```
<?php
$_SESSION['template'] = serialize($template);
?>
```
and
```
<?php
$template = unserialize($_SESSION['template']);
?>
```
# Edit:
reading your comment about moving it to the top gives one hint.
The automatic serialization/unserialization occurs when you call `session_start()`.
That means the order in which you include your files and call the `session_start()` is very important.
For example:
This would be wrong:
```
<?php
session_start();
include 'inc/template.class.php';
?>
```
While this would be correct:
```
<?php
include 'inc/template.class.php';
session_start();
?>
```
Now, I see in your example that it is in the CORRECT order, but I also notice you do many other includes before including template.class.php
Would it be possible that one of those includes (perhaps prep.php or header.class.php) does call `start_session()` too?
If yes, that was your issue (`session_start()` being called before your template.class.php). | When you `session_start()` in php `$_SESSION` array is populated with corresponding objects. This means that all interfaces must be available (require). If the session has already been started previously by another script (eg framework) that had no visibility on the interfaces, objects in `$ _SESSION` will be incomplete, and do it again `session_start()` is useless because the session has already been started. One possible solution is to use the method `session_write_close()`, then `session_start()` which starts again populate `$_SESSION`, but with visibility into interface, so your object in `$_SESSION` will be good. | PHP Session with an Incomplete Object | [
"",
"php",
"session",
"object",
""
] |
We have a huge code base and we suspect that there are quite a few "+" based string concats in the code that might benefit from the use of StringBuilder/StringBuffer. Is there an effective way or existing tools to search for these, especially in Eclipse?
A search by "+" isn't a good idea since there's a lot of math in the code, so this needs to be something that actually analyzes the code and types to figure out which additions involve strings. | Just make sure you really understand where it's *actually* better to use `StringBuilder`. I'm not saying you *don't* know, but there are certainly plenty of people who would take code like this:
```
String foo = "Your age is: " + getAge();
```
and turn it into:
```
StringBuilder builder = new StringBuilder("Your age is: ");
builder.append(getAge());
String foo = builder.toString();
```
which is just a less readable version of the same thing. Often the naive solution is the *best* solution. Likewise some people worry about:
```
String x = "long line" +
"another long line";
```
when actually that concatenation is performed at compile-time.
As nsander's quite rightly said, find out if you've got a problem first... | I'm pretty sure [FindBugs](http://findbugs.sourceforge.net/) can detect these. If not, it's still extremely useful to have around.
Edit: It can indeed find [concatenations in a loop](http://findbugs.sourceforge.net/bugDescriptions.html#SBSC_USE_STRINGBUFFER_CONCATENATION), which is the only time it really makes a difference. | How to find all naive ("+" based) string concatenations in large Java codebase? | [
"",
"java",
"optimization",
"string",
""
] |
For my Python application, I have the following directories structure:
```
\myapp
\myapp\utils\
\myapp\utils\GChartWrapper\
\myapp\model\
\myapp\view\
\myapp\controller\
```
One of my class in \myapp\view\ must import a class called [GChartWrapper](http://code.google.com/p/google-chartwrapper/). However, I am getting an import error...
```
myview.py
from myapp.utils.GChartWrapper import *
```
Here is the error:
```
<type 'exceptions.ImportError'>: No module named GChartWrapper.GChart
args = ('No module named GChartWrapper.GChart',)
message = 'No module named GChartWrapper.GChart'
```
What am I doing wrong? I really have a hard time to import modules/classes in Python... | The [`__init__.py` file](http://code.google.com/p/google-chartwrapper/source/browse/trunk/GChartWrapper/__init__.py) of the GChartWrapper package expects the GChartWrapper package on PYTHONPATH. You can tell by the first line:
```
from GChartWrapper.GChart import *
```
Is it necessary to have the GChartWrapper included package in your package directory structure?
If so, then one thing you could do is adding the path where the package resides to sys.path at run time. I take it `myview.py` is in the `myapp\view` directory? Then you could do this before importing `GChartWrapper`:
```
import sys
import os
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'utils')))
```
If it is not necessary to have it in your directory structure, it could be easier to have it installed at the conventional location. You can do that by running the setup.py script that's included in the GChartWrapper source distribution. | You don't import modules and packages from arbritary paths. Instead, in python you use packages and absolute imports. That'll avoid all future problems.
Example:
create the following files:
```
MyApp\myapp\__init__.py
MyApp\myapp\utils\__init__.py
MyApp\myapp\utils\charts.py
MyApp\myapp\model\__init__.py
MyApp\myapp\view\__init__.py
MyApp\myapp\controller\__init__.py
MyApp\run.py
MyApp\setup.py
MyApp\README
```
The files should be empty except for those:
**`MyApp\myapp\utils\charts.py:`**
```
class GChartWrapper(object):
def __init__(self):
print "DEBUG: An instance of GChartWrapper is being created!"
```
**`MyApp\myapp\view\__init__.py:`**
```
from myapp.utils.charts import GChartWrapper
def start():
c = GChartWrapper() # creating instance of the class
```
**`MyApp\run.py:`**
```
from myapp.view import start
start()
```
That's all! When you run your entry point (`run.py`) it calls a function on the view, and that creates an instance of the GChartWrapper class. Using this structure you can import anything anywhere and use it.
To complement, in `MyApp\setup.py` you write an installation program for the MyApp\myapp package. Use [distutils](http://docs.python.org/distutils) to write it:
```
from distutils.core import setup
setup(name='MyApp',
version='1.0',
description='My Beautiful Application',
author='Martin',
author_email='martin@xxxxxxx.com',
url='http://stackoverflow.com/questions/1003843/',
packages=['myapp'],
scripts=['run.py']
)
```
That is enough. Now when people download the MyApp folder, they can just install it using setup.py and run it using run.py. Distutils can generate packages in a number of formats including windows installable .EXE
It's the standard way of distributing python packages/applications. | How to import a module from a directory on level above the current script | [
"",
"python",
"import",
"gchart",
""
] |
In a Java application:
```
currentProcess = Runtime.getRuntime().exec("MyWindowsApp.exe");
...
currentProcess.destroy();
```
Calling `destroy` simply kills the process and doesn't allow any user cleanup or exit code to run. Is it possible to send a process a `WM_CLOSE` message or similar? | You could use [Process.getOutputStream](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Process.html#getOutputStream()) to send a message to the stdin of your app, eg:
```
PrintStream ps = new PrintStream(currentProcess.getOutputStream());
ps.println("please_shutdown");
ps.close();
```
Of course this means you have to contrive to listen on stdin in the Windows app. | you can try with JNA, importing user32.dll and defining an interface that defines at least `CloseWindow` | Is it possible to end a process nicely in a Java application? | [
"",
"java",
""
] |
> **Possible Duplicate:**
> [What is the difference between the following casts in c#?](https://stackoverflow.com/questions/702234/what-is-the-difference-between-the-following-casts-in-c)
In C#, is a there difference between casting an object or using the `as` keyword? Hopefully this code will illustrate what I mean...
```
String text = "Hello hello";
Object obj = text;
String originalCast = ((String)obj).ToUpper();
String originalAs = (obj as String).ToUpper();
``` | [`as`](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/as) will never throw a [`InvalidCastException`](https://learn.microsoft.com/en-us/dotnet/api/system.invalidcastexception). Instead, it returns null if the cast fails (which would give you a [`NullReferenceException`](https://learn.microsoft.com/en-us/dotnet/api/system.nullreferenceexception) if `obj` in your example were not a `string`). | Other than `InvalidCastException` that's already mentioned...
`as` will not work if the target type is a value type (unless it's nullable):
```
obj as int // compile time error.
``` | Difference between casting and as? | [
"",
"c#",
"casting",
""
] |
Is there any speed- and cache-efficient implementations of trie in C/C++?
I know what a trie is, but I don't want reinvent the wheel, implementing it myself. | if you are looking for an ANSI C implementation you can "steal" it from FreeBSD. The file you are looking for is called [radix.c](http://bxr.su/f/sys/net/radix.c). It's used for managing routing data in kernel. | I realize the question was about ready implementations, but for reference...
Before you jump on Judy you should have read "[A Performance Comparison of Judy to Hash Tables](http://www.nothings.org/computer/judy/)". Then googling the title will likely give you a lifetime of discussion and rebutals to read.
The one explicitly cache-conscious trie I know of is the [HAT-trie](http://crpit.com/confpapers/CRPITV62Askitis.pdf).
The HAT-trie, when implemented correctly, is very cool. However, for prefix search you need a sorting step on the hash buckets, which somewhat clashes with the idea of a prefix structure.
A somewhat simpler trie is the [burst-trie](http://www.cs.rmit.edu.au/~jz/fulltext/acmtois02.pdf) which essentially gives you an interpolation between a standard tree of some sort (like a BST) and a trie. I like it conceptually and it's much easier to implement. | Trie implementation | [
"",
"c++",
"c",
"data-structures",
"trie",
""
] |
```
<?php
$query = mysql_query("SELECT * FROM threads
INNER JOIN users
ON threads.poster = users.id
WHERE threads.forum_id = 11");
while($row = mysql_fetch_array($query)) {
<a href="thread.php?id=<?=$row['id']?>">Link</a>
} ?>
```
Theres a column named id in both threads and users. It prints the user id. Any way i got get it to print the thread id without re-naming one of them.
Thanks in advance! | SELECT \*, threads.id as thread\_id FROM ... | SELECT \*, threads.id AS thread\_id ...
Then you can reference thread\_id from $row.
$row['thread\_id'] | SQL question | [
"",
"sql",
""
] |
Is there a package that helps me benchmark JavaScript code? I'm not referring to Firebug and such tools.
I need to compare 2 different JavaScript functions that I have implemented. I'm very familiar with Perl's Benchmark ([Benchmark.pm](https://metacpan.org/pod/Benchmark)) module and I'm looking for something similar in JavaScript.
Has the emphasis on benchmarking JavaScript code gone overboard? Can I get away with timing just one run of the functions? | ~~Just time several iterations of each function. One iteration probably won't be enough, but (depending on how complex your functions are) somewhere closer to 100 or even 1,000 iterations should do the job.~~
~~Firebug also has a [profiler](http://getfirebug.com/js.html) if you want to see which parts of your function are slowing it down.~~
**Edit:** To future readers, the below answer recommending JSPerf should be the correct answer. I would delete mine, but I can't because it has been selected by the OP. There is much more to benchmarking than just running many iterations, and JSPerf takes care of that for you. | Just simple way.
```
console.time('test');
console.timeEnd('test');
``` | How can I benchmark JavaScript code? | [
"",
"javascript",
"benchmarking",
""
] |
Maybe I am missing something but I can't seem to figure this one out.
I have a ReWriteRule:
```
RewriteRule ^view/(\w+)$ view.php?mmdid=$1 [L]
```
and when I go to mydomain.org/view/3, the $\_GET array is empty. There is no key 'mmdid'.
However, when I change my rule to something else, such as:
```
RewriteRule ^viewz/(\w+)$ view.php?mmdid=$1 [L]
```
it works fine when I visit mydomain.org/viewz/3. I get Array ( [mmdid] => 1 ) when printing $\_GET.
There are no other rules similar to this that could conflict, and I've rebooted apache.
Any ideas on why this happens? Is 'view' a keyword or something?
Here is the contents of the Rewrite log:
```
192.168.204.187 - - [15/Jun/2009:13:01:19 --0400] [mydomain.org/sid#2787ab8][rid#2a61030/subreq] (1) [perdir /path/to/webroot/] pass through /path/to/webroot/view.php
192.168.204.187 - - [15/Jun/2009:13:01:19 --0400] [mydomain.org/sid#2787ab8][rid#2a54000/initial] (3) [perdir /path/to/webroot/] add path info postfix: /path/to/webroot/view.php -> /path/to/webroot/view.php/1
192.168.204.187 - - [15/Jun/2009:13:01:19 --0400] [mydomain.org/sid#2787ab8][rid#2a54000/initial] (3) [perdir /path/to/webroot/] strip per-dir prefix: /path/to/webroot/view.php/1 -> view.php/1
192.168.204.187 - - [15/Jun/2009:13:01:19 --0400] [mydomain.org/sid#2787ab8][rid#2a54000/initial] (3) [perdir /path/to/webroot/] applying pattern '^(.*)$' to uri 'view.php/1'
192.168.204.187 - - [15/Jun/2009:13:01:19 --0400] [mydomain.org/sid#2787ab8][rid#2a54000/initial] (4) [perdir /path/to/webroot/] RewriteCond: input='mydomain.org' pattern='^www\.mydomain\.org$' => not-matched
192.168.204.187 - - [15/Jun/2009:13:01:19 --0400] [mydomain.org/sid#2787ab8][rid#2a54000/initial] (1) [perdir /path/to/webroot/] pass through /path/to/webroot/view.php
192.168.204.187 - - [15/Jun/2009:13:01:19 --0400] [mydomain.org/sid#2787ab8][rid#2930e58/subreq] (1) [perdir /path/to/webroot/] pass through /path/to/webroot/1
```
Here is the output of the log when using just ^v/(\w+)$....
```
192.168.204.187 - - [15/Jun/2009:13:10:09 --0400] [mydomain.org/sid#2787ab8][rid#2a63038/initial] (3) [perdir /path/to/webroot/] add path info postfix: /path/to/webroot/v -> /path/to/webroot/v/1
192.168.204.187 - - [15/Jun/2009:13:10:09 --0400] [mydomain.org/sid#2787ab8][rid#2a63038/initial] (3) [perdir /path/to/webroot/] strip per-dir prefix: /path/to/webroot/v/1 -> v/1
192.168.204.187 - - [15/Jun/2009:13:10:09 --0400] [mydomain.org/sid#2787ab8][rid#2a63038/initial] (3) [perdir /path/to/webroot/] applying pattern '^v/([0-9]+)$' to uri 'v/1'
192.168.204.187 - - [15/Jun/2009:13:10:09 --0400] [mydomain.org/sid#2787ab8][rid#2a63038/initial] (2) [perdir /path/to/webroot/] rewrite 'v/1' -> 'view.php?mmdid=1'
192.168.204.187 - - [15/Jun/2009:13:10:09 --0400] [mydomain.org/sid#2787ab8][rid#2a63038/initial] (3) split uri=view.php?mmdid=1 -> uri=view.php, args=mmdid=1
192.168.204.187 - - [15/Jun/2009:13:10:09 --0400] [mydomain.org/sid#2787ab8][rid#2a63038/initial] (3) [perdir /path/to/webroot/] add per-dir prefix: view.php -> /path/to/webroot/view.php
192.168.204.187 - - [15/Jun/2009:13:10:09 --0400] [mydomain.org/sid#2787ab8][rid#2a63038/initial] (2) [perdir /path/to/webroot/] strip document_root prefix: /path/to/webroot/view.php -> /view.php
192.168.204.187 - - [15/Jun/2009:13:10:09 --0400] [mydomain.org/sid#2787ab8][rid#2a63038/initial] (1) [perdir /path/to/webroot/] internal redirect with /view.php [INTERNAL REDIRECT]
192.168.204.187 - - [15/Jun/2009:13:10:09 --0400] [mydomain.org/sid#2787ab8][rid#2a5ebc0/initial/redir#1] (3) [perdir /path/to/webroot/] strip per-dir prefix: /path/to/webroot/view.php -> view.php
192.168.204.187 - - [15/Jun/2009:13:10:09 --0400] [mydomain.org/sid#2787ab8][rid#2a5ebc0/initial/redir#1] (3) [perdir /path/to/webroot/] applying pattern '^v/([0-9]+)$' to uri 'view.php'
192.168.204.187 - - [15/Jun/2009:13:10:09 --0400] [mydomain.org/sid#2787ab8][rid#2a5ebc0/initial/redir#1] (3) [perdir /path/to/webroot/] strip per-dir prefix: /path/to/webroot/view.php -> view.php
192.168.204.187 - - [15/Jun/2009:13:10:09 --0400] [mydomain.org/sid#2787ab8][rid#2a5ebc0/initial/redir#1] (3) [perdir /path/to/webroot/] applying pattern '^(.*)$' to uri 'view.php'
192.168.204.187 - - [15/Jun/2009:13:10:09 --0400] [mydomain.org/sid#2787ab8][rid#2a5ebc0/initial/redir#1] (4) [perdir /path/to/webroot/] RewriteCond: input='mydomain.org' pattern='^www\.mydomain\.org$' => not-matched
192.168.204.187 - - [15/Jun/2009:13:10:09 --0400] [mydomain.org/sid#2787ab8][rid#2a5ebc0/initial/redir#1] (1) [perdir /path/to/webroot/] pass through /path/to/webroot/view.php
```
Thank you, | Perhaps your script name clashes with the rewrite. Try renaming your script to view.page.php, after all if you're rewriting it makes no difference what the script is called.
For more information on how your script is being called use
```
var_dump($_SERVER);
``` | It’s probably [`MultiViews`](http://httpd.apache.org/docs/2.2/content-negotiation.html#multiviews) that’s causing this behavior. Try to disable it:
```
Options -MultiViews
``` | Why is my variable not being put into $_GET? | [
"",
"php",
"mod-rewrite",
"url-rewriting",
""
] |
can anyone help? I have small procedure to read in an UTF-8 file with javascript using XMLHttpRequest.. this file has european characters like miércoles sábado etc.. Notice the accents..
But when being read in .. the characters are all messed up.. I have checked the file and it is perfect.. it must be the procedure for reading in..
heres an example i have file that contains, the file is perfect, it happens to be javascript but it doesn't matter.. any UTF-8 encoding file with special characters gives me the same issue
this.weekDays = new Array("Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo");
but when returned and read by the procedure below it is like this (notice the funny characters in sabado and miercoles)
this.weekDays = new Array("Lunes", "Martes", "Miércoles", "Jueves", "Viernes", "Sábado", "Domingo");
Here is my procedure - its very small...
```
var contentType = "application/x-www-form-urlencoded; charset=utf-8";
var request = new XMLHttpRequest();
request.open("GET", path, false);
request.setRequestHeader('Content-type', contentType)
if (request.overrideMimeType) request.overrideMimeType(contentType);
try { request.send(null); }
catch (e) { return null; }
if (request.status == 500 || request.status == 404 || request.status == 2 || (request.status == 0 && request.responseText == '')) return null;
//PROBLEM HERE is with european charcters that are read in
print(request.responseText);
return request.responseText;
``` | EDIT: Seems that this answer, although accepted, is suboptimal, so for anyone coming here with a similar problem, check out [Ricardo's answer](https://stackoverflow.com/a/21798825/34065)
I think you have to use a different way to print the characters, for example, see the code at the end of [this discussion](http://www.codingforums.com/archive/index.php/t-4588.html):
```
<script>
function getUnicode(num) {
num = num.toString(16);
if (num.length < 3) {
for ( var i = num.length; i < 4; i++) {
num = '0' + num;
}
}
return ( "&#" + num + ";" );
}
for ( var i = 0; i < 65355; i++) {
document.write(getUnicode(i));
}
</script>
``` | Probably your file is not in UTF-8 then try this from javascript:
```
var request = new XMLHttpRequest();
request.open("GET", path, false);
request.overrideMimeType('text/xml; charset=iso-8859-1');
``` | reading in utf-8 file (javascript XMLHttpRequest) gives bad european characters | [
"",
"javascript",
"encoding",
"utf-8",
"xmlhttprequest",
""
] |
Is it a bug to do this:
```
if(some_error)
throw Cat("Minoo");
```
Where Cat is a class.
Then in some other function that called the method that threw the exception...
I would have:
```
catch(const Cat &c)
{
}
```
If it is invalid, do I use new Cat("Minoo");
Would that cause a memory leak? | 1) Invalid? No, that's precisely what you're supposed to do: throw an object. The object in the throw-statement may be on the stack, but it is copied when it is thrown. Compare, for example, the effect of executing return Cat("Minoo");
2) Will throwing a pointer cause the pointed-to object to be leaked? Yes, if the object was allocated on the heap and unless you arrange to delete it. But you should avoid throwing pointers as a general rule. | What you have now is what everyone should be doing, and most do. Throw the object itself and catch by const-reference.
Throwing pointers has hairy issues such as "who deletes it?".
More information [here](http://www.parashift.com/c++-faq-lite/exceptions.html). | throwing exceptions of objects on the stack, mem leak with new? | [
"",
"c++",
"exception",
""
] |
A bit more specific than Stack Overflow question *[What is an existential type?](https://stackoverflow.com/questions/292274/what-is-an-existential-type)*, what is the difference between Scala's *existential types* and Java's *wildcard*, prefereably with some illustrative example?
In everything I've seen so far, they seem to be pretty equivalent.
*A few references. Martin Odersky [mentions them](http://www.artima.com/scalazine/articles/scalas_type_system.html); Google's [top hit for my question](http://scalada.blogspot.com/2008/01/existential-types.html)*:
> **MO:** The original wildcard design ... was inspired by existential types. In fact the original paper had an encoding in existential types. But then when the actual final design came out in Java, this connection got lost a little bit | This is Martin Odersky's answer on the Scala-users mailing list:
> The original Java wildcard types (as described in the ECOOP paper by
> Igarashi and Viroli) were indeed just shorthands for existential
> types. I am told and I have read in the FOOL '05 paper on Wild FJ that
> the final version of wildcards has some subtle differences with
> existential types. I would not know exactly in what sense (their
> formalism is too far removed from classical existential types to be
> able to pinpoint the difference), but maybe a careful read of the Wild
> FJ paper would shed some light on it.
So it does seem that Scala existential types and Java wildcards are kind-of equivalent | They are supposed to be equivalent, as their main purpose is interacting with Java's wildcards. | Difference between Scala's existential types and Java's wildcard by example? | [
"",
"java",
"scala",
"type-systems",
"bounded-wildcard",
"existential-type",
""
] |
I have seen it asserted several times now that the following code is not allowed by the C++ Standard:
```
int array[5];
int *array_begin = &array[0];
int *array_end = &array[5];
```
Is `&array[5]` legal C++ code in this context?
I would like an answer with a reference to the Standard if possible.
It would also be interesting to know if it meets the C standard. And if it isn't standard C++, why was the decision made to treat it differently from `array + 5` or `&array[4] + 1`? | Your example is legal, but only because you're not actually using an out of bounds pointer.
Let's deal with out of bounds pointers first (because that's how I originally interpreted your question, before I noticed that the example uses a one-past-the-end pointer instead):
In general, you're not even allowed to **create** an out-of-bounds pointer. A pointer must point to an element within the array, or *one past the end*. Nowhere else.
The pointer is not even allowed to exist, which means you're obviously not allowed to dereference it either.
Here's what the standard has to say on the subject:
5.7:5:
> When an expression that has integral
> type is added to or subtracted from a
> pointer, the result has the type of
> the pointer operand. If the pointer
> operand points to an element of an
> array object, and the array is large
> enough, the result points to an
> element offset from the original
> element such that the difference of
> the subscripts of the resulting and
> original array elements equals the
> integral expression. In other words,
> if the expression P points to the i-th
> element of an array object, the
> expressions (P)+N (equivalently,
> N+(P)) and (P)-N (where N has the
> value n) point to, respectively, the
> i+n-th and i−n-th elements of the
> array object, provided they exist.
> Moreover, if the expression P points
> to the last element of an array
> object, the expression (P)+1 points
> one past the last element of the array
> object, and if the expression Q points
> one past the last element of an array
> object, the expression (Q)-1 points to
> the last element of the array object.
> If both the pointer operand and the
> result point to elements of the same
> array object, or one past the last
> element of the array object, the
> evaluation shall not produce an
> overflow; **otherwise, the behavior is
> undefined**.
(emphasis mine)
Of course, this is for operator+. So just to be sure, here's what the standard says about array subscripting:
5.2.1:1:
> The expression `E1[E2]` is identical (by definition) to `*((E1)+(E2))`
Of course, there's an obvious caveat: Your example doesn't actually show an out-of-bounds pointer. it uses a "one past the end" pointer, which is different. The pointer is allowed to exist (as the above says), but the standard, as far as I can see, says nothing about dereferencing it. The closest I can find is 3.9.2:3:
> [Note: for instance, the address one past the end of an array (5.7) would be considered to
> point to an unrelated object of the array’s element type that might be located at that address. —end note ]
Which seems to me to imply that yes, you can legally dereference it, but the result of reading or writing to the location is unspecified.
Thanks to ilproxyil for correcting the last bit here, answering the last part of your question:
* `array + 5` doesn't actually
dereference anything, it simply
creates a pointer to one past the end
of `array`.
* `&array[4] + 1` dereferences
`array+4` (which is perfectly safe),
takes the address of that lvalue, and
adds one to that address, which
results in a one-past-the-end pointer
(but that pointer never gets
dereferenced.
* `&array[5]` dereferences array+5
(which as far as I can see is legal,
and results in "an unrelated object
of the array’s element type", as the
above said), and then takes the
address of that element, which also
seems legal enough.
So they don't do quite the same thing, although in this case, the end result is the same. | Yes, it's legal. From the [C99 draft standard](http://www.open-std.org/JTC1/SC22/WG14/www/docs/n1256.pdf):
§6.5.2.1, paragraph 2:
> A postfix expression followed by an expression in square brackets `[]` is a subscripted
> designation of an element of an array object. The definition of the subscript operator `[]`
> is that `E1[E2]` is identical to `(*((E1)+(E2)))`. Because of the conversion rules that
> apply to the binary `+` operator, if `E1` is an array object (equivalently, a pointer to the
> initial element of an array object) and `E2` is an integer, `E1[E2]` designates the `E2`-th
> element of `E1` (counting from zero).
§6.5.3.2, paragraph 3 (emphasis mine):
> The unary `&` operator yields the address of its operand. If the operand has type ‘‘*type*’’,
> the result has type ‘‘pointer to *type*’’. If the operand is the result of a unary `*` operator,
> neither that operator nor the `&` operator is evaluated and the result is as if both were
> omitted, except that the constraints on the operators still apply and the result is not an
> lvalue. Similarly, **if the operand is the result of a `[]` operator, neither the & operator nor the unary `*` that is implied by the `[]` is evaluated and the result is as if the `&` operator
> were removed and the `[]` operator were changed to a `+` operator**. Otherwise, the result is
> a pointer to the object or function designated by its operand.
§6.5.6, paragraph 8:
> When an expression that has integer type is added to or subtracted from a pointer, the
> result has the type of the pointer operand. If the pointer operand points to an element of
> an array object, and the array is large enough, the result points to an element offset from
> the original element such that the difference of the subscripts of the resulting and original
> array elements equals the integer expression. In other words, if the expression `P` points to
> the `i`-th element of an array object, the expressions `(P)+N` (equivalently, `N+(P)`) and
> `(P)-N` (where `N` has the value `n`) point to, respectively, the `i+n`-th and `i−n`-th elements of
> the array object, provided they exist. Moreover, if the expression `P` points to the last
> element of an array object, the expression `(P)+1` points one past the last element of the
> array object, and if the expression `Q` points one past the last element of an array object,
> the expression `(Q)-1` points to the last element of the array object. If both the pointer
> operand and the result point to elements of the same array object, or one past the last
> element of the array object, the evaluation shall not produce an overflow; otherwise, the
> behavior is undefined. If the result points one past the last element of the array object, it
> shall not be used as the operand of a unary `*` operator that is evaluated.
Note that the standard explicitly allows pointers to point one element past the end of the array, *provided that they are not dereferenced*. By 6.5.2.1 and 6.5.3.2, the expression `&array[5]` is equivalent to `&*(array + 5)`, which is equivalent to `(array+5)`, which points one past the end of the array. This does not result in a dereference (by 6.5.3.2), so it is legal. | Take the address of a one-past-the-end array element via subscript: legal by the C++ Standard or not? | [
"",
"c++",
"c",
"standards",
"language-lawyer",
""
] |
We are creating a simple but improved billing solution. Since we have to use different providers based on a number of reasons that is of no importance right now I was thinking of what would be the best way to handle this. The different providers might have a key and a value. I can store the value as object but then I need to store the type as well. I was thinking of creating a hmm let's call it Tuple class:
```
public class Tuple<TType, TValue>
{
public TType Type { get; set; }
public TValue Value { get; set; }
}
```
Now I can use this for storing the type reference but it I have a feeling something is missing. To use this with a lookup collection like dictionary I could:
```
public IDictionary<string, Tuple<Type, object>> TechnicalDetails =
new Dictionary<string, Tuple<Type, object>>
```
Suggestions for improvement? There has got to be a better way? :) | In cases like this, I tend to write a class to contain/hide the data structure, and to provide methods and properties which abstract away the details of the data structure, in this case, your `Dictionary<string, Tuple<Type, object>>`.
Methods like Find( ), Get( ), Add( ), Remove( ) etc, are easy to add since the data structure itself already has similar methods. | how many items are you going to store in the dictionary? a [hybrid dictonary](http://msdn.microsoft.com/en-us/library/system.collections.specialized.hybriddictionary.aspx) might offer better performance? | What generic/dynamic collection to use? (design issue) | [
"",
"c#",
""
] |
I'm a C and Java programmer, so memory allocation and OOP aren't anything new to me. But, I'm not sure about how exactly to avoid memory leaks with C++ implementation of objects. Namely:
```
string s1("0123456789");
string s2 = s1.substr(0,3);
```
`s2` now has a new string object, so it must be freed via:
```
delete &s2;
```
Right?
Moreover, am I correct to assume that I'll have to delete the address for any (new) object returned by a function, regardless of the return type not being a pointer or reference? It just seems weird that an object living on the heap wouldn't be returned as a pointer when it must be freed. | No,
Both `s1` and `s2` will get destructed when out of scope.
`s1.substr()` will create a temporary object that you don't have to think of. | No.
You only need to free memory you allocate (i.e. via new or memalloc). | C++ dynamic memory detail | [
"",
"c++",
"memory",
"memory-management",
"dynamic",
"free",
""
] |
Functions come up as undefined if I place them in the document.ready() function:
```
$(document).ready(function(){
function foo()
{
alert('Bar');
}
});
foo(); // Undefined
```
Why does this happen? I'm sure I'm just in need of some simple understanding :) | Not sure why defining the function with in the scope of `ready()` is important to you, but you can make it work by declaring `foo` up front:
```
<html><head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.1/jquery.min.js"></script>
<script>
var foo; // Here's the difference
$(document).ready(function(){
foo = function ()
{
alert('Bar');
}
});
</script></head><body>
<input type="button" onclick="foo()" value="Click me">
</body></html>
```
Obviously you can't call `foo()` from the inline script immediately after `ready()` because the `ready()` code hasn't yet run, but you can call the function later on.
Just make sure that nothing can try to call `foo()` before the `ready()` code has run (or make the initial declaration of `foo()` a harmless function). | You can but they must be called within the scope of the `ready()` method otherwise they lose scope when the `ready()` method exits.
For example, the code below will work:
```
$(document).ready(function(){
function foo()
{
alert('Bar');
}
foo(); // still in the scope of the ready method
});
``` | Why can I not define functions in jQuery's document.ready()? | [
"",
"javascript",
"jquery",
""
] |
Is there any way for me to use a string to call a method of a class? Here's an example that will hopefully explain better (using the way I think it should be):
```
class helloworld():
def world(self):
print "Hello World!"
str = "world"
hello = helloworld()
hello.`str`()
```
Which would output `Hello World!`.
Thanks in advance. | You can use [`getattr`](http://docs.python.org/3.0/library/functions.html#getattr):
```
>>> class helloworld:
... def world(self):
... print("Hello World!")
...
>>> m = "world"
>>> hello = helloworld()
>>> getattr(hello, m)()
Hello World!
```
* Note that the parens in `class helloworld()` as in your example are unnecessary, in this case.
* And, as [SilentGhost](https://stackoverflow.com/users/12855/silentghost) points out, [`str`](http://docs.python.org/3.0/library/functions.html#str) is an unfortunate name for a variable. | *Warning: exec is a dangerous function to use, study it before using it*
You can also use the built-in function "exec":
```
>>> def foo(): print('foo was called');
...
>>> some_string = 'foo';
>>> exec(some_string + '()');
foo was called
>>>
``` | Using string as variable name | [
"",
"python",
""
] |
How do you say something like this?
```
static const string message = "This is a message.\n
It continues in the next line"
```
The problem is, the next line isn't being recognized as part of the string..
How to fix that? Or is the only solution to create an array of strings and then initialize the array to hold each line? | Enclose each line in its own set of quotes:
```
static const string message = "This is a message.\n"
"It continues in the next line";
```
The compiler will combine them into a single string. | You can use a trailing slash or quote each line, thus
```
"This is a message.\n \
It continues in the next line"
```
or
```
"This is a message."
"It continues in the next line"
``` | Separating a large string | [
"",
"c++",
"string",
""
] |
Is this possible? Given that C# uses immutable strings, one could expect that there would be a method along the lines of:
```
var expensive = ReadHugeStringFromAFile();
var cheap = expensive.SharedSubstring(1);
```
If there is no such function, why bother with making strings immutable?
Or, alternatively, if strings are already immutable for other reasons, why not provide this method?
The specific reason I'm looking into this is doing some file parsing. Simple recursive descent parsers (such as the one generated by TinyPG, or ones easily written by hand) use Substring all over the place. This means if you give them a large file to parse, memory churn is unbelievable. Sure there are workarounds - basically roll your own SubString class, and then of course forget about being able to use String methods such as StartsWith or String libraries such as Regex, so you need to roll your own version of these as well. I assume parser generators such as ANTLR basically do that, but my format is simple enough not to justify using such a monster tool. Even TinyPG is probably an overkill.
Somebody please tell me I am missing some obvious or not-so-obvious standard C# method call somewhere... | No, there's nothing like that.
.NET strings contain their text data directly, unlike Java strings which have a reference to a char array, an offset and a length.
Both solutions have "wins" in some situations, and losses in others.
If you're absolutely *sure* this will be a killer for you, you could implement a Java-style string for use in your own internal APIs. | As far as I know, all larger parsers use streams to parse from. Isn't that suitable for your situation? | Sharing character buffer between C# strings objects | [
"",
"c#",
"parsing",
"memory-management",
"substring",
""
] |
I have a string value that its length is 5000 + characters long , i want to split this into 76 characters long with a new line at the end of each 76 characters. how woudld i do this in c#? | If you're writing Base64 data, try writing
```
Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks);
```
This will insert a newline every 76 characters | A little uglier ... but much faster ;) (this version took 161 ticks... Aric's took 413)
I posted my test code on my blog. <http://hackersbasement.com/?p=134>
(I also found StringBuilder to be much slower than string.Join)
<http://hackersbasement.com/?p=139> <= updated results
```
string chopMe = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
Stopwatch sw = new Stopwatch();
sw.Start();
char[] chopMeArray = chopMe.ToCharArray();
int totalLength = chopMe.Length;
int partLength = 12;
int partCount = (totalLength / partLength) + ((totalLength % partLength == 0) ? 0 : 1);
int posIndex = 0;
char[] part = new char[partLength];
string[] parts = new string[partCount];
int get = partLength;
for (int i = 0; i < partCount; i++)
{
get = Math.Min(partLength, totalLength - posIndex);
Array.Copy(chopMeArray, posIndex, part, 0, get);
parts[i] = new string(part, 0, get);
posIndex += partLength;
}
var output = string.Join("\r\n", parts) + "\r\n";
sw.Stop();
Console.WriteLine(sw.ElapsedTicks);
``` | Split String by length | [
"",
"c#",
".net",
"regex",
"split",
""
] |
please just point me in the right direction or tell me what to look up to solve this:
I have a "tree" object that holds "node" objects. (actually it's called a directed graph).
Each node holds the fields string "name" and "list" that contains the next nodes.
How can I create lists of all possible node names from the head node to the foot node?
each list is to hold a path from head to foot. the number of nodes from head to foot is always the same i.e: 6.
this is what the tree looks like:

that diagram should give me:
```
list 1: n1,n2,n4,n5,n7,n9,n13.
lsit 2: n1,n2,n4,n6,n8,n9,n13.
list 3: n1,n2,n4,n10,n11,n12,n13
```
and so on.
could some simply point me in the right direction? what kind of recursive algorithm should i use? should i use a recursive method or only loops? (i need to use this on the result of the dikstra algorithm.) | Do either a BFS or a DFS, and keep track of the path along with the node. When the node has no more children, dump the path. Note that you have a graph/forest instead of a tree, but the algorithm I outlined will work just the same.
To start you off using a BFS:
```
Step 1. [n1]
Step 2. [n2(n1), n3(n1)]
Step 3. [n3(n1), n4(n1,n2)]
Step 4. [n4(n1, n2), n4(n1, n3)]
Step 5. [n4(n1, n3), n5(n1, n2, n4), n6(n1, n2, n4), n10(n1, n2, n4)]
Step 6. [n5(n1, n2, n4), n6(n1, n2, n4), n10(n1, n2, n4), n5(n1, n3, n4), n6(n1, n3, n4), n10(n1, n3, n4)]
```
...
and so on. In the end you will have your paths. which will get printed out. You can implement this algorithm without requiring recursion. Just loop till the array is empty.
Makes sense? | That's a graph, not a tree. <http://en.wikipedia.org/wiki/Tree_structure>
So... my pointer would be, you're looking for a solution in [graph theory](http://en.wikipedia.org/wiki/Path_(graph_theory)). If you get stuck, a bit of google-fu around that term and your problem should yield algorithms to implement. | how can i list every path in a directed graph? (C#) | [
"",
"c#",
"list",
"recursion",
"tree",
""
] |
> **Possible Duplicate:**
> [How do I use PHP variables as values for the <script> tag when rendering jQuery code in my CakePHP view?](https://stackoverflow.com/questions/980361/how-do-i-use-php-variables-as-values-for-the-script-tag-when-rendering-jquery)
In CakePHP, the value passed as a parameter in the url can be obtained by the controller attribute
```
<?php $userid= $this->params['pass'][0];?>
```
I want to use $userid inside the jQuery code.
```
$("#displayPanel #saveForm").live("click", function(){
document.location = 'http://localhost/cake_1_2/forms/homepage';
});//Click on SaveForm
```
Suppose if the userid is 12, I need the document.location to be '<http://localhost/cake_1_2/forms/homepage/12>'.
How to use the php variable in jQuery? | For readability, how about:
```
<?php $userid= $this->params['pass'][0];?>
var userId = '<?=$userid?>';
$("#displayPanel #saveForm").live("click", function(){
document.location = 'http://localhost/cake_1_2/forms/homepage/' + userId;
});
``` | You'll need to output the variable into the JavaScript source:
```
$("#displayPanel #saveForm").live("click", function(){
document.location = 'http://localhost/cake_1_2/forms/homepage/<?=$userid?>';
});//Click on SaveForm
```
Note the `<?=$userid?>`. If shorthand is turned off on your server, use `<?php echo $userid; ?>`. | php code in jquery | [
"",
"php",
"jquery",
"cakephp",
""
] |
Programming in Android, most of the text values are expected in `CharSequence`.
Why is that? What is the benefit, and what are the main impacts of using `CharSequence` over `String`?
What are the main differences, and what issues are expected, while using them, and converting from one to another? | [Strings are CharSequences](http://download.oracle.com/javase/6/docs/api/java/lang/String.html), so you can just use Strings and not worry. Android is merely trying to be helpful by allowing you to also specify other CharSequence objects, like StringBuffers. | # `CharSequence` = interface `String` = concrete implementation
* [`CharSequence`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/CharSequence.html) is an [interface](https://en.wikipedia.org/wiki/Interface_(Java)).
* Several classes [implement](https://en.wikipedia.org/wiki/Interface_(Java)#Implementing_interfaces_in_a_class) this interface.
+ [`String`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/String.html) is one such class, a concrete implementation of `CharSequence`.
You said:
> converting from one to another
There is no converting from `String`.
* Every `String` object *is* a `CharSequence`.
* Every `CharSequence` can produce a `String`. Call [`CharSequence::toString`](https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/lang/CharSequence.html#toString()). If the `CharSequence` happens to be a `String`, then the method returns a reference to its own object.
In other words, every `String` is a `CharSequence`, but not every `CharSequence` is a `String`.
## Programming to an interface
> Programming in Android, most of the text values are expected in CharSequence.
>
> Why is that? What is the benefit, and what are the main impacts of using CharSequence over String?
Generally, programming to an interface is better than programming to concrete classes. This yields flexibility, so we can switch between concrete implementations of a particular interface without breaking other code.
When developing an [API](https://en.wikipedia.org/wiki/Application_programming_interface) to be used by various programmers in various situations, write your code to give and take the most general interfaces possible. This gives the calling programmer the freedom to use various implementations of that interface, whichever implementation is best for their particular context.
For example, look at the [Java Collections Framework](https://en.wikipedia.org/wiki/Java_collections_framework). If your API gives or takes an ordered collection of objects, declare your methods as using `List` rather than `ArrayList`, `LinkedList`, or any other 3rd-party implementation of `List`.
When writing a quick-and-dirty little method to be used only by your code in one specific place, as opposed to writing an API to be used in multiple places, you need not bother with using the more general interface rather than a specific concrete class. But even then, it does to hurt to use the most general interface you can.
> What are the main differences, and what issues are expected, while using them,
* With a `String` you know you have a single piece of text, entirely in memory, and is immutable.
* With a `CharSequence`, you do not know what the particular features of the concrete implementation might be.
The `CharSequence` object might represent an enormous chunk of text, and therefore has memory implications. Or may be many chunks of text tracked separately that will need to be stitched together when you call `toString`, and therefore has performance issues. The implementation may even be retrieving text from a remote service, and therefore has latency implications.
> and converting from one to another?
You generally won't be converting back and forth. A `String` *is* a `CharSequence`. If your method declares that it takes a `CharSequence`, the calling programmer may pass a `String` object, or may pass something else such as a `StringBuffer` or `StringBuilder`. Your method's code will simply use whatever is passed, calling any of the `CharSequence` methods.
The closest you would get to converting is if your code receives a `CharSequence` and you know you need a `String`. Perhaps your are interfacing with old code written to `String` class rather than written to the `CharSequence` interface. Or perhaps your code will work intensively with the text, such as looping repeatedly or otherwise analyzing. In that case, you want to take any possible performance hit only once, so you call `toString` up front. Then proceed with your work using what you know to be a single piece of text entirely in memory.
# Twisted history
Note the comments made on the [accepted Answer](https://stackoverflow.com/a/1049244/642706). The `CharSequence` interface was retrofitted onto existing class structures, so there are some important subtleties (`equals()` & `hashCode()`). Notice the various versions of Java (1, 2, 4 & 5) tagged on the classes/interfaces—quite a bit of churn over the years. Ideally `CharSequence` would have been in place from the beginning, but such is life.
My class diagram below may help you see the big picture of string types in Java 7/8. I'm not sure if all of these are present in Android, but the overall context may still prove useful to you.
 | CharSequence VS String in Java? | [
"",
"java",
"string",
"charsequence",
""
] |
I have a C++ dll that I need to call from C#. One of the functions in the dll requires a char\* for an input parameter, and another function uses a char\* as an output parameter.
What is the proper way to call these from C#? | Just using strings will work fine for input parameters, though you can control details about the string with the MarshalAs attribute. E.g.
```
[DllImport("somedll.dll", CharSet = CharSet.Unicode)]
static extern void Func([MarshalAs(UnmanagedType.LPWStr)] string wideString);
```
As for returning char\* parameters, that's a little more complex since object ownership is involved. If you can change the C++ DLL you can use CoTaskMemAllocate, with something like:
```
void OutputString(char*& output)
{
char* toCopy = "hello...";
size_t bufferSize = strlen(toCopy);
LPVOID mem = CoTaskMemAlloc(bufferSize);
memcpy(mem, toCopy, bufferSize);
output = static_cast<char*>(mem);
}
```
The C# side then just uses an 'out string' parameter, and the garbage collector can pick up the ownership of the string.
Another way of doing it would be to use a StringBuilder, but then you need to know how big the string will be before you actually call the function. | string should work if the parameter is read-only, if the method modifies the string you should use StringBuilder instead.
Example from reference below:
```
[DllImport ("libc.so")]
private static extern void strncpy (StringBuilder dest,
string src, uint n);
private static void UseStrncpy ()
{
StringBuilder sb = new StringBuilder (256);
strncpy (sb, "this is the source string", sb.Capacity);
Console.WriteLine (sb.ToString());
}
```
If you don't know how p/invoke marshaling works you could read <http://www.mono-project.com/Interop_with_Native_Libraries>
If you are only conserning with strings, read only the section: <http://www.mono-project.com/Interop_with_Native_Libraries#Strings> | Calling DLL function with char* param from C#? | [
"",
"c#",
""
] |
i want to capture all tags named 'STRONG' i can use `<STRONG.*?</STRONG>` this is working just fine but i dont want to capture these tags if the 'SPAN' tags come in these tags i want something like `<STRONG.*(^(SPAN)).*?</STRONG>`
this is the sample text
```
<STRONG> For technical <SPAN id=PageBreak>101</SPAN> please</STRONG>
<SPAN id=PageBreak type="4">56</SPAN><STRONG> visit</STRONG>
```
i want to capture the second strong tag and not the first one | Konrad is right.
But in case you don't care about imminent doom you could try something like
```
/<STRONG>\w+?<\/STRONG>/
```
Which will ignore STRONG tags if they enclose anything that isn't a word character, such as the `'<'` of `'<SPAN>'`, but will no doubt fail for anything out of the ordinary...leading back to the point about a doomed attempt. | You're trying to parse HTML structure using a regular expression, which is doomed to fail since the HTML language isn't regular (see [hierarchy of formal languages](http://en.wikipedia.org/wiki/Chomsky_hierarchy)).
Use an HTML parser instead, e.g. the [HTML Agility Pack](http://www.codeplex.com/htmlagilitypack). See also [these](https://stackoverflow.com/questions/100358/looking-for-c-html-parser) [other](https://stackoverflow.com/questions/56107/what-is-the-best-way-to-parse-html-in-c) [questions](https://stackoverflow.com/questions/916057/suggestion-needed-best-way-of-parsing-html-in-c). | i want to capture all tags not having a specific tag | [
"",
"c#",
".net",
"regex",
""
] |
I'm currently setting up an authentication system.
My current layout is to get his email from the `$_POST`, md5 his password, and check the database against his email and his password.
If it matches, I use `session_start`, and I start storing data in the `$_SESSION` variable, like so:
```
$_SESSION['uid'] = $uid;
$_SESSION['first_name'] = $first_name;
```
And on every page of the website, I would preform a simple check of
```
isset($_SESSION['uid']);
```
if not, redirect to index page, if is, load the page.
Am I doing this correctly? Is this secure enough? How easy is it for someone to forge that data?
Someone told me that I should create a table, with the user's email, and his session-id and use that to manage things... I've become rather confused - how would this help?
Could someone clarify this? What is the correct way to manage authentication with PHP sessions?
Thanks. | **Security update**: as of 2017-10-23: The advice in this answer, while of historical significance, is completely insecure. One should never use md5 in hashing a password because it is so easily brute forced. See [this answer](https://stackoverflow.com/a/30279440/576767) about how to use the built-in password\_\* api to hash and verify passwords.
---
I've dealt with login/authentication systems earlier, and I find several shortcomings in this method:
* you "md5 his password, and check the database" -- this means that if a person has access to the database, he can make out who has the same passwords!
**ADDENDUM (19 Sep 2015) \*** Look at this [link](https://crackstation.net/hashing-security.htm). It explains all the basics, the approaches you could take, why you should take those approaches and also gives you sample PHP code. If it's too long to read, just go to the end, grab the code and get set!
**BETTER APPROACH**: to store md5 of `username+password+email+salt` in the database, *salt* being random, and stored together with the user's record.
* using the 'uid' directly in the session variables can be very risky. Consider this: my friend is logged on from my browser, and he leaves for a leak. I quickly check which cookies are set in his browser, and decipher his 'uid'. Now I own him!
**BETTER APPROACH**: to generate a random sessionid when the user logs in successfully, and store that session ID in the `$_SESSION[]` array. You will also need to associate the sessionid with his uid (using the database, or memcached). Advantages are:
1. You can even bind a sessionid to a particular IP so that the sessionid can't be abused even if it is captured
2. You can invalidate an older sessionid if the user logs on from another location. So if my friend logs in from his own computer, the sessionid on my computer becomes invalid automatically.
EDIT: I've always used cookies manually for my session handling stuff. This helps me integrate the javascript components of my web apps more easily. You may need the same in your apps, in the future. | There is nothing wrong with doing this
```
isset($_SESSION['uid']);
```
The session data is not transmitted to the user, it's stored on the server (or wherever the session handler stores it). What is transmitted to the user is the session id which is just a random string generated by PHP, this can be stolen of course because it's sent to the user.
It should be clearly noted that randomly storing a string in the database and the users session and then using that to identify the user does not make the session any more secure, if the attacker gets the session they are still going to have compromised the user.
What we're discussing now is [session hijacking](http://www.owasp.org/index.php/Session_hijacking_attack), you may be thinking that you can just store the IP address in the session and check that with the IP coming from the request and be done with it. However it's often not that simple, I got burned with this recently when on a large web application we were storing a hash of the User Agent + IP address in the session and then checking that they matched on each occasion, for 99% of the users this worked fine. However, we started getting calls in from people who were finding that they were continually being logged out with no explanation. We put logging on the session hijacking checks to see what was going on and found that these people would come in on one IP and their session would continue on another, this wasn't a hijacking attempt however it was to do with how their proxy server worked, as a result we amended our session hijacking code to ascertain the [class of the IP address](http://www.tcpipguide.com/free/t_IPAddressClassABandCNetworkandHostCapacities.htm) and from there figure out the network portion of the IP address and store just those parts of the IP address, this is slightly less secure in that session hijacking could theoretically come from inside the same network but caused all our false positives to go away. | Correct way to manage sessions in PHP? | [
"",
"php",
"session",
"cookies",
""
] |
I've been trying to write some very fast Java code that has to do a lot of I/O. I'm using a memory mapped file that returns a ByteBuffer:
```
public static ByteBuffer byteBufferForFile(String fname){
FileChannel vectorChannel;
ByteBuffer vector;
try {
vectorChannel = new FileInputStream(fname).getChannel();
} catch (FileNotFoundException e1) {
e1.printStackTrace();
return null;
}
try {
vector = vectorChannel.map(MapMode.READ_ONLY,0,vectorChannel.size());
} catch (IOException e) {
e.printStackTrace();
return null;
}
return vector;
}
```
The problem that I'm having is that the `ByteBuffer` `.array()` method (which should return a `byte[]` array) doesn't work for read-only files. I want to write my code so that it will work with both memory buffers constructed in memory and buffers read from the disk. But I don't want to wrap all of my buffers a `ByteBuffer.wrap()` function because I'm worried that this will slow things down. So I've been writing two versions of everything, one that takes a `byte[]`, the other that takes a `ByteBuffer`.
Should I just wrap everything? Or should I double-write everything? | Did anyone actually check to see if `ByteBuffers` created by memory mapping support invoking `.array()` in the first place, regardless of readonly/readwrite?
From my poking around, as far as I can tell, the answer is **NO**. A `ByteBuffer`'s ability to return a direct `byte[]` array via `ByteBuffer.array()` is goverened by the presence of `ByteBuffer.hb` (`byte[]`), which is always set to null when a `MappedByteBuffer` is created.
Which kinda sucks for me, because I was hoping to do something similar to what the question author wanted to do. | Its always good not to reinvent the wheels.
Apache has provided a beautiful library for performing I/O operations. Take a look at <http://commons.apache.org/io/description.html>
Here's the scenario it serves. Suppose you have some data that you'd
prefer to keep in memory, but you don't know ahead of time how much data
there is going to be. If there's too much, you want to write it to disk
instead of hogging memory, but you don't want to write to disk until you
need to, because disk is slow and is a resource that needs tracking for
cleanup.
So you create a temporary buffer and start writing to that. If / when you
reach the threshold for what you want to keep in memory, you'll need to
create a file, write out what's in the buffer to that file, and write all
subsequent data to the file instead of the buffer.
That's what ***DeferredOutputStream*** does for you. It hides all the messing
around at the point of switch-over. All you need to do is create the
deferred stream in the first place, configure the threshold, and then just
write away to your heart's content.
EDIT: I just did a small re-search using google and found this link:
<http://lists.apple.com/archives/java-dev/2004/Apr/msg00086.html>
(Lightning fast file read/write). Very impressive. | Memory-mapped files in Java | [
"",
"java",
"memory-mapping",
""
] |
I have an existing method (or function in general) which I need to grow additional functionality, but I don't want to break any use of the method elsewhere in the code. Example:
```
int foo::bar(int x)
{
// a whole lot of code here
return 2 * x + 4;
}
```
is widely used in the codebase. Now I need to make the 4 into a parameter, but any code that already calls foo::bar should still receive what it expects. Should I extend and rename the old method and wrap it into a new one like
```
int foo::extended_bar(int x, int y)
{
// ...
return 2 * x + y;
}
int foo::bar(int x)
{
return extended_bar(x,4);
}
```
or should I declare a default argument in the header file like
```
int bar(int x, int y=4);
```
and just extend the function
```
int foo::bar(int x, int y)
{
// ...
return 2 * x + y;
}
```
What are advantages and disadvantages of each variant? | I usually use a **wrapper function** (via overloading most of the time) instead of default parameters.
The reason is that there are two levels of *backward compatibility*:
1. Having *source-level* backward compatibility means that you have to recompile the calling code without changes, because the new function signatures are compatible to the old ones. This level can be achieved with both; default values and wrappers/overloading.
2. A stronger level is *binary-level* backward compatibility, which even works without recompilation, e.g. when you don't have access to the calling code. Imagine you deploy your function in binary form, like in a DLL, etc. In such a case, the signatures have the be exactly the same to make it work, which is not the case for default values - they will break this level of compatibility.
Another advantage of wrapper functions is - if your application has logging of any kind - you can dump out a warning in the old function that it will become obsolete in future versions and that it is recommended to use the new one. | The longer I use C++, the less I like default function parameters. I can't pinpoint any specific reason for my dislike, but I find that if I use them, I almost always end up removing them later. So my (subjective) vote goes for the new named function - the name could of course be same as that of the old one. | Extend an existing API: Use default argument or wrapper function? | [
"",
"c++",
"backwards-compatibility",
""
] |
I'm writing an iPhone app that needs to interact with the Google Maps API, therefore I must user JavaScript (please correct me if I'm wrong) to access the results and the route created.
Since the JavaScript support in native iPhone apps is quite poor and slow, my idea was to ask a remote web server to do the job for me. That server would be running Apache and PHP.
So my question is, it possible to run JavaScript on the server side? And if possible, how would you do that? | After doing some research I found Aptana Jaxer, a open source software that allows you to run Ajax, HTML, JavaScript and DOM modification server-side. It's available in:
<http://aptana.com/jaxer>
In their website reads:
> HTML, JavaScript, and CSS are all
> native to Jaxer, as are
> XMLHttpRequests, JSON, and DOM
> scripting. And as a server it offers
> access to databases, files, and
> networking, as well as logging,
> process management, scalability,
> security, integration APIs, and
> extensibility.
There's also a very nice screencast that will get you started in a minute: <http://tv.aptana.com/videos/introduction-to-jaxer-10?ref=search&refId=jaxer> | Besides server-side Javascript, you could access Google Maps API from wrappers in other languages; for example, [here](http://code.google.com/p/pymaps/) is an open-source project that wraps the API for Python (it does so by generating and wrapping the needed Javascript) -- that may or may not help for your specific use case, of course (but similar issues apply to server-side JS). | How to run JavaScript on the server | [
"",
"javascript",
"iphone",
""
] |
what is the best practice to create a .jar file from a java project?? | Eclipse IDE is the best way for new comers. Just select the project right click export File, select jar anf filename. | Some points to consider:
* Create proper MANIFEST.MF, which should contain:
+ Build date;
+ Author;
+ Implementation-version;
* Use a script/program - like an [Ant task](http://ant.apache.org/) - which takes care of properly creating a manifest file.
---
Here's a simple ant file which builds a java project, adapted from the [Ant tutorial](http://ant.apache.org/manual/tutorial-HelloWorldWithAnt.html):
```
<project>
<target name="clean">
<delete dir="build"/>
</target>
<target name="compile">
<mkdir dir="build/classes"/>
<javac srcdir="src" destdir="build/classes"/>
</target>
<target name="jar">
<mkdir dir="build/jar"/>
<jar destfile="build/jar/HelloWorld.jar" basedir="build/classes">
<manifest>
<attribute name="Implementation-Version" value="1.0"/>
</manifest>
</jar>
</target>
<target name="run">
<java jar="build/jar/HelloWorld.jar" fork="true"/>
</target>
</project>
``` | what is the best practice to create a .jar file from a java project? | [
"",
"java",
"jar",
""
] |
Let's say I have the following code:
```
interface ISomeInterface
{
void DoSomething();
void A();
void B();
}
public abstract class ASomeAbstractImpl : ISomeInterface
{
public abstract void A();
public abstract void B();
public void DoSomething()
{
// code here
}
}
public class SomeImpl : ASomeAbstractImpl
{
public override void A()
{
// code
}
public override void B()
{
// code
}
}
```
The problem is that i wish to have the `ASomeAbstractImpl.DoSomething()` method sealed (final) so no other class could implement it.
As the code is now `SomeImpl` could have a method called `DoSomething()` and that could be called (it would not override the method with the same name from the abstract class, because that's not marked as virtual), yet I would like to cut off the possibility of implementing such a method in `SomeImpl` class.
Is this possible? | Methods in C# are sealed by default. There is, however, **nothing you can do** to prevent method hiding (exposing a method with the same name in the derived class, commonly with `new`).
Or, for that matter, interface-reimplementation:
```
static void Main()
{
ISomeInterface si = new EvilClass();
si.DoSomething(); // mwahahah
}
public class EvilClass : ASomeAbstractImpl, ISomeInterface
{
public override void A() {}
public override void B() { }
void ISomeInterface.DoSomething()
{
Console.WriteLine("mwahahah");
}
}
``` | All methods are sealed by default, but there's no way of preventing Member Hiding.
The C# compiler will issue a compiler warning whenever you hide a member, but apart from that, you can't prevent it. | C# inheritance | [
"",
"c#",
"inheritance",
"interface",
"abstract-class",
""
] |
Can someone show me a simple way I can test if someone's cookies are not enabled in php? I want to create a test script to determine if the user can properly use my site. If they cannot, I will redirect them to a couple screen shots to show them what to change.
I am only using $\_SESSION[] variables, and I beleive that the only thing the cookie is for, in my setup is the session id variable.
Ideally, I would like to turn on an option in PHP for that user to pass the session id back and forth via GET/POST if their cookies are messed up.
Anything Javascript will not work for me, as they may not have javascript enabled. | ```
setcookie("cookies","yes",time() +"3600");
```
Then redirect after that and test if the cookie is set on the next page. It will take at least two pages to know whether or not cookies are enabled. | use SID
see <https://www.php.net/function.session-start> and <https://www.php.net/manual/en/session.idpassing.php>
SID will be empty if the cookie was accepted, and contain the session id (PHPSESSID=session\_id(), actually) otherwise. This does however depend on compilation flags so be sure to check the refs.
you could use it as :
```
echo '<br /><a href="page2.php?' . SID . '">page 2</a>';
``` | How can I test if someones cookies are not working? (PHP) | [
"",
"php",
"cookies",
""
] |
I've got a small website that has about 5-10 administrators. I've set it up to monitor what each administrator is doing (adding items, removing items, etc). I had a list within our admin-panel that shows the previous 10 activities performed by the collective administration. Today, I decided to make this self-updating every 30 seconds.
My question is simple: is there any problem doing this? I'm calling a small bit of text with each request, and the request is likely only running on 3 or 4 computers at a time (reflecting the number of concurrent-administrators logged in).
```
$(document).ready(function(){
setInterval("activity()", 30000);
});
function activity() {
$("#recent_activity").load("../home/login #recent_activity .data");
}
```
Produces the following (or similar - only with 10 rows) with each request.
```
<table>
<tbody>
<tr>
<td><p>jsampson</p></td>
<td><p>logged out</p></td>
<td><p>28 minutes 27 seconds ago</p></td>
</tr>
<tr>
<td><p>jdoe</p></td>
<td><p>logged in</p></td>
<td><p>29 minutes 45 seconds ago</p></td>
</tr>
</tbody>
</table>
``` | 3-4 users every 30 seconds isn't very much at all. Even 300 users at that rate wouldn't be much at all.
You may want to check into these questions:
* [Should I use Ajax Push or Pull](https://stackoverflow.com/questions/219868/client-notification-should-i-use-an-ajax-push-or-poll)
* [Simple Long Polling Example Code](https://stackoverflow.com/questions/333664/simple-long-polling-example-code)
You *can* cache this as well, and it would be advisable *especially if the query to generate the page is computationally heavy*, but of course take into account what kind of lag you want in the most recent content being displayed. | You should cache this and only update the cache every 30 seconds. | Constantly Querying Server via Javascript - Good Idea? | [
"",
"javascript",
"jquery",
"design-patterns",
"auto-update",
""
] |
What is wrong with my line below?
```
table.DefaultView.RowFilter = cmbBox.Text + 'LIKE' + strName";
```
The line below works fine but is obviously no use.
```
table.DefaultView.RowFilter = 'FirstName LIKE James';
```
Thanks | Seems as if you are missing the wildcards?
```
table.DefaultView.RowFilter = cmbBox.Text + " LIKE '%" + strName + "%'";
``` | It could be a problem with spacing
```
table.DefaultView.RowFilter = cmbBox.Text + " LIKE " + strName;
``` | c# Help joining textbox value, LIKE and a string variable | [
"",
"c#",
"sql-like",
""
] |
In Python, how can we find out the command line arguments that were provided for a script, and process them?
---
Related background reading: [What does "sys.argv[1]" mean? (What is sys.argv, and where does it come from?)](https://stackoverflow.com/questions/4117530). For some more specific examples, see [Implementing a "[command] [action] [parameter]" style command-line interfaces?](https://stackoverflow.com/questions/362426) and [How do I format positional argument help using Python's optparse?](https://stackoverflow.com/questions/642648). | The canonical solution in the standard library is `argparse` ([docs](https://docs.python.org/3/library/argparse.html)):
Here is an example:
```
from argparse import ArgumentParser
parser = ArgumentParser()
parser.add_argument("-f", "--file", dest="filename",
help="write report to FILE", metavar="FILE")
parser.add_argument("-q", "--quiet",
action="store_false", dest="verbose", default=True,
help="don't print status messages to stdout")
args = parser.parse_args()
```
`argparse` supports (among other things):
* Multiple options in any order.
* Short and long options.
* Default values.
* Generation of a usage help message. | ```
import sys
print("\n".join(sys.argv))
```
[`sys.argv`](https://docs.python.org/3/library/sys.html#sys.argv) is a list that contains all the arguments passed to the script on the command line. `sys.argv[0]` is the script name.
Basically,
```
import sys
print(sys.argv[1:])
``` | How can I read and process (parse) command line arguments? | [
"",
"python",
"command-line",
"command-line-arguments",
""
] |
I'm trying to execute a file with Python commands from within the interpreter.
I'm trying to use variables and settings from that file, not to invoke a separate process. | Several ways.
* From the shell
```
python someFile.py
```
* From inside IDLE, hit **F5**.
* If you're typing interactively, try this (**Python3**):
```
>>> exec(open("filename.py").read())
```
* For Python 2:
```
>>> variables= {}
>>> execfile( "someFile.py", variables )
>>> print variables # globals from the someFile module
``` | **For Python 2:**
```
>>> execfile('filename.py')
```
**For Python 3:**
```
>>> exec(open("filename.py").read())
# or
>>> from pathlib import Path
>>> exec(Path("filename.py").read_text())
```
See [the documentation](http://docs.python.org/library/functions.html#execfile). If you are using Python 3.0, see [this question](https://stackoverflow.com/questions/436198/what-is-an-alternative-to-execfile-in-python-3-0).
See answer by @S.Lott for an example of how you access globals from filename.py after executing it. | How to execute a file within the Python interpreter? | [
"",
"python",
""
] |
I'm trying to **reduce the warnings** that are sent to my apache server log.
One warning is:
> Call-time pass-by-reference has been deprecated.
It is **hard for me to imagine** why this was deprecated since it is such a useful programming feature, basically I do this:
```
public function takeScriptsWithMarker(&$lines, $marker) {
...
}
```
and I call this function repeatedly getting results back from it and processing them but also letting the array $lines build up by being sent into this method repeatedly.
1. To reprogram this would be extensive.
2. I don't want to just "turn off warnings" since I want to see other warnings.
So, as call-by-reference is deprecated, **what is the "accepted way" to attain the functionality** of this pattern: namely of sending an array of strings into a method, have them be changed by the method, then continuing to use that array? | Actually, there's no problem with the way you define the function. Is a problem with the way you call the function. So for your example, instead of calling it like:
```
takeScriptsWithMarker(&$lines, $marker);
```
You'd call it like:
```
takeScriptsWithMarker($lines, $marker); // no ampersands :)
```
So the feature is still available. But I don't know the reason behind this change. | like noted above in a previous answer, the issue is at CALL time, not definition time.. so you could define a function as:
```
function foo(&$var1,$var2,$var3=null){
// procesing here
}
```
then call as:
```
$return = foo($invar1,$invar2);
```
your first invar is passed by reference, second one is not.
the error appears when you try to call like so:
```
$return = foo(&$invar1,$invar2);
``` | How to avoid call-time pass-by-reference deprecated error in PHP? | [
"",
"php",
""
] |
In C#,
Suppose I am in a form, and I pressed a button I made to close it.
```
this.Close();
some_action(); //can I do this??
```
can I perform another action after I closed the form or does the thread die and everything after that is lost? | Depends on what you are trying to do and the context of the statement. If the form being closed is the main form which owns the message loop, you can't do any **UI related stuff** (e.g. you can't display another `MessageBox`). If you are not doing it from another window (which doesn't own the message loop), you could do anything (even UI related) as long as you aren't manipulating the closed form object (you'll get `ObjectDisposedException` just like any disposed object).
By the way, the thread doesn't die as a result of `Close`. Closing the main window causes the message loop to terminate and not the thread itself. For example, the following program
```
static void Main() {
Application.Run(new Form1());
Application.Run(new Form2());
}
```
will display `Form2` after `Form1` is closed (using a newly created message loop). This proves that the thread is not dead. | If you try to manipulate the form or any of it's controls after calling Close you're going to run into trouble. However there's nothing preventing you from calling some other method - for instance a logging method - after calling Close. | Can I put commands after Form.Close()? | [
"",
"c#",
"winforms",
""
] |
I know it's a simple concept but I'm struggling with the font metrics. Centering horizontally isn't too hard but vertically seems a bit difficult.
I've tried using the FontMetrics getAscent, getLeading, getXXXX methods in various combinations but no matter what I've tried the text is always off by a few pixels. Is there a way to measure the exact height of the text so that it is exactly centered. | Note, you *do* need to consider precisely what you mean by vertical centering.
Fonts are rendered on a baseline, running along the bottom of the text. The vertical space is allocated as follows:
```
---
^
| leading
|
--
^ Y Y
| Y Y
| Y Y
| ascent Y y y
| Y y y
| Y y y
-- baseline ______Y________y_________
| y
v descent yy
--
```
The leading is simply the font's recommended space between lines. For the sake of centering vertically between two points, you should ignore leading (it's ledding, BTW, not leeding; in general typography it is/was the lead spacing inserted between lines in a printing plate).
So for centering the text ascenders and descenders, you want the
```
baseline=(top+((bottom+1-top)/2) - ((ascent + descent)/2) + ascent;
```
Without the final "+ ascent", you have the position for the top of the font; therefore adding the ascent goes from the top to the baseline.
Also, note that the font height should include leading, but some fonts don't include it, and due to rounding differences, the font height may not exactly equal (leading + ascent + descent). | I found a recipe [here](http://leepoint.net/notes-java/GUI-appearance/fonts/18font.html).
The crucial methods seem to be `getStringBounds()` and `getAscent()`
```
// Find the size of string s in font f in the current Graphics context g.
FontMetrics fm = g.getFontMetrics(f);
java.awt.geom.Rectangle2D rect = fm.getStringBounds(s, g);
int textHeight = (int)(rect.getHeight());
int textWidth = (int)(rect.getWidth());
int panelHeight= this.getHeight();
int panelWidth = this.getWidth();
// Center text horizontally and vertically
int x = (panelWidth - textWidth) / 2;
int y = (panelHeight - textHeight) / 2 + fm.getAscent();
g.drawString(s, x, y); // Draw the string.
```
(note: above code is covered by the [MIT License](http://www.opensource.org/licenses/mit-license.php) as noted on the page.) | How do you draw a string centered vertically in Java? | [
"",
"java",
"graphics",
""
] |
I'm trying to create an HttpWebRequest/HttpWebResponse session with an ASP.NET website to later parse an HTML form through url params (this part I know how to do), but I do not understand how to parse and set a cookie such as the session id. In Fiddler, it shows that the ASP.NET Session ID is returned through Set-Cookie in the response to the request to the / path of the url, but how can I extract this session id and set it as a cookie for the next HttpWebRequest? I understand that this Set-Cookie header would be found in HttpWebResponse.Headers.Keys, but is there a direct path to parsing it? Thanks! | The .NET framework will manage cookies for you. You don't have to concern yourself with parsing the cookie information out of the headers or adding a cookie header to your requests.
To store and send your session ID, use the [`Cookie`](http://msdn.microsoft.com/en-us/library/system.net.cookie.aspx) and [`CookieContainer`](http://msdn.microsoft.com/en-us/library/system.net.cookiecontainer.aspx) classes to store them and then make sure you send your cookies with every request.
The following example shows how to do this. The CookieContainer, '`cookieJar`' can be shared across multiple domains and requests. Once you add it to a request object, the reference to it will also be added to the response object when the response is returned.
```
CookieContainer cookieJar = new CookieContainer();
var request = (HttpWebRequest)HttpWebRequest.Create("http://www.google.com");
request.CookieContainer = cookieJar;
var response = request.GetResponse();
foreach (Cookie c in cookieJar.GetCookies(request.RequestUri))
{
Console.WriteLine("Cookie['" + c.Name + "']: " + c.Value);
}
```
The output of this code will be:
> `Cookie['PREF']: ID=59e9a22a8cac2435:TM=1246226400:LM=1246226400:S=tvWTnbBhK4N7Tlpu` | The answer from Dan Herbert helped me really. I appreciate your help.
Just want to post my usage - hope it helps some one at some point of time. My requirement is that I need to send back cookies from first http post response to second http post request.
1st:
```
CookieContainer cookieJar = new CookieContainer();
request.CookieContainer = cookieJar;
....
CookieCollection setCookies = cookieJar.GetCookies(request.RequestUri);
```
2nd:
```
CookieContainer cc = new CookieContainer();
cc.Add(setCookies);
request.CookieContainer = cc;
``` | How to parse HttpWebResponse.Headers.Keys for a Set-Cookie session id returned | [
"",
"c#",
"cookies",
"httpwebrequest",
"httpwebresponse",
"setcookie",
""
] |
Is there a way to make my program remember the way columns are re-ordered so when the application is re-opened, it orders them the same way as it was when I closed the form. I can't find any properties for this.
Thanks. | Assuming you are talking about a Windows Forms DataGridView, I'm not aware of any property that would do this for you automatically. I think you could devise a pretty simple scheme by handling the ColumnDisplayIndexChanged Event, though. Whenever the user changes the order of the columns, this event would be triggered, then you could save the column order in an XML file. When first creating the form with the DataGridView, you would need to read the data from the file and set the proper DisplayIndex for each column.
Hope that helps,
-Dan | ```
var query = from DataGridViewColumn col in dataGridView1.Columns
orderby col.DisplayIndex
select col;
foreach (DataGridViewColumn col in query)
{
MessageBox.Show(col.HeaderText);
MessageBox.Show(col.DisplayIndex.ToString());
}
``` | Saving settings for "AllowUserToOrderColumns" of my DataGridView | [
"",
"c#",
".net",
"datagridview",
""
] |
I have a big number stored in a string and try to extract a single digit. But what are the differences between those calls?
```
#include <iostream>
#include <string>
int main(){
std::string bigNumber = "93485720394857230";
char tmp = bigNumber.at(5);
int digit = atoi(&tmp);
int digit2 = atoi(&bigNumber.at(5))
int digit3 = atoi(&bigNumber.at(12));
std::cout << "digit: " << digit << std::endl;
std::cout << "digit2: " << digit2 << std::endl;
std::cout << "digit3: " << digit3 << std::endl;
}
```
This will produce the following output.
> digit: 7
>
> digit2: 2147483647
>
> digit3: 57230
The first one is the desired result. The second one seems to me to be a random number, which I cannot find in the string. The third one is the end of the string, but not just a single digit as I expected, but up from the 12th index to the end of the string. Can somebody explain the different outputs to me?
EDIT: Would this be an acceptable solution?
```
char tmp[2] = {bigNumber.at(5), '\0'};
int digit = atoi(tmp);
std::cout << "digit: " << digit << std::endl;
``` | It is all more or less explicable.
```
int main(){
std::string bigNumber = "93485720394857230";
```
This line copies the single character '5' into the character variable. `atoi` will convert this correctly. `atoi` expects that the string parameter is a valid 0 terminated string. `&tmp` is only a pointer to the character variable - the behaviour of this call is undefined since the memory immediately following the character in memory is unknown. To be exact, you would have to create a null terminated string and pass that in.\*
```
char tmp = bigNumber.at(5);
int digit = atoi(&tmp);
```
This line gets a pointer to the character in position 5 in the string. This happens to be a pointer into the original big number string above - so the string parameter to `atoi` looks like the string "5720394857230". `atoi` will clearly oveflow trying to turn this into an integer since no 32 bit integer will hold this.
```
int digit2 = atoi(&bigNumber.at(5))
```
This line gets a pointer into the string at position 12. The parameter to `atoi` is the string
"57230". This is converted into the integer 57230 correctly.
```
int digit3 = atoi(&bigNumber.at(12));
```
...
}
Since you are using C++, there are nicer methods to convert strings of characters into integers. One that I am partial to is the Boost lexical\_cast library. You would use it like this:
```
char tmp = bigNumber.at(5);
// convert the character to a string then to an integer
int digit = boost::lexical_cast<int>(std::string(tmp));
// this copies the whole target string at position 5 and then attempts conversion
// if the conversion fails, then a bad_lexical_cast is thrown
int digit2=boost::lexical_cast<int>(std::string(bigNumber.at(5)));
```
\* Strictly, `atoi` will scan through the numeric characters until a non-numeric one is found. It is clearly undefined when it would find one and what it will do when reading over invalid memory locations. | I know why the 2nd number is displayed.
[From the atoi reference.](http://www.cplusplus.com/reference/clibrary/cstdlib/atoi/)
> If the correct value is out of the range of representable values, **`INT_MAX`** or INT\_MIN is returned.
2147483647 is INT\_MAX | What is difference between my atoi() calls? | [
"",
"c++",
"atoi",
""
] |
When you add a DateTimePicker control, you can select part of the control value (for example the month) and then use the up/down arrows to modify this part of the date/time value (for example, incrementing/decrementing the month).
What i would like to do is to allow the same thing with the mouse wheel. I tried to register on the event MouseWheel but I can't find a way to know which part of my date/time is currently selected, so I have no way to know if i should increment the time, the day, the month or the year.
Is there any way to do this ? | A possible, but not quite elegant solution would be something like :
```
private void dateTimePicker1_MouseWheel(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (e.Delta > 0)
{
System.Windows.Forms.SendKeys.Send("{UP}");
}
else
{
System.Windows.Forms.SendKeys.Send("{DOWN}");
}
}
```
this should definitely work in general case, but some corner cases might have unexpected results (like having KeyUp/KeyDown events overriden) | I've tried to figure this one out too. In the end, I ended up with this:
```
Private Sub dtpDateTimePicker_MouseWheel(ByVal sender As Object, ByVal e As System.Windows.Forms.MouseEventArgs)
If e.Delta > 0 Then
SendKeys.Send("{Up}")
Else
SendKeys.Send("{Down}")
End If
End Sub
```
You can automatically add this handler to all your date pickers in your form and it's containers using this method. Just call it once in form\_load:
```
Public Sub AttachDateTimeMouseWheels(ByRef ownerForm As Control)
Dim myControl As Control
For Each myControl In ownerForm.Controls
If TypeOf myControl Is DateTimePicker Then
AddHandler myControl.MouseWheel, AddressOf dtpDateTimePicker_MouseWheel
Else
If myControl.Controls.Count > 0 Then
AttachDateTimeMouseWheels(myControl)
End If
End If
Next
End Sub
``` | How to make a DateTimePicker increment/decrement on mouse wheel | [
"",
"c#",
"winforms",
""
] |
I'd like to add parts of the source code to the XML documentation. I could copy & paste source code to some <code> elements, like this:
```
/// <summary>
/// Says hello world in a very basic way:
/// <code>
/// System.Console.WriteLine("Hello World!");
/// System.Console.WriteLine("Press any key to exit.");
/// System.Console.ReadKey();
/// </code>
/// </summary>
static void Main()
{
System.Console.WriteLine("Hello World!");
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}
```
Maintaining this will be painful. Are there other possibilities to add source code to the XML documentation in C#?
I am processing the XML documentation with Sandcastle and would like to make a technical help file (\*.chm) out of it. I would like to add parts or complete method bodies to the that help file.
---
**EDIT:**
Thanks for the comment from slide\_rule. I have added a more realistic and less trivial example:
Suppose I have some method like this:
```
public decimal CalculateFee(Bill bill)
{
if (bill.TotalSum < 5000) return 500;
else
{
if (bill.ContainsSpecialOffer) return bill.TotalSum * 0.01;
else return bill.TotalSum * 0.02;
}
}
```
It would be nice to have a possibility to add the information how the fee is calculated into the technical help file.
The most obvious solution would be write down the algorithm as prosaic text into the comment like: "If the bill has a total sum less than 5000 then ...".
Another solution would be to copy & paste the body of the method into the comment field and put it into a <code> element. This method body can be understood quite easily, even without much knowledge about C# -- so there is nothing wrong to put it into a technical help file.
**Both solutions violate the DRY principle!** I would like to add method bodies or pieces of a method body into the help file, without duplicating information.
Is this possible in C#? (I think RDoc for Ruby is capable of doing this, but I need some solution in C#) | Just throwing an idea out there...
Automate a process that looks for code blocks delimited in some way, then inject that code into the XML comment.
```
/// <summary>
/// Says hello world in a very basic way:
/// <code>
/// Code block 1
/// </code>
/// </summary>
static void Main()
{
// Code block 1 start
System.Console.WriteLine("Hello World!");
System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
// Code block 1 end
}
```
I know it's not pretty, but it's a start! ;) | Why not go with a more standard approach for documenting the code by using fields like
```
<summary>
<description>Displays Hello World!</description>
<arguments>None</arguments>
<returns>None</returns>
</summary>
```
Just a thought. | How to make source code a part of XML documentation and not violate DRY? | [
"",
"c#",
".net",
"dry",
"documentation-generation",
""
] |
Does anyone know where I can find a Stream splitter implementation?
I'm looking to take a Stream, and obtain two separate streams that can be independently read and closed without impacting each other. These streams should each return the same binary data that the original stream would. No need to implement Position or Seek and such... Forward only.
I'd prefer if it didn't just copy the whole stream into memory and serve it up multiple times, which would be fairly simple enough to implement myself.
Is there anything out there that could do this? | Not out of the box.
You'll need to buffer the data from the original stream in a FIFO manner, discarding only data which has been read by all "reader" streams.
I'd use:
* A "management" object holding some sort of queue of byte[] holding the chunks to be buffered and reading additional data from the source stream if required
* Some "reader" instances which known where and on what buffer they are reading, and which request the next chunk from the "management" and notify it when they don't use a chunk anymore, so that it may be removed from the queue | I have made a SplitStream available on github and NuGet.
It goes like this.
```
using (var inputSplitStream = new ReadableSplitStream(inputSourceStream))
using (var inputFileStream = inputSplitStream.GetForwardReadOnlyStream())
using (var outputFileStream = File.OpenWrite("MyFileOnAnyFilestore.bin"))
using (var inputSha1Stream = inputSplitStream.GetForwardReadOnlyStream())
using (var outputSha1Stream = SHA1.Create())
{
inputSplitStream.StartReadAhead();
Parallel.Invoke(
() => {
var bytes = outputSha1Stream.ComputeHash(inputSha1Stream);
var checksumSha1 = string.Join("", bytes.Select(x => x.ToString("x")));
},
() => {
inputFileStream.CopyTo(outputFileStream);
},
);
}
```
I have not tested it on very large streams, but give it a try.
github: <https://github.com/microknights/SplitStream> | How can I split (copy) a Stream in .NET? | [
"",
"c#",
".net",
"io",
"stream",
""
] |
I have three different base classes:
```
class BaseA
{
public:
virtual int foo() = 0;
};
class BaseB
{
public:
virtual int foo() { return 42; }
};
class BaseC
{
public:
int foo() { return 42; }
};
```
I then derive from the base like this (substitute X for A, B or C):
```
class Child : public BaseX
{
public:
int foo() { return 42; }
};
```
How is the function overridden in the three different base classes? Are my three following assumptions correct? Are there any other caveats?
* With BaseA, the child class doesn't compile, the pure virtual function isn't defined.
* With BaseB, the function in the child is called when calling foo on a BaseB\* or Child\*.
* With BaseC, the function in the child is called when calling foo on Child\* but not on BaseB\* (the function in parent class is called). | In the derived class a method is virtual if it is defined virtual in the base class, even if the keyword virtual is not used in the derived class's method.
* With `BaseA`, it will compile and execute as intended, with `foo()` being virtual and executing in class `Child`.
* Same with `BaseB`, it will also compile and execute as intended, with `foo()` being virtual() and executing in class `Child`.
* With `BaseC` however, it will compile and execute, but it will execute the `BaseC` version if you call it from the context of `BaseC`, and the `Child` version if you call with the context of `Child`. | The important rule to remember is once a function is declared virtual, functions with matching signatures in the derived classes are always virtual. So, it is overridden for Child of A and Child of B, which would behave identically (with the exception of you can't directly instantiate BaseA).
With C, however, the function isn't overridden, but overloaded. In that situation, only the static type matters: it will call it on what it is a pointer to (the static type) instead of what the object really is (the dynamic type) | C++ function overriding | [
"",
"c++",
"function",
"polymorphism",
"overriding",
""
] |
I need to write the data from an Excel sheet/workbook to the text file using C#.
Also, I want all Excel worksheet data in single text file.
Apart from reading the data from Excel sheets one by one and then appending it to the existing text file, is there any other simple way to do it? | I would suggest using [`OleDbDataReader`](http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdatareader.aspx) with a connection string from [www.connectionstrings.com](http://www.connectionstrings.com/) to read the Excel file. You can use your favorite method, say [`StreamWriter`](http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx), to spit the data out to a text file. | [SpreadsheetGear for .NET](http://www.spreadsheetgear.com/) can do it with a few lines of code:
```
using System;
using SpreadsheetGear;
namespace WorkbookToCSV
{
class Program
{
static void Main(string[] args)
{
string inputFilename = @"c:\CSVIn.xlsx";
string outputFilename = @"c:\CSVOut.csv";
// Create the output stream.
using (System.IO.FileStream outputStream = new System.IO.FileStream(outputFilename, System.IO.FileMode.Create, System.IO.FileAccess.Write))
{
// Load the source workbook.
IWorkbook workbook = Factory.GetWorkbook(inputFilename);
foreach (IWorksheet worksheet in workbook.Worksheets)
{
// Save to CSV in a memory buffer and then write it to
// the output FileStream.
byte[] csvBuffer = worksheet.SaveToMemory(FileFormat.CSV);
outputStream.Write(csvBuffer, 0, csvBuffer.Length);
}
outputStream.Close();
}
}
}
}
```
You can download a free trial [here](https://www.spreadsheetgear.com/downloads/register.aspx) and try it yourself.
Disclaimer: I own SpreadsheetGear LLC | Write the data from an Excel sheet to the text file using C# | [
"",
"c#",
"excel",
"text-files",
""
] |
I'm building a small webapp on win2003 with asp.net 2.0.
I need to create small files that i suppose to be accessable by for the web and the files is suppose to have 10 minute expiration time.
I didn't find any support for this in the framework and my other solution that came to mind was to have a schedule job that cleans the file ever X minute. But somehow I think I'm not the first one to experience this problem and wondering if there are any other smart solutions.
Thanks in advance. | Without knowing more about why you are doing this, I think your solution of an external program to clean the files out is the best solution. An alternative might be to store the "files" in a database and create a handler that retrieves the data from the database, but only if the "file" is not expired. You could then schedule a clean up task on the database much less frequently and still only serve up the "files" that are not expired. Creating them on disk would force you to do the clean up on a regular schedule to ensure that expired items are no longer available.
I suppose you could also do the handler with on-disk files and check the creation date before serving the file up. In this case the folder containing the actual files would need to be outside the web site or in a restricted area that prohibits direct access from normal users. | Since it's small, and if you want to keep it simple, just check on every N requests to the website. If you think the number of files to clean could get large, stop cleaning after you find a few to clean and let the next request clean up a few more. The advantage is that you don't have to manage an external job (and install it and keep it running, etc).
Probably not a good idea for a big site. | Creating public temporary files with expiration time | [
"",
"c#",
"asp.net",
"temporary-files",
""
] |
Is there any good way (and a simple way too) using Boost to read and write XML files?
I can't seem to find any simple sample to read XML files using Boost. Can you point me a simple sample that uses Boost for reading and writing XML files?
If not Boost, is there any good and simple library to read and write XML files that you can recommend? (it must be a C++ library) | You should Try [pugixml](http://pugixml.org/) *Light-weight, simple and fast XML parser for C++*
The nicest thing about pugixml is the **XPath** support, which TinyXML and RapidXML lack.
Quoting RapidXML's author "I would like to thank Arseny Kapoulkine for his work on pugixml, which was an inspiration for this project" and "5% - 30% faster than pugixml, the fastest XML parser I know of" He had tested against version 0.3 of pugixml, which has reached recently version 0.42.
Here is an excerpt from pugixml documentation:
The main features are:
* low memory consumption and fragmentation (the win over pugxml is ~1.3 times, TinyXML - ~2.5 times, Xerces (DOM) - ~4.3 times 1). Exact numbers can be seen in Comparison with existing parsers section.
* extremely high parsing speed (the win over pugxml is ~6 times, TinyXML - ~10 times, Xerces-DOM - ~17.6 times 1
* extremely high parsing speed (well, I'm repeating myself, but it's so fast, that it outperforms Expat by 2.8 times on test XML) 2
* more or less standard-conformant (it will parse any standard-compliant file correctly, with the exception of DTD related issues)
* pretty much error-ignorant (it will not choke on something like You & Me, like expat will; it will parse files with data in wrong encoding; and so on)
* clean interface (a heavily refactored pugxml's one)
* more or less Unicode-aware (actually, it assumes UTF-8 encoding of the input data, though it will readily work with ANSI - no UTF-16 for now (see Future work), with helper conversion functions (UTF-8 <-> UTF-16/32 (whatever is the default for std::wstring & wchar\_t))
* fully standard compliant C++ code (approved by Comeau strict mode); the library is multiplatform (see reference for platforms list)
* high flexibility. You can control many aspects of file parsing and DOM tree building via parsing options.
Okay, you might ask - what's the catch? Everything is so cute - it's small, fast, robust, clean solution for parsing XML. What is missing? Ok, we are fair developers - so here is a misfeature list:
* memory consumption. It beats every DOM-based parser that I know of - but when SAX parser comes, there is no chance. You can't process a 2 Gb XML file with less than 4 Gb of memory - and do it fast. Though pugixml behaves better, than all other DOM-based parser, so if you're stuck with DOM, it's not a problem.
* memory consumption. Ok, I'm repeating myself. Again. When other parsers will allow you to provide XML file in a constant storage (or even as a memory mapped area), pugixml will not. So you'll have to copy the entire data into a non-constant storage. Moreover, it should persist during the parser's lifetime (the reasons for that and more about lifetimes is written below). Again, if you're ok with DOM - it should not be a problem, because the overall memory consumption is less (well, though you'll need a contiguous chunk of memory, which can be a problem).
* lack of validation, DTD processing, XML namespaces, proper handling of encoding. If you need those - go take MSXML or XercesC or anything like that. | [TinyXML](http://www.grinninglizard.com/tinyxml/) is probably a good choice. As for Boost:
There is the [Property\_Tree](http://kaalus.atspace.com/ptree/doc/index.html) library in the [Boost Repository](http://svn.boost.org/svn/boost/trunk/boost/property_tree/). It has been accepted, but support seems to be lacking at the moment (EDIT: [Property\_Tree](http://www.boost.org/doc/libs/1_43_0/doc/html/property_tree.html) is now part of Boost [since version 1.41](http://www.boost.org/users/news/version_1_41_0), read [the documentation](http://www.boost.org/doc/libs/1_43_0/doc/html/boost_propertytree/parsers.html#boost_propertytree.parsers.xml_parser) regarding its XML functionality).
Daniel Nuffer has implemented an [xml parser](http://spirit.sourceforge.net/repository/applications/show_contents.php) for Boost Spirit. | Using Boost to read and write XML files | [
"",
"c++",
"xml",
"boost",
""
] |
IE handles one of my div's classes totally wrong. It works in every other browser I tried. I want to simply not apply the class to the div in IE. Is there a trick to make IE not apply it?
More info: The div has multiple classes. I want to still load one but not the other in IE. The classes are defined in a Javascript file.
Thanks.
Mike | I hate to do browser detection via javascript, but if none of the other solutions work you might try something like the following:
```
function removeClassForIE() {
// Look at userAgent to test for IE
if (/MSIE (\d+\.\d+);/.test(navigator.userAgent)) {
var divs = document.getElementsByTagName("div");
for (var i = 0; i < divs.length; i++) {
if (divs[i].className == "myClassName") {
divs[i].className = "";
}
}
}
}
```
That should remove the class from those divs, and only if its IE. You could call the function like <body onload="removeClassForIE();"> | You can use conditional comments for IE to override the style on the class - that might be the easiest thing. Have a look here: [MSDN link](http://msdn.microsoft.com/en-us/library/ms537512(VS.85).aspx)
Essentially, you'd assign a more specific style to the class in the comment, overriding the standard - so, you could take most of the styling off. Intelligent browsers won't see the comment. | How can I make just IE ignore a class? | [
"",
"javascript",
"html",
"css",
""
] |
Is there a table of how much "work" it takes to execute a given function in PHP? I'm not a compsci major, so I don't have maybe the formal background to know that "oh yeah, strings take longer to work with than integers" or anything like that. Are all steps/lines in a program created equal? I just don't even know where to start researching this.
I'm currently doing some Project Euler questions where I'm very sure my answer will work, but I'm timing out my local Apache server at a minute with my requests (and PE has said that all problems can be solved < 1 minute). I don't know how/where to start optimizing, so knowing more about PHP and how it uses memory would be useful. For what it's worth, here's my code for [question 206](http://projecteuler.net/index.php?section=problems&id=206):
```
<?php
$start = time();
for ($i=1010374999; $i < 1421374999; $i++) {
$a = number_format(pow($i,2),0,".","");
$c = preg_split('//', $a, -1, PREG_SPLIT_NO_EMPTY);
if ($c[0]==1) {
if ($c[2]==2) {
if ($c[4]==3) {
if ($c[6]==4) {
if ($c[8]==5) {
if ($c[10]==6) {
if ($c[12]==7) {
if ($c[14]==8) {
if ($c[16]==9) {
if ($c[18]==0) {
echo $i;
}
}
}
}
}
}
}
}
}
}
}
$end = time();
$elapsed = ($end-$start);
echo "<br />The time to calculate was $elapsed seconds";
?>
```
If this is a wiki question about optimization, just let me know and I'll move it. Again, not looking for an answer, just help on where to learn about being efficient in my coding (although cursory hints wouldn't be flat out rejected, and I realize there are probably more elegant mathematical ways to set up the problem) | There's no such table that's going to tell you how long each PHP function takes to execute, since the time of execution will vary wildly depending on the input.
Take a look at what your code is doing. You've created a loop that's going to run 411,000,000 times. Given the code needs to complete in less than 60 seconds (a minute), in order to solve the problem you're assuming each trip through the loop will take less than (approximately) .000000145 seconds. That's unreasonable, and no amount of using the "right" function will solve your call. Try your loop with **nothing** in there
```
for ($i=1010374999; $i < 1421374999; $i++) {
}
```
Unless you have access to science fiction computers, this probably isn't going to complete execution in less than 60 seconds. So you know this approach will never work.
This is known a brute force solution to a problem. The point of Project Euler is to get you thinking creatively, both from a math and programming point of view, about problems. You want to **reduce** the number of trips you need to take through that loop. The obvious solution will never be the answer here.
I don't want to tell you the solution, because the point of these things is to think your way through it and become a better algorithm programmer. Examine the problem, think about it's restrictions, and think about ways you reduce the total number of numbers you'd need to check. | A good tool for taking a look at execution times for your code is xDebug: <http://xdebug.org/docs/profiler>
It's an installable PHP extension which can be configured to output a complete breakdown of function calls and execution times for your script. Using this, you'll be able to see what in your code is taking longest to execute and try some different approaches.
EDIT: now that I'm actually looking at your code, you're running 400 million+ regex calls! I don't know anything about project Euler, but I have a hard time believing this code can be excuted in under a minute on commodity hardware. | PHP function efficiencies | [
"",
"php",
"performance",
"optimization",
""
] |
When consuming a .NET WCF webservice I get the following response (error):
> Unsupported HTTP response status 415
> Cannot process the message because the content type 'text/xml; charset=UTF-8'
> was not the expected type 'application/soap+xml; charset=utf-8'.
How do I change the content type? I can't find it in the NuSOAP forums/docs, or I might be overlooking something.... | i know this is an old post, but i ran in to this page looking for an answer.
`application/soap+xml` is the content-type passed when using SOAP 1.2,
`text/xml` is used with SOAP 1.1,
something like this should do the trick,
```
$client = new SoapClient("some.wsdl", array('soap_version' => SOAP_1_1));
``` | You can specify the encoding of NuSOAP streams with the webservices like that :
```
$client = new nusoap_client($params);
$client->soap_defencoding = 'UTF-8';
``` | NuSOAP: how to change content-type of request? | [
"",
"php",
"web-services",
"content-type",
"nusoap",
""
] |
```
EXPLAIN SELECT
*
FROM
content_link link
STRAIGHT_JOIN
content
ON
link.content_id = content.id
WHERE
link.content_id = 1
LIMIT 10;
+----+-------------+---------+-------+---------------+------------+---------+-------+------+-------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------+-------+---------------+------------+---------+-------+------+-------+
| 1 | SIMPLE | link | ref | content_id | content_id | 4 | const | 1 | |
| 1 | SIMPLE | content | const | PRIMARY | PRIMARY | 4 | const | 1 | |
+----+-------------+---------+-------+---------------+------------+---------+-------+------+-------+
```
However, when I remove the WHERE, the query stops using the key (even when i explicitly force it to)
```
EXPLAIN SELECT
*
FROM
content_link link FORCE KEY (content_id)
STRAIGHT_JOIN
content
ON
link.content_id = content.id
LIMIT 10;
+----+-------------+---------+--------+---------------+---------+---------+------------------------+---------+-------------+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+----+-------------+---------+--------+---------------+---------+---------+------------------------+---------+-------------+
| 1 | SIMPLE | link | index | content_id | PRIMARY | 7 | NULL | 4555299 | Using index |
| 1 | SIMPLE | content | eq_ref | PRIMARY | PRIMARY | 4 | ft_dir.link.content_id | 1 | |
+----+-------------+---------+--------+---------------+---------+---------+------------------------+---------+-------------+
```
Are there any work-arounds to this?
I realize I'm selecting the entire table in the second example, but why does mysql suddenly decide that it's going to ignore my FORCE anyway and not use the key? Without the key the query takes like 10 minutes.. ugh. | FORCE is a bit of a misnomer. Here's what the MySQL docs say (emphasis mine):
*You can also use FORCE INDEX, which acts like USE INDEX (index\_list) but with the addition that a table scan is assumed to be very expensive. In other words, **a table scan is used only if there is no way to use one of the given indexes to find rows** in the table.*
Since you aren't actually "finding" any rows (you are selecting them all), a table scan is **always** going to be fastest, and the optimizer is smart enough to know that in spite of what you are telling them.
ETA:
Try adding an ORDER BY on the primary key once and I bet it'll use the index. | An index helps search quickly inside a table, but it just slows things down if you select the entire table. So MySQL is correct in ignoring the index.
In your case, maybe the index has a hidden side effect that's not known to MySQL. For example, if the inner join holds only for a few rows, an index would speed things up. But MySQL can't know that without an explicit hint.
There is an exception: when every column you select is inside the index, the index is still useful if you select every row. For example, if you have an index on LastName, the following query still benefits from the index:
```
select LastName from orders
```
But this one won't:
```
select * from Orders
``` | Mysql Index Being Ignored | [
"",
"sql",
"mysql",
"indexing",
"primary-key",
"key",
""
] |
In a web application that I have run across, I found the following code to deal with the DataContext when dealing with LinqToSQL
```
public partial class DbDataContext
{
public static DbDataContext DB
{
get
{
if (HttpContext.Current.Items["DB"] == null)
HttpContext.Current.Items["DB"] = new DbDataContext();
return (DbDataContext)HttpContext.Current.Items["DB"];
}
}
}
```
Then referencing it later doing this:
```
DbDataContext.DB.Accounts.Single(a => a.accountId == accountId).guid = newGuid;
DbDataContext.DB.SubmitChanges();
```
I have been looking into best practices when dealing with LinqToSQL.
I am unsure about the approach this one has taken when dealing with DataContext not being ThreadSafe and keeping a static copy of it around.
Is this a good approach to take in a web application?
@Longhorn213 - Based on what you said and the more I have read into HttpContext because of that, I think you are right. But in the application that I have inherited it is confusing this because at the beginning of each method they are requerying the db to get the information, then modifying that instance of the datacontext and submitting changes on it.
From this, I think this method should be discouraged because it is giving the false impression that the datacontext is static and persisting between requests. If a future developer thinks that requerying the data at the beginning of a method because they think it is already there, they could run into problems and not understand why.
So I guess my question is, should this method be discouraged in future development? | This is not a static copy. Note that the property retrieves it from Context.Items, which is per-request. This is a per-request copy of the DataContext, accessed through a static property.
On the other hand, this property is assuming only a single thread per request, which may not be true forever. | I prefer to create a Page base class (inherit from System.Web.UI.Page), and expose a DataContext property. It ensures that there is one instance of DataContext per page request.
This has worked well for me, it's a good balance IMHO. You can just call DataContext.SubmitChanges() at the end of the page and be assured that everything is updated. You also ensure that all the changes are for one user at a time.
Doing this via static will cause pain -- I fear DataContext will lose track of changes since it's trying to track changes for many users concurrently. I don't think it was designed for that. | LinqToSql static DataContext in a web application | [
"",
"c#",
"asp.net",
"linq-to-sql",
"datacontext",
""
] |
I have a swing application which stores a list of objects. When the users clicks a button,
I want to perform two operations on each object in the list, and then once that is complete, graph the results in a JPanel. I've been trying SwingWorker, Callable & Runnable to do the processing, but no matter what I do, while processing the list (which can take up to a few minutes, as it is IO bound), the GUI is locked up.
I have a feeling it's probably the way I'm calling the threads or something, or could it be to do with the graphing function? That isn't threaded as it is very quick.
I have to do the two processing stages in order too, so what is the best way to ensure the second one has waited on the first? I've used join(), and then
```
while(x.isAlive())
{
Thread.sleep(1000);
}
```
to try and ensure this, but I'm worried this could be the cause of my problem too.
I've been looking everywhere for some pointers, but since I can't find any I'm sure I'm doing something stupid here. | The problem is, your long running task is blocking the Thread that keeps the GUI responsive.
What you will need to do is put the long running task on another thread.
Some common ways of doing this are using Timers or a [`SwingWorker`](http://java.sun.com/javase/6/docs/api/javax/swing/SwingWorker.html).
The [Java tutorials](http://java.sun.com/docs/books/tutorial/uiswing/concurrency/) have lots of information regarding these things in their lesson in concurrency.
To make sure the first task finishes before the second, just put them both on the same thread. That way you won't have to worry about keeping two different threads timed correctly.
Here is a sample implementation of a SwingWorkerFor your case:
```
public class YourTaskSwingWorkerSwingWorker extends SwingWorker<List<Object>, Void> {
private List<Object> list
public YourClassSwingWorker(List<Object> theOriginalList){
list = theOriginalList;
}
@Override
public List<Object> doInBackground() {
// Do the first opperation on the list
// Do the second opperation on the list
return list;
}
@Override
public void done() {
// Update the GUI with the updated list.
}
}
```
To use this code, when the event to modify the list is fired, create a new `SwingWorker` and tell it to start. | You are not returning the swing thread properly. I realize you are using callable/runnable but i'm guessing you are not doing it right (although you didn't post enough code to know for sure).
The basic structure would be:
```
swingMethod() { // Okay, this is a button callback, we now own the swing thread
Thread t=new Thread(new ActuallyDoStuff());
t.start();
}
public class ActuallyDoStuff() implements Runnable {
public void run() {
// this is where you actually do the work
}
}
```
This is just off the top of my head, but I'm guessing that you either aren't doing the thread.start and are instead calling the run method directly, or you are doing something else in the first method that locks it up (like thread.join). Neither of these would free up the swing thread. The first method MUST return quickly, the run() method can take as long as it wants.
If you are doing a thread.join in the first method, then the thread is NOT being returned to the system!
Edit: (Second edit actually)
I think to speak to the problem you are actually feeling--you might want to think more in terms of a model/view/controller system. The code you are writing is the controller (the view is generally considered to be the components on the screen--view/controller are usually very tightly bound).
When your controller gets the event, it should pass the work off to your model. The view is then out of the picture. It does not wait for the model, it's just done.
When your model is finished, it needs to then tell the controller to do something else. It does this through one of the invoke methods. This transfers control back to the controller and you go on your merry way. If you think about it this way, separating control and deliberately passing it back and forth doesn't feel so bulky, and it's actually very common to do it this way. | Prevent Swing GUI locking up during a background task | [
"",
"java",
"multithreading",
"swing",
"swingworker",
"event-dispatch-thread",
""
] |
How can I use win32 API in Python?
What is the best and easiest way to do it?
Can you please provide some examples? | PyWin32 is the way to go - but how to use it? One approach is to begin with a concrete problem you're having and attempting to solve it. PyWin32 provides bindings for the Win32 API functions for which there are many, and you really have to pick a specific goal first.
In my Python 2.5 installation (ActiveState on Windows) the win32 package has a Demos folder packed with sample code of various parts of the library.
For example, here's CopyFileEx.py:
```
import win32file, win32api
import os
def ProgressRoutine(TotalFileSize, TotalBytesTransferred, StreamSize, StreamBytesTransferred,
StreamNumber, CallbackReason, SourceFile, DestinationFile, Data):
print Data
print TotalFileSize, TotalBytesTransferred, StreamSize, StreamBytesTransferred, StreamNumber, CallbackReason, SourceFile, DestinationFile
##if TotalBytesTransferred > 100000:
## return win32file.PROGRESS_STOP
return win32file.PROGRESS_CONTINUE
temp_dir=win32api.GetTempPath()
fsrc=win32api.GetTempFileName(temp_dir,'cfe')[0]
fdst=win32api.GetTempFileName(temp_dir,'cfe')[0]
print fsrc, fdst
f=open(fsrc,'w')
f.write('xxxxxxxxxxxxxxxx\n'*32768)
f.close()
## add a couple of extra data streams
f=open(fsrc+':stream_y','w')
f.write('yyyyyyyyyyyyyyyy\n'*32768)
f.close()
f=open(fsrc+':stream_z','w')
f.write('zzzzzzzzzzzzzzzz\n'*32768)
f.close()
operation_desc='Copying '+fsrc+' to '+fdst
win32file.CopyFileEx(fsrc, fdst, ProgressRoutine, operation_desc, False, win32file.COPY_FILE_RESTARTABLE)
```
It shows how to use the CopyFileEx function with a few others (such as GetTempPath and GetTempFileName). From this example you can get a "general feel" of how to work with this library. | PyWin32, as mentioned by @chaos, is probably the most popular choice; the alternative is [ctypes](http://docs.python.org/library/ctypes.html) which is part of Python's standard library. For example, `print ctypes.windll.kernel32.GetModuleHandleA(None)` will show the module-handle of the current module (EXE or DLL). A more extensive example of using ctypes to get at win32 APIs is [here](http://web.archive.org/web/20081016104309/http://mail.python.org/pipermail/python-list/2005-March/314328.html). | How to use Win32 API with Python? | [
"",
"python",
"winapi",
"api",
""
] |
I seem to have confused myself with a preg\_match regex I'm doing, so fresh eyes and help would be appreciated.
My current regex is as follows:
```
/<!--menu:start:\(([0-9])\,([0-9])\)-->(.*?)<!--menu:end-->/se
```
I am looking to make the number input and colon e.g. :(1,4) optional, so it would match:
```
<!--menu:start--><!--menu:end-->
```
or
```
<!--menu:start:(0,3)--><!--menu:end-->
``` | Enclose with a non matching group and set it to optional : `(?:...)?`
```
/<!--menu:start(?::\(([0-9])\,([0-9])\))?-->(.*?)<!--menu:end-->/se
``` | Like this:
```
/<!--menu:start(?::\((\d),(\d)\))?-->(.*?)<!--menu:end-->/se
```
I've added a non-capturing group, `(?: )`, around the part you want to be optional, and then suffixed it with a question mark: `(?:<optional content>)?` | Regex Optional Groups? | [
"",
"php",
"regex",
"preg-replace",
"preg-match",
""
] |
I am using borland 2006 c++, and have following code. I am using vectors, and have trouble understanding why the destructor is not being called.
basically i have a class A
```
class A
{
private:
TObjectList* list;
int myid;
public:
__fastcall A(int);
__fastcall ~A();
};
__fastcall A::A(int num)
{
myid = num;
list = new TObjectList();
}
__fastcall A::~A()
{
delete list;
}
int main(int argc, char* argv[])
{
myfunc();
return 0;
}
void myfunc()
{
vector<A*> vec;
vec.push_back(new A(1));
vec.push_back(new A(2));
}
```
according to what i read, when variable vec goes out of scope in myfunc(), it should destruct its contained elements, so the destructor for A should be called. I have a breakpoint at ~A(), but never gets called, i have tried resize(), erase methods also
TIA | vec does destruct its elements when it goes out of scope. The problem here is that vec's elements are the *pointers* to A objects, not A objects themselves. If you instead did
```
vector<A> vec;
vec.push_back(A(1));
vec.push_back(A(2));
```
...then things would work as you expect.
ETA: note, though, that if you do this you have to define a copy constructor for A. That should involve doing a deep copy of the TObjectList member. Otherwise, when you copy an A object you'll wind up with two objects both pointing to the same TObjectList, and your program will crash when the second object is destroyed. | Lots of good answers already, but I'll add one more:
Use **boost::ptr\_vector** from the [Boost Pointer Container Library](http://www.boost.org/doc/libs/1_39_0/libs/ptr_container/doc/ptr_container.html), instead of std::vector. It will delete the objects when the vector goes out of scope, thus calling the destructors. | stl vector memory management | [
"",
"c++",
""
] |
I want my product, like every other web product out there, to pull a data information from my database and convert it to the user's timezone before displaying it on a page. I am using PHP and MySQL.
Is the use of TIMESTAMP fields more common than the use of DATETIME fields?
From my research, it seems that using DATETIME fields, I would have to
1. Store all date information in UTC
2. call `date_default_timezone_set('UTC')` each time the application starts
3. manually subtract the user's UTC offset hours from dates created using date() being based on the current date/time
4. manually subtract the user's UTC offset hours from existing dates passed to and formatted by date()
Using TIMESTAMPS for my date fields, it seems I will only have to run the following when a database connection is made: SET time\_zone='the users timezone' (eg. America/Los\_Angelos).
Considering this, I would deduce most people would be inclined to using TIMESTAMPs rather than DATETIMEs...is this accurate? | From [this](http://www.sqlteam.com/article/timestamps-vs-datetime-data-types) location:
> The SQL Server timestamp data type has
> nothing to do with times or dates. SQL
> Server timestamps are binary numbers
> that indicate the relative sequence in
> which data modifications took place in
> a database. The timestamp data type
> was originally implemented to support
> the SQL Server recovery algorithms.
Edit: to answer your question, DATETIME is more commonly used, as TIMESTAMP is not intended to be used for storing general Date / Time information. | No, I don't think that's accurate.
Generally, you use datetime to store just that - the date and time that something is happening, when it's entered into your site. You use timestamp to keep track of when data was entered into your site for your program's use. timestamp shouldn't have to keep track of time zones because all of the work happens in your db server's time zone - whereas datetime has more options for presenting it properly for it to make sense as output to the user.
So, for the question "Which is more common for presenting user-timezone data", I'd say the answer is DATETIME. | How common are TIMESTAMPS over DATETIME fields? | [
"",
"php",
"mysql",
"timezone",
""
] |
Which is better in AJAX request, Response with ready HTML or response with just data and write HTML using JavaScript, and this JavaScript will use a predefined HTML template to put the coming data inside and show on the page.
Creating the HTML on the server and send to the page, will decrease the client side JS code, but will increase the response size.
Sending the data to the client side will decrease the response size but will increase the JS code.
Which is better and most used? | I think the right solution is highly context dependent. There may be a **right** answer for a given situation, but there is no one size fits all answer. Generally, if I'm using a partial view that gets replaced via AJAX, I'll return html. If I'm performing an action on a small part of something, I'll use JSON. I'm probably more likely to use JSON as there are more situations where it fits, but I try to pick the best solution for the problem at hand. I'm using ASP.NET MVC, though. Other frameworks undoubtedly have different characteristic solutions. | I've seen both used. In addition to the tradeoffs listed in the OP, I'd add:
* It is better to send the information as data, not html since you'll then have more options in how you will use it.
* What is your comfort level with JS?
* You can use multiple UI's (on different pages) and can re-use the data on the page. Eg display the data in a short form and in a long form, but use the same data source. -- letting the client switch between the two on a page without requiring a server trip.
* A pure JS implementation of the liquid template system is available for client-side templating: <http://www.mattmccray.com/archive/2008/12/11/Liquidjs_A_Non-Evaling_Templat>
Larry | Using Ajax, is it better to generate additional markup in the server or the client side? | [
"",
"asp.net",
"javascript",
"ajax",
""
] |
**First, the problem:**
I have several free projects, and as any software they contains bugs. Some fellow users when encounter bug send me a bug-reports with stack traces. In order to simplify finding fault place, I want to see line numbers in this stack traces. If application shipped without .pdb files, then all line information is lost, so currently all my projects deployed with .pdb files, and so generated stack traces has this numbers.
But! But I do not want to see this files in distribution and want to remove all .pdb. They confuse users, consume space in installer, etc.
**Delphi solution:**
Long time ago when I was a delphi programmer, I used the following technique: on exception my application walk on stack and collect addresses. Then, when I receive bug-report, I used a tool that reconstruct valid stack trace with function names and line numbers based on collected addresses and corresponding symbol files located on MY machine.
**Question:**
Is there any lib, or technique or whatever to do the same in .NET?
**Status Update:** Very interesting, that often asking a question is the best way to start your own investigation. For example I think about this problem for some time, but start looking for answer only several days ago.
Option 1: MiniDumps. After a lot googling I have found a way to create mini dump from code, and how to recreate stack from managed mini dump.
* Redistributable assembly to create mini dump form code - [clrdump](http://www.debuginfo.com/tools/clrdump.html#redist)
* Blog post about using previous assembly - [Creating and analyzing minidumps in .NET production applications](http://voneinem-windbg.blogspot.com/2007/03/creating-and-analyzing-minidumps-in-net.html)
This solution however need to redistribute two additional assemblies (~1mb in size), and mini dumps takes some space, and it is uncomfortable for user to send them by email. So for my purposes, right now, it is unacceptable.
Option 2: Thanks to weiqure for clue. It is possible to extract managed IL offset for every stack frame. Now the problem is how to get line numbers from .pdb based on this offsets. And what I have found:
* [PDB File Internals](http://www.informit.com/articles/article.aspx?p=22685), just for information because:
* [ISymbolReader](http://msdn.microsoft.com/en-us/library/system.diagnostics.symbolstore.isymbolreader.aspx) - managed interface to read program database files
* And finally a [tool to convert .pdb files to structured xml](http://blogs.msdn.com/jmstall/archive/2005/08/25/pdb2xml.aspx) for easy xpath processing
Using this tool, it is possible to create xml files for every release build and put them into repositary. When exception occurs on user's machine, it is possible to create formatted error message with IL offsets. Then user send this message (very small) by mail. And finally, it is possible to create a simple tool that recreate resulting stack from formatted error message.
I only wondering why nobody else does not implement a tool like this? I don't believe that this is interesting for me only. | You can get the offset of the last MSIL instruction from the Exception using System.Diagnostics.StackTrace:
```
// Using System.Diagnostics
static void Main(string[] args)
{
try { ThrowError(); }
catch (Exception e)
{
StackTrace st = new System.Diagnostics.StackTrace(e);
string stackTrace = "";
foreach (StackFrame frame in st.GetFrames())
{
stackTrace = "at " + frame.GetMethod().Module.Name + "." +
frame.GetMethod().ReflectedType.Name + "."
+ frame.GetMethod().Name
+ " (IL offset: 0x" + frame.GetILOffset().ToString("x") + ")\n" + stackTrace;
}
Console.Write(stackTrace);
Console.WriteLine("Message: " + e.Message);
}
Console.ReadLine();
}
static void ThrowError()
{
DateTime myDateTime = new DateTime();
myDateTime = new DateTime(2000, 5555555, 1); // won't work
Console.WriteLine(myDateTime.ToString());
}
```
Output:
> at ConsoleApplicationN.exe.Program.Main (IL offset: 0x7)
> at ConsoleApplicationN.exe.Program.ThrowError (IL offset: 0x1b)
> at mscorlib.dll.DateTime..ctor (IL offset: 0x9)
> at mscorlib.dll.DateTime.DateToTicks (IL offset: 0x61)
> Message: Year, Month, and Day parameters describe an un-representable DateTime.
You can then use [Reflector](http://www.red-gate.com/products/reflector/) or [ILSpy](http://ilspy.net/) to interpret the offset:
```
.method private hidebysig static void ThrowError() cil managed
{
.maxstack 4
.locals init (
[0] valuetype [mscorlib]System.DateTime myDateTime)
L_0000: nop
L_0001: ldloca.s myDateTime
L_0003: initobj [mscorlib]System.DateTime
L_0009: ldloca.s myDateTime
L_000b: ldc.i4 0x7d0
L_0010: ldc.i4 0x54c563
L_0015: ldc.i4.1
L_0016: call instance void [mscorlib]System.DateTime::.ctor(int32, int32, int32)
L_001b: nop
L_001c: ldloca.s myDateTime
L_001e: constrained [mscorlib]System.DateTime
L_0024: callvirt instance string [mscorlib]System.Object::ToString()
L_0029: call void [mscorlib]System.Console::WriteLine(string)
L_002e: nop
L_002f: ret
}
```
You know that the instruction before 0x1b threw the exception. It's easy to find the C# code for that:
```
myDateTime = new DateTime(2000, 5555555, 1);
```
You could map the IL code to your C# code now, but I think the gain would be too little and the effort too big (though there might be a reflector plugin). You should be fine with the IL offset. | You should use [Environment.FailFast](http://msdn.microsoft.com/en-us/library/ms131100.aspx), call FailFast in the [Application.UnhandledException](http://msdn.microsoft.com/en-us/library/system.windows.application.unhandledexception(VS.95).aspx) and a dump file will be created for you.
From the MSDN:
> The FailFast method writes a log entry
> to the Windows Application event log
> using the message parameter, creates a
> dump of your application, and then
> terminates the current process.
>
> Use the FailFast method instead of the
> Exit method to terminate your
> application if the state of your
> application is damaged beyond repair,
> and executing your application's
> try-finally blocks and finalizers will
> corrupt program resources. The
> FailFast method terminates the current
> process and executes any
> CriticalFinalizerObject objects, but
> does not execute any active
> try-finally blocks or finalizers.
You can write a simple app that will collect the log files and send them to you.
Now, opening the dump file is a bit tricky, Visual Studio cannot handle managed dump file (fixed in .NET 4.0) you can use [WinDBG](http://www.microsoft.com/whdc/DevTools/Debugging/default.mspx) but you need to use [SOS](http://www.microsoft.com/whdc/DevTools/Debugging/default.mspx). | Recreate stack trace with line numbers from user bug-report in .net? | [
"",
"c#",
".net",
"debugging",
"stack-trace",
""
] |
I'm getting no Javascript errors, but the code does nothing...
```
function registerValidator(target, validator) {
var element = document.getElementById(target);
if (element) {
var validationID = element.id + "_validationResult";
var validationSpan = document.createElement('span');
validationSpan.id = validationID;
element.parentNode.appendChild(validationSpan);
element.onkeyup = function() {
var result = validator(element);
if (result.ok) {
validationSpan.innerHTML = '<img src="/media/valid.gif" width="12" />';
} else {
validationSpan.innerHTML = '<img src="/media/invalid.gif" width="12" />';
if (result.message) {
validationSpan.innerHTML += '<br />' + result.message;
}
}
};
alert(1);
}
}
window.onload = function() {
registerValidator('username', function(element) {
var result = new Object();
alert('validate');
if (element.value.length >= 4) {
result.ok = true;
}
else {
result.ok = false;
result.message = "Too short";
}
return result;
});
alert(2);
}
```
The two alerts (1 and 2) are triggered correctly, but the 'validate' alert is never triggered. The function is used for the following element:
```
<input type="text" name="username" id="username" />
```
I have tried this in Google Chrome, Firefox 3 and Internet Explorer 8. | Oops. I forgot there's another textbox with id "username" in the header of the page, to allow people to login. Obviously the validation was working fine there ¬\_¬ | Everything is working fine here. see test page at <http://ashita.org/StackOverflow/validator.html>
---
You are currently using element.onkeyup which could be getting clobbered by another script.
try using
```
if (element.addEventListener)
element.addEventListener("keyup", validator,false);
else if (element.attachEvent)
element.attachEvent("onkeyup", validator);
```
References:
* attachEvent <http://msdn.microsoft.com/en-us/library/ms536343(VS.85).aspx>
* addEventListener <https://developer.mozilla.org/en/DOM/element.addEventListener> | Unable to validate user input - onkeyup event not firing | [
"",
"javascript",
""
] |
For my project i needed to rotate a rectangle. I thought, that would be easy but i'm getting an unpredictable behavior when running it..
Here is the code:
```
glPushMatrix();
glRotatef(30.0f, 0.0f, 0.0f, 1.0f);
glTranslatef(vec_vehicle_position_.x, vec_vehicle_position_.y, 0);
glEnable(GL_TEXTURE_2D);
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
glBegin(GL_QUADS);
glTexCoord2f(0.0f, 0.0f);
glVertex2f(0, 0);
glTexCoord2f(1.0f, 0.0f);
glVertex2f(width_sprite_, 0);
glTexCoord2f(1.0f, 1.0f);
glVertex2f(width_sprite_, height_sprite_);
glTexCoord2f(0.0f, 1.0f);
glVertex2f(0, height_sprite_);
glEnd();
glDisable(GL_BLEND);
glDisable(GL_TEXTURE_2D);
glPopMatrix();
```
The problem with that, is that my rectangle is making a translation somewhere in the window while rotating. In other words, the rectangle doesn't keep the position : `vec_vehicle_position_.x` and `vec_vehicle_position_.y`.
What's the problem ?
Thanks | You need to flip the order of your transformations:
```
glRotatef(30.0f, 0.0f, 0.0f, 1.0f);
glTranslatef(vec_vehicle_position_.x, vec_vehicle_position_.y, 0);
```
becomes
```
glTranslatef(vec_vehicle_position_.x, vec_vehicle_position_.y, 0);
glRotatef(30.0f, 0.0f, 0.0f, 1.0f);
``` | To elaborate on the previous answers.
Transformations in OpenGL are performed via matrix multiplication. In your example you have:
M\_r\_ - the rotation transform
M\_t\_ - the translation transform
v - a vertex
and you had applied them in the order:
M\_r\_ \* M\_t\_ \* v
Using parentheses to clarify:
( M\_r\_ \* ( M\_t\_ \* v ) )
We see that the vertex is transformed by the closer matrix first, which is in this case the translation. It can be a bit counter intuitive because this requires you to specify the transformations in the order opposite of that which you want them applied in. But if you think of how the transforms are placed on the matrix stack it should hopefully make a bit more sense (the stack is pre-multiplied together).
Hence why in order to get your desired result you needed to specify the transforms in the opposite order. | C++/OpenGL - Rotating a rectangle | [
"",
"c++",
"opengl",
"rotation",
""
] |
I have a XML schema, and I know that "xsd.exe" can generate the C# code for it. But I want to know if is possible to automatically create the MS SQL Server 2005+ tables from the XSD, with the help of this or other tools.
BTW I didn't get what the C# code generated by "xsd.exe" is worth for.
What's the difference between code generated by CodeXS and xsd.exe? | You can use the XSD2DB utility
This is the Example
xsd2db.exe -f true -l [Server Name] -n [Database Name] -s D:\po.xsd -t sql
Link for Help
<http://xsd2db.sourceforge.net/> | Disclaimer: I haven't done this myself, but I bookmarked these links a little while ago when I was thinking about doing this. This guy's T-SQL is usually brilliant, so I'd recommend it highly:
<http://weblogs.sqlteam.com/peterl/archive/2009/03/05/Extract-XML-structure-automatically.aspx>
<http://weblogs.sqlteam.com/peterl/archive/2009/06/04/Extract-XML-structure-automatically-part-2.aspx> | How to create SQL Server table schema from a XML schema? (with .NET and Visual Studio 2008) | [
"",
"c#",
".net",
"sql-server",
"xml",
"sql-server-2005",
""
] |
I don't understand what is going on here...
I've got the following error:
*The type `'TestApp.TestVal'` cannot be used as type parameter `'T'` in the generic type or method `'TestApp.SomeClass<T>'`. There is no boxing conversion from `'TestApp.TestVal'` to `'System.IComparable<TestApp.TestVal>'`.*
This error happens for the following code:
```
public enum TestVal
{
First,
Second,
Third
}
public class SomeClass<T>
where T : IComparable<T>
{
public T Stored
{
get
{
return storedval;
}
set
{
storedval = value;
}
}
private T storedval;
}
class Program
{
static void Main(string[] args)
{
//Error is on the next line
SomeClass<TestVal> t = new SomeClass<TestVal>();
}
}
```
Since the enum is an `int` by default and int's implement the `IComparable<int>` interface it seems like there shouldn't be an error.... | Firstly, I'm not sure whether it is sensible to use `IComparable<T>` with an enum... `IEquatable<T>`, sure - but comparison?
As a safer alternative; rather than mandate the `IComparable<T>` with the generic constraint, perhaps use `Comparer<T>.Default` inside the class. This has the advantage of supporting `IComparable<T>` and `IComparable` - and it means you have less constraints to propagate.
For example:
```
public class SomeClass<T> { // note no constraint
public int ExampleCompareTo(T other) {
return Comparer<T>.Default.Compare(Stored, other);
}
... [snip]
}
```
This works fine with the enum:
```
SomeClass<TestVal> t = new SomeClass<TestVal>();
t.Stored = TestVal.First;
int i = t.ExampleCompareTo(TestVal.Second); // -1
``` | Enums do not derive from System.Int32s - they derive from System.Enum, which doesn't implement `IComparable<int>` (it does implement `IComparable`, though).
Although an enum's underlying value is an int by default, the enum itself isn't. Thus, there is no conversion between the two. | C# boxing enum error with generics | [
"",
"c#",
"generics",
"enums",
"icomparablet",
""
] |
i made a basic calculator. but i don't know how to assign keypress. how it assigned? | you can wire the text box OnKeyPress event
Here is sample from the [MSDN](http://msdn.microsoft.com/en-us/library/system.windows.forms.control.onkeypress(VS.80).aspx)
Hope this helps | I **strongly** suggest you pick up a copy of a C# book (covering Windows Forms, etc) or try to follow an on-line tutorial.
For example, take a look at [this tutorial](http://kamhungsoh.com/001e.php) or [this one](http://csharpcomputing.com/Tutorials/calculator.htm)... Googling "C# windows forms calculator" gives 320,000 hits!
### On-keys screen
Assuming you are developing a GUI and by 'key-presses' you mean the 'on-screen keys', then what you are wanting to do, roughly, is:
1. Assign an event to your button, the Click event seems best.
2. In the event-handler, you will need to maintain some list of clicks or convert directly to a number e.g. currentDisplayValue = (currentDisplayValue \* 10) + thisDigit
3. When the plus, minus, multiply, divide, equals buttons are pressed, you need to do the appropriate action with the displayValue and the previously calculated value.
The logic of a calculator will be easy to find on the internet, the magic is wiring the button's events to an event handler to do the work for you!
### Physical keys (eg. number-pad)
This gets harder. The GUI typically routes the keyboard to the focused control. You need to overcome this routing:
* On the form, set `KeyPreview` to `true`
* Register an event-handler to the form
```
// Associate the event-handling method with the
// KeyDown event.
this.KeyDown += new KeyEventHandler(Form1_KeyDown);
```
* In the event-handler, do your calculation using the "KeyCode" values
```
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
switch (e.KeyCode)
{
case "0":
// Zero
break;
case "1":
// One
break;
// .. etc
case "+":
// Plus
break;
default:
// Avoid setting e.Handled to
return;
}
e.Handled = true;
}
``` | Calculator keypress | [
"",
"c#",
".net",
"winforms",
""
] |
I'm a beginner so if there is a terminology for what I'm doing I don't know how to search for it. So forgive me if this has been asked before. So here is what I do. Before I make any major code changes, I make a copy of the projects folder and call it "project v6" for example. Then if I really mess things up and cant find a way to undo it, I just go back to the previous folder. This has been working well enough for me but sometimes I forget to do this and have to take 2 steps back. Is there an easier way to do this than the way I am now? | There are many source control tools, which keeps track of all this stuff. [Git](http://en.wikipedia.org/wiki/Git_(software)), [subversion](http://en.wikipedia.org/wiki/Subversion_(software)), [cvs](http://en.wikipedia.org/wiki/Concurrent_Versions_System) (used wikipedia links, which explains each with more detail. This can be done much more easily once you get used to them.
In both there is commit what you've done to a server (which may be your own machine). But you can store your code somewhere else (so you don't lose everything, in case your hard disk fails or something like that). [Google Code](http://code.google.com/) is a good example.
Git - harder to use, but very powerful (more used when there are lots of people working on the same project, and even the same file sometimes), much easier to deal with branches and stuff like that (if you don't know what that is, so you probably don't need it yet)
svn (subversion) and cvs - simpler to use, with fewer resources available. Probably enough for your needs | What you're looking for is revision/source control software.
<http://en.wikipedia.org/wiki/Revision_control> | Keeping track of changes I make by copying project folders | [
"",
"c#",
"version-control",
""
] |
I need to insert key value pairs in app.Config as follows:
```
<configuration>
<appSettings>
<add key="Setting1" value="Value1" />
<add key="Setting2" value="Value2" />
</appSettings>
</configuration>
```
When I searched in google I got the following code snippet
```
System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); // Add an Application Setting.
config.AppSettings.Settings.Add("ModificationDate",
DateTime.Now.ToLongTimeString() + " ");
// Save the changes in App.config file.
config.Save(ConfigurationSaveMode.Modified);
```
The above code is not working as ConfigurationManager is not found in System.Configuration namespace I'm using .NET 2.0.
How to add key-value pairs to app.Config programatically and retrieve them? | Are you missing the reference to System.Configuration.dll? `ConfigurationManager` class lies there.
EDIT: The `System.Configuration` namespace has classes in mscorlib.dll, system.dll and in system.configuration.dll. Your project always include the mscorlib.dll and system.dll references, but system.configuration.dll must be added to most project types, as it's not there by default... | This works:
```
public static void AddValue(string key, string value)
{
Configuration config = ConfigurationManager.OpenExeConfiguration(Application.ExecutablePath);
config.AppSettings.Settings.Add(key, value);
config.Save(ConfigurationSaveMode.Minimal);
}
``` | Add values to app.config and retrieve them | [
"",
"c#",
""
] |
This ought to be pretty simple, maybe use a regex but I would think there is an easier - faster way. Currently I make this work by using a couple of splits, but that sure seems like a poor method.
Example string:
> on Jun 09, 2009. Tagged:
What I need to do is turn that date (June 09, 2009) into three strings (Jun, 09, 2009). Obviously this date may vary to things like May 25, 2011. I assume using the two outside strings which would be consistent ("on " and ". Tagged") and searching based on them is the best method. The month will always be three letters.
What would be a better way to do this via Javascript?
Thanks! | You could do it using substring commands, but a regex would be simpler and less prone to breaking if the source data ever changed.
You can use this regex:
```
var input = "on Jun 09, 2009 Tagged:";
var date = input.match(/([a-zA-Z]{3}) (\d{1,2}), (\d{4})/);
// date = ["Jun 09, 2009", "Jun", "09", "2009"];
var simpledate = date.slice(1);
// simpledate = ["Jun", "09", "2009"];
```
When using RegEx's, I find this site to be extremely useful: <http://www.regular-expressions.info/javascriptexample.html>
It provides a JavaScript regex tester that's very handy! You can plug in same data and a regex and run it and see the matched data. It's helped me to understand regular expressions a lot better. For example, you can see that my regex and the other answers are different but accomplish the same thing. | You could use a regular expression:
```
var match = str.match(/on (\w+) (\d{2}), (\d{4})\. Tagged/);
// match = ["on Jun 09, 2009. Tagged", "Jun", "09", "2009"]
``` | Efficient way to find a string between two other strings via Javascript | [
"",
"javascript",
"string",
""
] |
If you have a `$start_date` and `$end_date`, how can you check if a date given by the user falls within that range?
e.g.
```
$start_date = '2009-06-17';
$end_date = '2009-09-05';
$date_from_user = '2009-08-28';
```
At the moment the dates are strings, would it help to convert them to timestamp integers? | Converting them to timestamps is the way to go alright, using [strtotime](http://php.net/strtotime), e.g.
```
$start_date = '2009-06-17';
$end_date = '2009-09-05';
$date_from_user = '2009-08-28';
check_in_range($start_date, $end_date, $date_from_user);
function check_in_range($start_date, $end_date, $date_from_user)
{
// Convert to timestamp
$start_ts = strtotime($start_date);
$end_ts = strtotime($end_date);
$user_ts = strtotime($date_from_user);
// Check that user date is between start & end
return (($user_ts >= $start_ts) && ($user_ts <= $end_ts));
}
``` | Use the DateTime class if you have PHP 5.3+. Easier to use, better functionality.
DateTime internally supports timezones, with the other solutions is up to you to handle that.
```
<?php
/**
* @param DateTime $date Date that is to be checked if it falls between $startDate and $endDate
* @param DateTime $startDate Date should be after this date to return true
* @param DateTime $endDate Date should be before this date to return true
* return bool
*/
function isDateBetweenDates(DateTime $date, DateTime $startDate, DateTime $endDate) {
return $date > $startDate && $date < $endDate;
}
$fromUser = new DateTime("2012-03-01");
$startDate = new DateTime("2012-02-01 00:00:00");
$endDate = new DateTime("2012-04-30 23:59:59");
echo isDateBetweenDates($fromUser, $startDate, $endDate);
``` | How to check if a date is in a given range? | [
"",
"php",
"date",
"date-range",
""
] |
Recently I stumbled on an interesting bug where entries would show up in our local custom-made ticket system from users that didn't exist in the app. After some poking around I realised that both this and another PHP app running on the same server were using $\_SESSION['user'] for authentication purposes. When someone used one system and then opened the other one he was "automatically" logged in as a user from the first app.
After the obligatory facepalm I changed the session variable name in one of the systems to stop this. However I need to make a permanent, zero-maintenance change to my session handling class to avoid this in future projects. I figure this could be done by using a unique value (for example the script path) to put an app's variables in a place in $\_SESSION that wont be used by another app.
Is there a better way?
Edit: This is on linux. And both apps are on the same website. | You can ensure that the Session cookies will be specific to the application by making sure that the domain and path of the cookies are set restrictively, e.g. for an application at <http://www.example.com/apppath>, you could do the following:
```
<?php
$currentParams = session_get_cookie_params();
session_set_cookie_params($currentParams['lifetime'], '/apppath/', 'www.example.com', $currentParams['secure'], $currentParams['httponly']);
session_start();
```
This will leave the other session settings intact.
The path is probably the important one, by default PHP will issue the cookie for the domain that the site was requested over (I think), so you could probably actually leave the domain parameter as the default. | Set the cookie path so that each app only stores a session cookie valid for its own path.
You can do this with the [session\_set\_cookie\_params](https://www.php.net/manual/en/function.session-set-cookie-params.php) call. | Preventing session conflicts in PHP | [
"",
"php",
"session",
""
] |
I am looking for a tool that will let me model my domain as well as map exports of it to other formats. Is there anything good out there? | I know it costs money but have you looked at [Visio](http://office.microsoft.com/en-us/visio/default.aspx)? | [Enterprise Architect 7.5](http://www.sparxsystems.com/)
Its an excellent utility that fully supports UML, as well as several other modeling standards. It is not free, but it is almost industry standard as pretty much everywhere I have worked, EA was the de-facto standard tool for creating models. | What tool do you use to model your domain objects? | [
"",
".net",
"sql",
""
] |
I come from a C/C++ background and now do a lot of C# stuff.
Lately I have become interested in doing some projects in Java since playing around with the Android SDK.
I know that Java apps run in a sandbox that can limit their access to the system.
In a desktop/server application environment what kind of things are restricted? | For normal desktop and server apps, the limitations are not related to the sandbox concept (though you could use it to apply very fine-grained restrictions to e.g. user-submitted code) but to the platform-independant nature of Java. Basically, OS-specific stuff and hardware access usually can't be done in pure JAVA unless specifically adressed by the API library.
Examples are:
* Windows registry
* Windows system tray
* Bluetooth
* WLAN configuration | Java applications are much in a sandbox as .NET applications are in a sandbox. They both run on their respective virtual machines, and do have some limitations as to what they can do, but for the most part, they have a good deal of access to the system, including access to native code through certain calls.
You may be thinking about [Java applets](http://java.sun.com/docs/books/tutorial/deployment/applet/index.html), which run inside a browser, and generally will be in a security sandbox that prevents access to the system resources such as local files. (This restriction can be circumvented by specifically granting access to the system to certain applets.)
Here's a section on [Security Restrictions](http://java.sun.com/docs/books/tutorial/deployment/applet/security_practical.html) for applets from [The Java Tutorials](http://java.sun.com/docs/books/tutorial/index.html), which includes a list of restrictions placed on applets. | Limitations of Java desktop applications? | [
"",
"java",
"security",
"desktop-application",
"sandbox",
"restriction",
""
] |
On of my client asked me to create an Web App in PHP, I ended up using Symfony. At delivery, he told me that he has distributed a software with an embedded Web view pointing to a hardcoded url :
www.domain.com/dir/tools.php
Now he wants the Web app to appear in it's Web View, but the software isused by about 400 customers, we can't expect the hard coded URL to be changed.
How do you think I can do that in clean way :
* Create www.domain.com/dir/tools.php and use a redirection ? Which one and how ?
* Use URL rewriting ? Any snippets appreciated, I have no Idea how to do that. | Apache [mod\_rewrite](http://httpd.apache.org/docs/2.0/mod/mod_rewrite.html):
```
RewriteEngine on
RewriteRule ^dir/tools\.php$ new_page.php [R=301]
```
EDIT: As noted, this goes in your .htaccess file. The mod\_rewrite documentation I linked has more information. Fixed . | In your Apache configuration for the host or in a .htaccess file, you can do a redirect:
```
Redirect 301 /dir/tools.php http://www.example.com/whatever
``` | How to redirect a request to a non existant PHP file to a existing DIR in a clean way? | [
"",
"php",
"url-rewriting",
"redirect",
""
] |
I'm trying to call a class (main method) from command line (Windows) with Java.
The class imports other classes (other jars).
I always get "class not found exception" from a class that my main program imports.
Here's what I tried:
* Add a CLASSPATH env. var with the path where the referenced lib resides (not working)
* I tried with all these different parameters when calling "`java -jar myjar.jar`" from command line : "`-classpath lib/`", "`-classpath ./lib/`", "`-classpath lib`", "`-cp lib/*`", "`-cp lib/\*`", "`-classpath lib/referenced-class.jar`", "`-classpath ./lib/referenced-class.jar`" (lib is where the referenced jar resides)
* I tried packaging all the referenced jar inside my jar where my main class resides...
* And with all that, I also tried to specify the classes inside the Manifest file with:
`Class-path referenced-jar.jar` and I also tried `Class-path lib/referenced-jar.jar` | You could run it without the `-jar` command line argument if you happen to know the name of the main class you wish to run:
```
java -classpath .;myjar.jar;lib/referenced-class.jar my.package.MainClass
```
If perchance you are using linux, you should use ":" instead of ";" in the classpath. | If you're running a jar file with `java -jar`, the `-classpath` argument [is ignored](http://mindprod.com/jgloss/jar.html#CLASSPATH). You need to set the classpath in the manifest file of your jar, like so:
> `Class-Path: jar1-name jar2-name directory-name/jar3-name`
See the Java tutorials: [Adding Classes to the JAR File's Classpath](http://java.sun.com/docs/books/tutorial/deployment/jar/downman.html).
**Edit:** I see you already tried setting the class path in the manifest, but are you sure you used the correct syntax? If you skip the '`:`' after "`Class-Path`" like you showed, it would not work. | Java: how to import a jar file from command line | [
"",
"java",
"command-line",
"jar",
"classpath",
""
] |
I have an IEnumerable list of objects in C#. I can use a for each to loop through and examine each object fine, however in this case all I want to do is examine the first object is there a way to do this without using a foreach loop?
I've tried mylist[0] but that didnt work.
Thanks | (For the sake of convenience, this answer assumes `myList` implements `IEnumerable<string>`; replace `string` with the appropriate type where necessary.)
If you're using .NET 3.5, use the [`First()`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.first.aspx) extension method:
```
string first = myList.First();
```
If you're not sure whether there are any values or not, you can use the [`FirstOrDefault()`](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.firstordefault.aspx) method which will return `null` (or more generally, the default value of the element type) for an empty sequence.
You can still do it "the long way" without a `foreach` loop:
```
using (IEnumerator<string> iterator = myList.GetEnumerator())
{
if (!iterator.MoveNext())
{
throw new WhateverException("Empty list!");
}
string first = iterator.Current;
}
```
It's pretty ugly though :)
In answer to your comment, no, the returned iterator is *not* positioned at the first element initially; it's positioned *before* the first element. You need to call `MoveNext()` to move it to the first element, and that's how you can tell the difference between an empty sequence and one with a single element in.
EDIT: Just thinking about it, I wonder whether this is a useful extension method:
```
public static bool TryFirst(this IEnumerable<T> source, out T value)
{
using (IEnumerator<T> iterator = source.GetEnumerator())
{
if (!iterator.MoveNext())
{
value = default(T);
return false;
}
value = iterator.Current;
return true;
}
}
``` | Remember, there may be no "first element" if the sequence is empty.
```
IEnumerable<int> z = new List<int>();
int y = z.FirstOrDefault();
``` | C# IEnumerable Retrieve The First Record | [
"",
"c#",
".net",
""
] |
```
var allRapidSpells = $$('input[value^=RSW]');
```
Can anyone tell me what that does? | I would venture to guess that you're using [MooTools](http://mootools.net), a JavaScript framework. The [`$$()`](http://mootools.net/docs/core/Utilities/Selectors#Selectors) function is used to select an element (or multiple elements) in the DOM.
More specifically, the `$$('input[value^=RSW]');` syntax is selecting all `input` elements whose `value` attribute starts with `RSW`.
Other attribute selectors include:
* `=` : is equal to
* `*=` : contains
* `^=` : starts-with
* `$=` : ends-with
* `!=` : is not equal to
* `~=` : contained in a space separated list
* `|=` : contained in a '-' separated list
**Edit:** It looks as though [Prototype](http://prototypejs.org), another JavaScript framework, uses the [same syntax](http://prototypejs.org/api/utility/dollar-dollar). | Return all inputs that hava value starting with RSW | Javascript confusion | [
"",
"javascript",
""
] |
I like being able to measure performance of the python functions I code, so very often I do something similar to this...
```
import time
def some_function(arg1, arg2, ..., argN, verbose = True) :
t = time.clock() # works best in Windows
# t = time.time() # apparently works better in Linux
# Function code goes here
t = time.clock() - t
if verbose :
print "some_function executed in",t,"sec."
return return_val
```
Yes, I know you are supposed to measure performance with timeit, but this works just fine for my needs, and allows me to turn this information on and off for debugging very smoothly.
That code of course was from before I knew about function decorators... Not that I know much about them now, but I think I could write a decorator that did the following, using the \*\*kwds dictionary:
```
some_function(arg1, arg2, ..., argN) # Does not time function
some_function(arg1, arg2, ..., argN, verbose = True) # Times function
```
I would nevertheless like to duplicate the prior working of my functions, so that the working would be something more like:
```
some_function(arg1, arg2, ..., argN) # Does not time function
some_function(arg1, arg2, ..., argN, False) # Does not time function
some_function(arg1, arg2, ..., argN, True) # Times function
```
I guess this would require the decorator to count the number of arguments, know how many the original function will take, strip any in excess, pass the right number of them to the function... I'm uncertain though on how to tell python to do this... Is it possible? Is there a better way of achieving the same? | Though [inspect](http://docs.python.org/3.0/library/inspect.html) may get you a bit on the way, what you want is in general *not* possible:
```
def f(*args):
pass
```
Now how many arguments does `f` take? Since `*args` and `**kwargs` allow for an arbitrary number of arguments, there is no way to determine the number of arguments a function requires. In fact there are cases where the function really handles as many as there are thrown at it!
---
**Edit:** if you're willing to put up with `verbose` as a special keyword argument, you can do this:
```
import time
def timed(f):
def dec(*args, **kwargs):
verbose = kwargs.pop('verbose', False)
t = time.clock()
ret = f(*args, **kwargs)
if verbose:
print("%s executed in %ds" % (f.__name__, time.clock() - t))
return ret
return dec
@timed
def add(a, b):
return a + b
print(add(2, 2, verbose=True))
```
(Thanks [Alex Martelli](https://stackoverflow.com/questions/889088/function-decorators/889235#889235) for the `kwargs.pop` tip!) | +1 on Stephan202's answer, however (putting this in a separate answer since comments don't format code well!), the following bit of code in that answer:
```
verbose = False
if 'verbose' in kwargs:
verbose = True
del kwargs['verbose']
```
can be expressed much more clearly and concisely as:
```
verbose = kwargs.pop('verbose', False)
``` | Function Decorators | [
"",
"python",
"decorator",
"argument-passing",
""
] |
I have the following code:
```
def causes_exception(lamb):
try:
lamb()
return False
except:
return True
```
I was wondering if it came already in any built-in library?
/YGA
Edit: Thx for all the commentary. It's actually impossible to detect whether code causes an exception without running it -- otherwise you could solve the halting problem (raise an exception if the program halts). I just wanted a syntactically clean way to filter a set of identifiers for those where the code didn't except. | I'm not aware of that function, or anything similar, in the Python standard library.
It's rather misleading - if I saw it used, I might think it told you *without calling the function* whether the function could raise an exception. | No, as far as I know there is no such function in the standard library. How would it be useful? I mean, presumably you would use it like this:
```
if causes_exception(func):
# do something
else:
# do something else
```
But instead, you could just do
```
try:
func()
except SomeException:
# do something else
else:
# do something
``` | Does python have a "causes_exception()" function? | [
"",
"python",
""
] |
It's a big array, so i won't to strtolower every value. | Use [`preg_grep`](https://www.php.net/manual/en/function.preg-grep.php) with the case insensitivity flag “`i`”:
```
$result = preg_grep('/pattern/i', $array);
``` | Try this using the [`strcasecmp` function](http://docs.php.net/strcasecmp):
```
$array = array('foo', 'bar', 'baz', 'quux');
$needle = 'FOO';
$hit = false;
foreach ($array as $elem) {
if (is_string($elem) && strcasecmp($needle, $elem) == 0) {
$hit = true;
break;
}
}
var_dump($hit);
``` | How to use in_array() for caseless? | [
"",
"php",
""
] |
We have build a intranet application where users have to login to do certain tasks...
We have to make sure that no "application user" is logged in more than once at the same time.
So what I do at the moment is that I store the current asp .net session id in the database and then i compare at every page load wheter they are same or not. The session id is stored in the database when the user logs in.
But by using this kind check, there is always a database select needed. So I don't like this way very much. There must be a more elegant way to solve this, or?
We use ASP .Net2, C#..
Thanks in advance for any input
**[Info Update]**
I have already created a custom Membershipprovider and a custom Membershippuser.
The Membershipuser has a method called "StartSession(string sessionId)" which is used, when the user logs in.
The other method CheckSession(string sessionId) is used at every postback, and it compares the current session id with the session id stored in the database.
**[Update]**
Thanks everybody for your input. I will now use the cache to prevent permanent database access. I first thought that there is already a Class or something that is already handling this problem. | Your existing approach of storing this info in the DB is reasonable, it helps if things scale up.
However you could also use the System.Web.Caching.Cache object to track a users current session as well. If finding the info in the cache object fails fall back to reading it from the DB then place that info in the cache for the benefit of subsequent requests. | Whilst digging around for something related to this earlier today I ran across this article that may be of use:
> [Preventing Multiple Logins in ASP.NET (EggHead Cafe)](http://www.eggheadcafe.com/articles/20030418.asp) | How to prevent simultaneous login with same user on different pcs | [
"",
"c#",
"asp.net",
""
] |
Well here is the API I'm trying to use: <http://www.hotelscombined.com/api/LiveRates.asmx?op=HotelSearch>
Here is the code I've tried:
```
$client = new SoapClient('http://www.hotelscombined.com/api/LiveRates.asmx?WSDL');
echo '<pre>'; var_dump($client->__getFunctions()); echo '</pre><br /><br /><br />';
//since the above line returns the functions I am assuming everything is fine but until this point
try
{
$client->__soapCall('HotelSearch',
array(
'ApiKey' => 'THE_API_KEY_GOES_HERE', // note that in the actual code I put the API key in...
'UserID' => session_id(),
'UserAgent' => $_SERVER['HTTP_USER_AGENT'],
'UserIPAddress' => $_SERVER['REMOTE_ADDR'],
'HotelID' => '50563',
'Checkin' => '07/02/2009',
'Checkout' => '07/03/2009',
'Guests' => '2',
'Rooms' => '1',
'LanguageCode' => 'en',
'DisplayCurrency' => 'usd',
'TimeOutInSeconds' => '90'
)
);
}
catch (Exception $e)
{
echo $e->getMessage();
}
```
Anywho this throws an exception and echos the following:
```
Server was unable to process request. ---> Object reference not set to an instance of an object.
```
NOTE: I've never used SOAP before so it's possible I'm just doing something fundamentally wrong, even a small tip to get me in the right direction would be hugely appreciated
Tom Haigh suggested wrapping the values in another array which seems to be returning the same error message: (I always tried changing integers to be in integer form and the same with dates)
```
try
{
$client->__soapCall('HotelSearch',
array('request' =>
array(
'ApiKey' => 'THE_API_KEY_GOES_HERE', // note that in the actual code I put the API key in...
'UserID' => session_id(),
'UserAgent' => $_SERVER['HTTP_USER_AGENT'],
'UserIPAddress' => $_SERVER['REMOTE_ADDR'],
'HotelID' => '50563',
'Checkin' => '2009-07-02',
'Checkout' => '2009-07-03',
'Guests' => 2,
'Rooms' => 1,
'LanguageCode' => 'en',
'DisplayCurrency' => 'usd',
'TimeOutInSeconds' => 90
) )
);
}
catch (Exception $e)
{
echo $e->getMessage();
}
``` | I find when using PHP's SOAP implementation you end up wrapping everything up in more arrays than you think you need.
The below example seems to work, but also you need to format your date values correctly before it will work. I'm not sure of the best way of doing this - it might be that you can pass an Integer representing UNIX time and PHP will convert it for you.
```
$client->__soapCall('HotelSearch',
array(
array('request' =>
array(
'ApiKey' => 'THE_API_KEY_GOES_HERE', // note that in the actual code I put the API key in...
'UserID' => session_id(),
'UserAgent' => $_SERVER['HTTP_USER_AGENT'],
'UserIPAddress' => $_SERVER['REMOTE_ADDR'],
'HotelID' => '50563',
'Checkin' => '07/02/2009',
'Checkout' => '07/03/2009',
'Guests' => '2',
'Rooms' => '1',
'LanguageCode' => 'en',
'DisplayCurrency' => 'usd',
'TimeOutInSeconds' => '90'
)
)
)
);
``` | One thing that drove me crazy for days - double-check the names of your array elements (ApiKey, UserId, etc). Make sure the case is correct also. I wasted hours on a on an incorrectly cased 'm'. | Having trouble getting my head around SOAP in PHP | [
"",
"php",
"soap",
""
] |
How we can find out the next character of the entered one. For example, if I entered the character "b" then how do I get the answer "c"? | Try this:
```
char letter = 'c';
if (letter == 'z')
nextChar = 'a';
else if (letter == 'Z')
nextChar = 'A';
else
nextChar = (char)(((int)letter) + 1);
```
This way you have no trouble when the char is the last of the alphabet. | How about:
```
char first = 'c';
char nextChar = (char)((int) first + 1);
``` | How to find out next character alphabetically? | [
"",
"c#",
"char",
""
] |
Suppose I have the following `Event` model:
```
from django.db import models
import datetime
class Event(models.Model):
date_start = models.DateField()
date_end = models.DateField()
def is_over(self):
return datetime.date.today() > self.date_end
```
I want to test `Event.is_over()` by creating an Event that ends in the future (today + 1 or something), and stubbing the date and time so the system thinks we've reached that future date.
I'd like to be able to stub ALL system time objects as far as python is concerned. This includes `datetime.date.today()`, `datetime.datetime.now()`, and any other standard date/time objects.
What's the standard way to do this? | **EDIT**: Since my answer is the accepted answer here I'm updating it to let everyone know a better way has been created in the meantime, the freezegun library: <https://pypi.python.org/pypi/freezegun>. I use this in all my projects when I want to influence time in tests. Have a look at it.
**Original answer:**
Replacing internal stuff like this is always dangerous because it can have nasty side effects. So what you indeed want, is to have the monkey patching be as local as possible.
We use Michael Foord's excellent mock library: <http://www.voidspace.org.uk/python/mock/> that has a `@patch` decorator which patches certain functionality, but the monkey patch only lives in the scope of the testing function, and everything is automatically restored after the function runs out of its scope.
The only problem is that the internal `datetime` module is implemented in C, so by default you won't be able to monkey patch it. We fixed this by making our own simple implementation which *can* be mocked.
The total solution is something like this (the example is a validator function used within a Django project to validate that a date is in the future). Mind you I took this from a project but took out the non-important stuff, so things may not actually work when copy-pasting this, but you get the idea, I hope :)
First we define our own very simple implementation of `datetime.date.today` in a file called `utils/date.py`:
```
import datetime
def today():
return datetime.date.today()
```
Then we create the unittest for this validator in `tests.py`:
```
import datetime
import mock
from unittest2 import TestCase
from django.core.exceptions import ValidationError
from .. import validators
class ValidationTests(TestCase):
@mock.patch('utils.date.today')
def test_validate_future_date(self, today_mock):
# Pin python's today to returning the same date
# always so we can actually keep on unit testing in the future :)
today_mock.return_value = datetime.date(2010, 1, 1)
# A future date should work
validators.validate_future_date(datetime.date(2010, 1, 2))
# The mocked today's date should fail
with self.assertRaises(ValidationError) as e:
validators.validate_future_date(datetime.date(2010, 1, 1))
self.assertEquals([u'Date should be in the future.'], e.exception.messages)
# Date in the past should also fail
with self.assertRaises(ValidationError) as e:
validators.validate_future_date(datetime.date(2009, 12, 31))
self.assertEquals([u'Date should be in the future.'], e.exception.messages)
```
The final implementation looks like this:
```
from django.utils.translation import ugettext_lazy as _
from django.core.exceptions import ValidationError
from utils import date
def validate_future_date(value):
if value <= date.today():
raise ValidationError(_('Date should be in the future.'))
```
Hope this helps | You could write your own datetime module replacement class, implementing the methods and classes from datetime that you want to replace. For example:
```
import datetime as datetime_orig
class DatetimeStub(object):
"""A datetimestub object to replace methods and classes from
the datetime module.
Usage:
import sys
sys.modules['datetime'] = DatetimeStub()
"""
class datetime(datetime_orig.datetime):
@classmethod
def now(cls):
"""Override the datetime.now() method to return a
datetime one year in the future
"""
result = datetime_orig.datetime.now()
return result.replace(year=result.year + 1)
def __getattr__(self, attr):
"""Get the default implementation for the classes and methods
from datetime that are not replaced
"""
return getattr(datetime_orig, attr)
```
Let's put this in its own module we'll call `datetimestub.py`
Then, at the start of your test, you can do this:
```
import sys
import datetimestub
sys.modules['datetime'] = datetimestub.DatetimeStub()
```
Any subsequent import of the `datetime` module will then use the `datetimestub.DatetimeStub` instance, because when a module's name is used as a key in the `sys.modules` dictionary, the module will not be imported: the object at `sys.modules[module_name]` will be used instead. | Django unit testing with date/time-based objects | [
"",
"python",
"django",
"unit-testing",
"datetime",
"stub",
""
] |
I'm using the above mentioned Python lib to connect to a MySQL server. So far I've worked locally and all worked fine, until i realized I'll have to use my program in a network where all access goes through a proxy.
Does anyone now how I can set the connections managed by that lib to use a proxy?
Alternatively: do you know of another Python lib for MySQL that can handle this?
I also have no idea if the if the proxy server will allow access to the standard MySQL port or how I can trick it to allow it. Help on this is also welcomed. | I use [ssh tunneling](http://www.ssh.com/support/documentation/online/ssh/winhelp/32/Tunneling_Explained.html) for that kind of issues.
For example I am developing an application that connects to an oracle db.
In my code I write to connect to localhost and then from a shell I do:
```
ssh -L1521:localhost:1521 user@server.com
```
If you are in windows you can use [PuTTY](http://www.chiark.greenend.org.uk/~sgtatham/putty/) | there are a lot of different possibilities here. the only way you're going to get a definitive answer is to talk to the person that runs the proxy.
if this is a web app and the web server and the database serve are both on the other side of a proxy, then you won't need to connect to the mysql server at all since the web app will do it for you. | MySQLdb through proxy | [
"",
"python",
"mysql",
"proxy",
""
] |
I'm preparing to build a 2D scene graph for my game, and i would like to know whether i should use at it's root an interface or two or a couple of abstract classes. Here's my requirements:
* Base node item
+ needs to be able to store a matrix
+ also needs to be able to store a list
of child nodes
+ as well as a single parent node
* Transform node items
+ needs to have a Draw method (implementation is highly probable to be the same)
+ requires that the base node item be
implemented/derived from
* Drawable node item
+ needs to have a Draw method (implementation may be different)
+ requires that the base node item be
implemented/derived from and cannot
be implemented/derived from alongside
the transform node item
What scheme of base classes/interfaces should i use for this? | Jasonh covered the basics -- use the abstract class where you want to share code, otherwise use the interface.
I wan to add one point -- even if you go the abstract class route, I'd still recommend creating an interface as well. You never know when you'll want to have a subclass that acts like the others, but really needs to inherit another class for some reason. Abstract base classes are great to save implementation code. Interfaces are more flexible though, so unless there's a really good reason (ie. your testing reveals you can't take the performance hit of virtual method calls), use an interface as well as an abstract base class where it makes sense.
My general rule on this is: use interfaces to define the API, and use abstract base classes to allow implementations of the interface to share code. | Interfaces and abstract classes are used for two different things - interface are used for defining contract while abstract class are used to provide a base implementation and share common code. So you should definitly always use interfaces and sometimes (and I think your case is such a case) also abstract classes to avoid duplicating code.
So with interfaces only you will get the following.
```
class Transformation : INode, ITransformation { }
class GraphicsObject : INode, IGraphicsObject { }
```
I assume you can factor the common node specific code out into a base class.
```
abstarct class Node : INode { }
class Transformation : Node, ITransformation { }
class GraphicsObject : Node, IGraphicsObject { }
``` | Building a new hierarchy, use an abstract class or an interface? | [
"",
"c#",
"oop",
"scenegraph",
""
] |
I have to consume a Web Service that is written in Java by a 3rd party, generated with Axis I guess.
I'm using .Net Framework 3.5 SP1 and VS 2008.
I've made a Web Reference, as we used to make in .net 2.0, and pointed it to the [wsdl](https://servicoscomercialpta.bvfinanceira.com.br/gmp2/servicos?WSDL) of the service.
It worked perfectly with some methods of the service, but when I try to call a Method that takes an int as a parameter, the following exception is thrown:
```
JAXRPCTIE01: caught exception while handling request:
unexpected element type:
expected={http://schemas.xmlsoap.org/soap/encoding/}int,
actual={http://www.w3.org/2001/XMLSchema}int
```
I checked the wsdl and it defines five different Xml Schema Namespaces:
```
<definitions xmlns="http://schemas.xmlsoap.org/wsdl/"
xmlns:tns="urn:servicos/wsdlservicosgmp2"
xmlns:ns2="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:ns3="urn:servicos/typesservicosgmp2"
xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns:soap="http://schemas.xmlsoap.org/wsdl/soap/"
name="servicosgmp2"
targetNamespace="urn:servicos/wsdlservicosgmp2">
<schema xmlns="http://www.w3.org/2001/XMLSchema"
xmlns:tns="urn:servicos/typesservicosgmp2"
xmlns:soap11-enc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/"
targetNamespace="urn:servicos/typesservicosgmp2">
```
And the definition of the problematic method:
```
<message name="IWsServicosGMP2_buscaConvenio">
<part name="Integer_1" type="ns2:int" />
<part name="Integer_2" type="ns2:int" />
</message>
```
Anyone has a clue of what I have to do to solve this problem? | It seems the Java/AXIS web service is using SOAP (section 5) encoding. This is a throwback, and is very odd to see these days.
Where'd you get the web service? how long has it been running? Do you have the ability to change it? AXIS or AXIS2? What version? For AXIS1, anything from AXIS v1.1 onward should work ok, but I'd advise updating to v1.4. If possible move to AXIS2, and use v1.4. (Confusingly, AXIS and AXIS2 are at the same version number.)
Why does the Java side want to use SOAP encoding? Did the Java side take a ***WSDL first*** approach, or is this one of those dynamically-generated WSDL things?
[AXIS and .NET work together just fine](http://www.google.com/search?hl=en&rls=com.microsoft%3A*&q=AXIS+.net+interop), if you start with [WSDL+XSD first](http://www.mindreef.com/newsletter/newsletter-v6.html), and confine yourself to doc/lit webservices and confine your use of xmlschema to the less exotic pieces: primitives, and structures and arrays of same. You can nest to any level: arrays of structures containing arrays, structures containing arrays of structures, etc etc.
**Addendum**: If you start with your Java object model, and try to dynamically generate a wire-interface from it (eg, WSDL), you tend to get much worse interop, and you tend to think in terms of sending objects over the wire instead of messages, which can be harmful.
Things to avoid: lists, restrictions, substitution groups, and other wacky things. | I'm not sure if this will help but it may be worth a try. Have you tried adding a Service Reference (svcutil.exe wrapper) instead of Web reference (wsdl.exe wrapper)? | Problems consuming a Java/AXIS web service in a .Net Application | [
"",
"java",
".net",
"web-services",
"interop",
"wsdl",
""
] |
Before anyone flips out on me about singletons, I will say that in this instance it makes sense for me to have a singleton given the wide use of this object throughout my code and if someone has a better way short of DI I would like to hear but I would hope that this would not be the focus of this post, moreso helping solve it would be.
That being said here's the issue:
It seems after a given amount of time that I am losing a reference to my class scheduler and inside there is a timer tick that no longer fires. Is this because it is being used in a singleton fashion and once it loses a reference it is GC'd?
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
namespace MessageQueueInterface
{
public class Scheduler
{
private const int _interval = 1000;
private readonly Dictionary<DateTime, Action> _scheduledTasks = new Dictionary<DateTime, Action>();
private readonly Timer _mainTimer;
public Scheduler()
{
_mainTimer = new Timer();
_mainTimer.Interval = _interval;
_mainTimer.Tick += MainTimer_Tick;
_mainTimer.Start();
}
void MainTimer_Tick(object sender, EventArgs e)
{
CheckStatus();
}
public void Add(DateTime timeToFire, Action action)
{
lock (_scheduledTasks)
{
if (!_scheduledTasks.Keys.Contains(timeToFire))
{
_scheduledTasks.Add(timeToFire, action);
}
}
}
public void CheckStatus()
{
Dictionary<DateTime, Action> scheduledTasksToRemove = new Dictionary<DateTime, Action>();
lock (_scheduledTasks)
{
foreach (KeyValuePair<DateTime, Action> scheduledTask in _scheduledTasks)
{
if (DateTime.Now >= scheduledTask.Key)
{
scheduledTask.Value.Invoke();
scheduledTasksToRemove.Add(scheduledTask.Key, scheduledTask.Value);
}
}
}
foreach (KeyValuePair<DateTime, Action> pair in scheduledTasksToRemove)
{
_scheduledTasks.Remove(pair.Key);
}
}
}
}
```
it is accessed in the following way in other classes
```
ApplicationContext.Current.Scheduler.Add(DateTime.Now.AddSeconds(1), ResetBackColor);
```
`ApplicationContext` is my singleton
also i am aware that a datetime object is not the best KEY for a dictionary, but it suits my purposes here
here's the singleton
```
public class ApplicationContext
{
private static ApplicationContext _context;
private Scheduler _scheduler;
public Scheduler Scheduler
{
get { return _scheduler; }
}
private void SetProperties()
{
_scheduler = new Scheduler();
}
public static ApplicationContext Current
{
get
{
if (_context == null)
{
_context = new ApplicationContext();
_context.SetProperties();
}
return _context;
}
}
}
``` | The class that you posted doesn't appear to be your singleton class. That code would be more helpful.
In any event, yes, if the timer were to fall out of scope and be GC'ed, then it would stop firing the event. What is more likely is that the scheduler is immediately falling out of scope and there is just a delay between when that happens and when GC occurs.
Posting your singleton code would allow me or anyone else to give a more specific answer.
**Edit**
Given the simplicity of the singleton class, the only potential issue that jumps out at me is a race condition on the `Current` property. Given that you don't lock anything, then two threads accessing `Current` property at the same time when it's null could potentially end up with different references, and the last one that gets set would be the only one that has a reference whose scope would extend beyond the scope of the property getter itself.
I would recommend creating a simple sync `object` instance as a static member, then locking it in the getter. This should prevent that condition from cropping up.
As an aside, what's the purpose for the `SetProperties()` method rather than initializing the variable in a parameterless constructor or even at the point of declaration? Having a function like this allows for the possibility of creating a new `Scheduler` object and abandoning the existing one. | Are you saying the issue is that your global/static pointer to Scheduler() becomes null? If thats the case we'd need to see code that manipulates that reference to understand while it fails.
I do have some feedback though... Your calls to \_scheduledTasks.Remove() should happen within the lock, to prevent race conditions changing the list. Also your calls to scheduledTask.Value.Invoke() should happen outside the lock, to prevent someone from queueing another workitem within that lock when they implement Invoke. I would do this by moving due tasks to a list local to the stack before leaving the lock, then executing tasks from that list.
Then consider what happens if an Invoke() call throws an exception, if there are remaining tasks in the local list they may be leaked. The can be handled by catching/swallowing the exceptions, or only pulling 1 task out of the queue each time the lock is picked up. | Threading and Singletons | [
"",
"c#",
"multithreading",
"singleton",
"timer",
""
] |
I have a simple click and show, click and hide button, but when I click it, the page anchors at the top of the page. Is there anyway to prevent this? So that when I click the button, I stay at the same place in the browser?
My code is..
```
$('#reportThis').hide();
$('#flagThis').click(function () {
$('#reportThis').show("slow");
});
$('#submitFlag').click(function () {
$('#reportThis').hide("slow");
});
``` | Try this:
```
$('#reportThis').hide();
$('#flagThis').click(function (evt) {
$('#reportThis').show("slow");
evt.preventDefault();
});
$('#submitFlag').click(function (evt) {
$('#reportThis').hide("slow");
evt.preventDefault();
});
``` | You probably are binding this clicks to a <a> tag which has a default action. To prevent this you can use another tag like <div> or you can do this:
```
$('#flagThis').click(function (event) {
$('#reportThis').show("slow");
event.preventDefault();
});
``` | jQuery click brings me to top of page. But I want to stay where I am | [
"",
"javascript",
"jquery",
""
] |
Basically I'd like to bind function A to all inputs. Something like this:
```
$('input').bind('change', function() { bla bla bla });
```
And then later I would like to bind something different in addition like this:
```
$('#inputName').bind('change', function() { do additional processing..});
```
Is that possible? Does it work? Am I missing the syntax? Is that fine actually fine (meaning I have a bug elsewhere that's causing one of these not to bind)? | In your code, one is input, and the other inputName, is that a typo?
Searched, there is a [similar question](https://stackoverflow.com/questions/702352/many-event-handles-to-one-event-jquery) here.
```
$(document).ready(function() {
$("input").change(function() {
console.log("function1");
});
$("input").change(function() {
console.log("function2");
});
});
``` | The short answer to your question is YES.
If you wish to bind additional functionality to the change event of #inputName, your code sample should work.
If you wish to alter the function that handles the event you can unbind all handlers of the change event before you rebind any new event handlers like so...
```
$('#inputName').unbind('change');
```
but be careful... w/o trying this out I am unsure of any of the side affects. | Is it possible to bind two separate functions to the same event | [
"",
"javascript",
"jquery",
""
] |
Just to keep my sanity, I'm telling Spring to barf on circular references:
```
_context = new ClassPathXmlApplicationContext(getApplicationContextFiles(), false);
_context.setAllowCircularReferences(false);
_context.refresh();
_context.start();
```
The problem is that the resulting stack trace actually does look like barf :|
How can I get a simple output of a circular references, similar to:
```
Unresolved circular reference: [aBean->nextBean->otherBean->aBean]
```
? | If all your cycles are between registered components this may help (as far as I can recall you can't reference inner beans easily as they are not registered).
You can register a custom listener on events generated by the bean parsers, to do so extend the application context and override initBeanDefinitionReader(), in that method set your custom listener on the beanDefinitionReader using setEventListener (you'll need to cast to XmlBeanDefinitionReader).
The listener will be notified when ComponentDefinitions are registered and store them in a Map.
Once processing of the configuration is complete, you can then process the ComponentDefinitions to identify cycles using something similar to [JDepend](http://www.clarkware.com/software/JDepend.html)'s jdepend.framework.JavaPackage..
For each ComponentDefinition, iterate the getBeanDefinitions() and getBeanReferences() (and maybe getInnerBeanDefinitions()) and add create a "JavaPackage" for each definition and a dependency for each reference.
After processing each reference and declaration, you can then interrogate the JavaPackage-like objects and spit out the results of any that return true for containsCycle() | The approach I'd take is to write a script (probably in Python, though Groovy is probably also quite suitable) to do the following:
1. Parse the text of the bean graph dump to generate a directed graph of single dependencies of the form (A, B) indicating that B has a reference to A. Here A, B etc. are the nodes in the graph, and the (A, B) pairings are edges.
2. Run a topological sort on the graph. This removes nodes in several passes. There are numerous implementations in numerous languages. Pick one for your chosen scripting language, Google is your friend.
3. If there are any nodes left, they are your cycle (set of circular references).
It may sound a bit complicated, but actually it's not. I've solved similar problems using Python scripts many a time. | Getting human-readable output of Spring circular references | [
"",
"java",
"spring",
""
] |
Sometimes when reading others' C# code I see a method that will accept multiple enum values in a single parameter. I always thought it was kind of neat, but never looked into it.
Well, now I think I may have a need for it, but don't know how to
1. set up the method signature to accept this
2. work with the values in the method
3. define the enum
to achieve this sort of thing.
---
In my particular situation, I would like to use the System.DayOfWeek, which is defined as:
```
[Serializable]
[ComVisible(true)]
public enum DayOfWeek
{
Sunday = 0,
Monday = 1,
Tuesday = 2,
Wednesday = 3,
Thursday = 4,
Friday = 5,
Saturday = 6
}
```
I want to be able to pass one or more of the DayOfWeek values to my method. Will I be able to use this particular enum as it is? How do I do the 3 things listed above? | When you define the enum, just attribute it with [Flags], set values to powers of two, and it will work this way.
Nothing else changes, other than passing multiple values into a function.
For example:
```
[Flags]
enum DaysOfWeek
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64
}
public void RunOnDays(DaysOfWeek days)
{
bool isTuesdaySet = (days & DaysOfWeek.Tuesday) == DaysOfWeek.Tuesday;
if (isTuesdaySet)
//...
// Do your work here..
}
public void CallMethodWithTuesdayAndThursday()
{
this.RunOnDays(DaysOfWeek.Tuesday | DaysOfWeek.Thursday);
}
```
For more details, see [MSDN's documentation on Enumeration Types](http://msdn.microsoft.com/en-us/library/cc138362.aspx).
---
Edit in response to additions to question.
You won't be able to use that enum as is, unless you wanted to do something like pass it as an array/collection/params array. That would let you pass multiple values. The flags syntax requires the Enum to be specified as flags (or to bastardize the language in a way that's its not designed). | I think the more elegant solution is to use HasFlag():
```
[Flags]
public enum DaysOfWeek
{
Sunday = 1,
Monday = 2,
Tuesday = 4,
Wednesday = 8,
Thursday = 16,
Friday = 32,
Saturday = 64
}
public void RunOnDays(DaysOfWeek days)
{
bool isTuesdaySet = days.HasFlag(DaysOfWeek.Tuesday);
if (isTuesdaySet)
{
//...
}
}
public void CallMethodWithTuesdayAndThursday()
{
RunOnDays(DaysOfWeek.Tuesday | DaysOfWeek.Thursday);
}
``` | How do you pass multiple enum values in C#? | [
"",
"c#",
"enums",
""
] |
OK, so I'm working with a little regular expression—it's my first time, please, be gentle—and I've run into a problem where I can set a variable with it but if I try to do anything with that variable it causes problems.
Here's my script:
```
$(document).ready(function () {
var show_number;
var url_param;
$("a[rel=more]").live("click", function(){
url_param = $(this).attr("href").match(/show:[^/]+/i);
show_number = url_param.substr(5);
alert(show_number);
return false;
});
});
```
Now instead of showing the alert the way it should it just follows the link. However, if I get rid of the "show\_number" variable and set it to alert the "url\_param" everything goes fine.
I basically need to get what comes after the first five characters of that RegEx. I tried adding the substr() function directly to it but that didn't seem to help.
What am I doing wrong? | No, the problem is not with the backslash. Jacob is correct, it does not need quoting.
The problem is that indeed, match returns an array. Hence the following simple test case does NOT work.
```
<html>
<script type="text/javascript">
var a='show: something';
url_param = a.match(/show:[^/]+/i);
show_number = url_param.substring(5);
alert (show_number);
</script>
</html>
```
However, this second version DOES work.
```
<html>
<script type="text/javascript">
var a='show: something';
url_param = a.match(/show:[^/]+/i);
show_number = url_param[0].substring(5);
alert (show_number);
</script>
</html>
```
Even better is probably something explicit which handles whitespace, checks for start and end of string, and does a pattern match extraction.
```
<html>
<script type="text/javascript">
var a='show: something';
url_param = a.match(/^\s*show:\s*([^/]+)\s*$/i);
show_number = url_param[0].substring(5);
alert (show_number);
</script>
</html>
```
That's a bit more bullet-proof. | `match()` returns an array, not a string, so at a minimum you need something like this:
```
url_param = $(this).attr("href").match(/show:[^/]+/i);
if (url_param && url_param.length > 0) {
show_number = url_param[0].substr(5);
alert(show_number);
}
```
A neater way to get the piece of the URL after the "show:" is to use parentheses to capture that part of the URL, which will end up in `url_param[1]`:
```
url_param = $(this).attr("href").match(/show:([^/]+)/i);
if (url_param && url_param.length > 0) {
show_number = url_param[1];
alert(show_number);
}
``` | My RegEx is screwing up the rest of my javascript | [
"",
"javascript",
"jquery",
"regex",
"string",
""
] |
I have asked this [question](https://stackoverflow.com/questions/994117/using-first-with-a-generic-collection-through-reflection) about using the a Linq method that returns one object (First, Min, Max, etc) from of a generic collection.
I now want to be able to use linq's Except() method and I am not sure how to do it. Perhaps the answer is just in front on me but think I need help.
I have a generic method that fills in missing dates for a corresponding descriptive field. This method is declared as below:
```
public IEnumerable<T> FillInMissingDates<T>(IEnumerable<T> collection, string datePropertyName, string descriptionPropertyName)
{
Type type = typeof(T);
PropertyInfo dateProperty = type.GetProperty(datePropertyName);
PropertyInfo descriptionProperty = type.GetProperty(descriptionPropertyName);
...
}
```
What I want to accomplish is this. datePropertyName is the name of the date property I will use to fill in my date gaps (adding default object instances for the dates not already present in the collection). If I were dealing with a non-generic class, I would do something like this:
```
foreach (string description in descriptions)
{
var missingDates = allDates.Except(originalData.Where(d => d.Description == desc).Select(d => d.TransactionDate).ToList());
...
}
```
But how can I do the same using the generic method FillInMissingDates with the dateProperty and descriptionProperty properties resolved in runtime? | I think the best way would be to define an interface with all of the properties that you want to use in your method. Have the classes that the method may be used in implement this interface. Then, use a generic method and constrain the generic type to derive from the interface.
This example may not do exactly what you want -- it fills in missing dates for items in the list matching a description, but hopefully it will give you the basic idea.
```
public interface ITransactable
{
string Description { get; }
DateTime? TransactionDate { get; }
}
public class CompletedTransaction : ITransactable
{
...
}
// note conversion to extension method
public static void FillInMissingDates<T>( this IEnumerable<T> collection,
string match,
DateTime defaultDate )
where T : ITransactable
{
foreach (var trans in collection.Where( t => t.Description = match ))
{
if (!trans.TransactionDate.HasValue)
{
trans.TransactionDate = defaultDate;
}
}
}
```
You'll need to Cast your enumeration to ITransactable before invoking (at least until C# 4.0 comes out).
```
var list = new List<CompletedTransaction>();
list.Cast<ITransactable>()
.FillInMissingDates("description",DateTime.MinValue);
```
Alternatively, you could investigate using [Dynamic LINQ](http://weblogs.asp.net/scottgu/archive/2008/01/07/dynamic-linq-part-1-using-the-linq-dynamic-query-library.aspx) from the [VS2008 Samples](http://msdn.microsoft.com/en-us/vstudio/bb330936.aspx) collection. This would allow you to specify the name of a property if it's not consistent between classes. You'd probably still need to use reflection to set the property, however. | You could try this approach:
```
public IEnumerable<T> FillInMissingDates<T>(IEnumerable<T> collection,
Func<T, DateTime> dateProperty, Func<T, string> descriptionProperty, string desc)
{
return collection.Except(collection
.Where(d => descriptionProperty(d) == desc))
.Select(d => dateProperty(d));
}
```
This allows you to do things like:
```
someCollection.FillInMissingDates(o => o.CreatedDate, o => o.Description, "matching");
```
Note that you don't necessarily need the `Except()` call, and just have:
```
.. Where(d => descriptionProperty(d) != desc)
``` | Using Except() on a Generic collection | [
"",
"c#",
"linq",
"generics",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.